blob: 08d2d934ca74b261b035a0a4e335d9e3f1cf418d [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
jiabinc52b1ff2019-10-31 17:20:42 -070034#include <media/AudioContainers.h>
35#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070036#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070037#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080038#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080041#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070044#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010045#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080046#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080047#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080048#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080050#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070051#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070052#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_ns.h>
54#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070055#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070058#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080059#include <media/nbaio/AudioStreamOutSink.h>
60#include <media/nbaio/MonoPipe.h>
61#include <media/nbaio/MonoPipeReader.h>
62#include <media/nbaio/Pipe.h>
63#include <media/nbaio/PipeReader.h>
64#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080065#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080066
Mikhail Naganov2996f672019-04-18 12:29:59 -070067#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080068#include <powermanager/PowerManager.h>
69
Kevin Rocard7588ff42018-01-08 11:11:30 -080070#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070071#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080072
Eric Laurent81784c32012-11-19 14:55:58 -080073#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080074#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070075#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070076#include <mediautils/SchedulingPolicyService.h>
77#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080078
Eric Laurent81784c32012-11-19 14:55:58 -080079#ifdef ADD_BATTERY_DATA
80#include <media/IMediaPlayerService.h>
81#include <media/IMediaDeathNotifier.h>
82#endif
83
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070085#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080086#include <cpustats/ThreadCpuUsage.h>
87#endif
88
Glenn Kastenc05b8d72016-03-24 09:48:17 -070089#include "AutoPark.h"
90
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080091#include <pthread.h>
92#include "TypedLogger.h"
93
Eric Laurent81784c32012-11-19 14:55:58 -080094// ----------------------------------------------------------------------------
95
96// Note: the following macro is used for extremely verbose logging message. In
97// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
98// 0; but one side effect of this is to turn all LOGV's as well. Some messages
99// are so verbose that we want to suppress them even when we have ALOG_ASSERT
100// turned on. Do not uncomment the #def below unless you really know what you
101// are doing and want to see all of the extremely verbose messages.
102//#define VERY_VERY_VERBOSE_LOGGING
103#ifdef VERY_VERY_VERBOSE_LOGGING
104#define ALOGVV ALOGV
105#else
106#define ALOGVV(a...) do { } while(0)
107#endif
108
Andy Hung6770c6f2015-04-07 13:43:36 -0700109// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700110#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700111
Andy Hung6770c6f2015-04-07 13:43:36 -0700112template <typename T>
113static inline T min(const T& a, const T& b)
114{
115 return a < b ? a : b;
116}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700117
Eric Laurent81784c32012-11-19 14:55:58 -0800118namespace android {
119
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700120using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000121using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700122
Eric Laurent81784c32012-11-19 14:55:58 -0800123// retry counts for buffer fill timeout
124// 50 * ~20msecs = 1 second
125static const int8_t kMaxTrackRetries = 50;
126static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700127
Eric Laurent81784c32012-11-19 14:55:58 -0800128// allow less retry attempts on direct output thread.
129// direct outputs can be a scarce resource in audio hardware and should
130// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700131// Notes:
132// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
133// in case the data write is bursty for the AudioTrack. The application
134// should endeavor to write at least once every kMaxTrackRetriesDirectMs
135// to prevent an underrun situation. If the data is bursty, then
136// the application can also throttle the data sent to be even.
137// 2) For compressed audio data, any data present in the AudioTrack buffer
138// will be sent and reset the retry count. This delivers data as
139// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
140// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
141// of data to be available, then any remaining data is delivered.
142// This is required to ensure the last bit of data is delivered before underrun.
143//
144// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
145// or the size of the HAL period for proportional / linear PCM tracks.
146static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800147
148// don't warn about blocked writes or record buffer overflows more often than this
149static const nsecs_t kWarningThrottleNs = seconds(5);
150
151// RecordThread loop sleep time upon application overrun or audio HAL read error
152static const int kRecordThreadSleepUs = 5000;
153
Eric Laurent10351942014-05-08 18:49:52 -0700154// maximum time to wait in sendConfigEvent_l() for a status to be received
155static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800156
157// minimum sleep time for the mixer thread loop when tracks are active but in underrun
158static const uint32_t kMinThreadSleepTimeUs = 5000;
159// maximum divider applied to the active sleep time in the mixer thread loop
160static const uint32_t kMaxThreadSleepTimeShift = 2;
161
Andy Hung09a50072014-02-27 14:30:47 -0800162// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700163// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800164static const uint32_t kMinNormalSinkBufferSizeMs = 20;
165// maximum normal sink buffer size
166static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800167
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700168// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
169// FIXME This should be based on experimentally observed scheduling jitter
170static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
171
Eric Laurent972a1732013-09-04 09:42:59 -0700172// Offloaded output thread standby delay: allows track transition without going to standby
173static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
174
Eric Laurent51716182016-02-29 18:00:56 -0800175// Direct output thread minimum sleep time in idle or active(underrun) state
176static const nsecs_t kDirectMinSleepTimeUs = 10000;
177
Glenn Kasten1b291842016-07-18 14:55:21 -0700178// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
179// balance between power consumption and latency, and allows threads to be scheduled reliably
180// by the CFS scheduler.
181// FIXME Express other hardcoded references to 20ms with references to this constant and move
182// it appropriately.
183#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800184
Eric Laurent81784c32012-11-19 14:55:58 -0800185// Whether to use fast mixer
186static const enum {
187 FastMixer_Never, // never initialize or use: for debugging only
188 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
189 // normal mixer multiplier is 1
190 FastMixer_Static, // initialize if needed, then use all the time if initialized,
191 // multiplier is calculated based on min & max normal mixer buffer size
192 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
193 // multiplier is calculated based on min & max normal mixer buffer size
194 // FIXME for FastMixer_Dynamic:
195 // Supporting this option will require fixing HALs that can't handle large writes.
196 // For example, one HAL implementation returns an error from a large write,
197 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
198 // We could either fix the HAL implementations, or provide a wrapper that breaks
199 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
200} kUseFastMixer = FastMixer_Static;
201
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700202// Whether to use fast capture
203static const enum {
204 FastCapture_Never, // never initialize or use: for debugging only
205 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
206 FastCapture_Static, // initialize if needed, then use all the time if initialized
207} kUseFastCapture = FastCapture_Static;
208
Eric Laurent81784c32012-11-19 14:55:58 -0800209// Priorities for requestPriority
210static const int kPriorityAudioApp = 2;
211static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700212static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800213
Glenn Kastenea38ee72016-04-18 11:08:01 -0700214// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
215// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
216// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700217
218// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800219static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800220
Glenn Kasten03490092014-05-27 12:30:54 -0700221// The minimum and maximum allowed values
222static const int kFastTrackMultiplierMin = 1;
223static const int kFastTrackMultiplierMax = 2;
224
225// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
226static int sFastTrackMultiplier = kFastTrackMultiplier;
227
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700228// See Thread::readOnlyHeap().
229// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
230// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
231// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700232static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700233
Eric Laurent81784c32012-11-19 14:55:58 -0800234// ----------------------------------------------------------------------------
235
Andy Hungb68f5eb2019-12-03 16:49:17 -0800236// TODO: move all toString helpers to audio.h
237// under #ifdef __cplusplus #endif
238static std::string patchSinksToString(const struct audio_patch *patch)
239{
240 std::stringstream ss;
241 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700242 if (i > 0) {
243 ss << "|";
244 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800245 ss << "(" << toString(patch->sinks[i].ext.device.type)
246 << ", " << patch->sinks[i].ext.device.address << ")";
247 }
248 return ss.str();
249}
250
251static std::string patchSourcesToString(const struct audio_patch *patch)
252{
253 std::stringstream ss;
254 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700255 if (i > 0) {
256 ss << "|";
257 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800258 ss << "(" << toString(patch->sources[i].ext.device.type)
259 << ", " << patch->sources[i].ext.device.address << ")";
260 }
261 return ss.str();
262}
263
Glenn Kasten03490092014-05-27 12:30:54 -0700264static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
265
266static void sFastTrackMultiplierInit()
267{
268 char value[PROPERTY_VALUE_MAX];
269 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
270 char *endptr;
271 unsigned long ul = strtoul(value, &endptr, 0);
272 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
273 sFastTrackMultiplier = (int) ul;
274 }
275 }
276}
277
278// ----------------------------------------------------------------------------
279
Eric Laurent81784c32012-11-19 14:55:58 -0800280#ifdef ADD_BATTERY_DATA
281// To collect the amplifier usage
282static void addBatteryData(uint32_t params) {
283 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
284 if (service == NULL) {
285 // it already logged
286 return;
287 }
288
289 service->addBatteryData(params);
290}
291#endif
292
Andy Hung3f0c9022016-01-15 17:49:46 -0800293// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
294struct {
295 // call when you acquire a partial wakelock
296 void acquire(const sp<IBinder> &wakeLockToken) {
297 pthread_mutex_lock(&mLock);
298 if (wakeLockToken.get() == nullptr) {
299 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
300 } else {
301 if (mCount == 0) {
302 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
303 }
304 ++mCount;
305 }
306 pthread_mutex_unlock(&mLock);
307 }
308
309 // call when you release a partial wakelock.
310 void release(const sp<IBinder> &wakeLockToken) {
311 if (wakeLockToken.get() == nullptr) {
312 return;
313 }
314 pthread_mutex_lock(&mLock);
315 if (--mCount < 0) {
316 ALOGE("negative wakelock count");
317 mCount = 0;
318 }
319 pthread_mutex_unlock(&mLock);
320 }
321
322 // retrieves the boottime timebase offset from monotonic.
323 int64_t getBoottimeOffset() {
324 pthread_mutex_lock(&mLock);
325 int64_t boottimeOffset = mBoottimeOffset;
326 pthread_mutex_unlock(&mLock);
327 return boottimeOffset;
328 }
329
330 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
331 // and the selected timebase.
332 // Currently only TIMEBASE_BOOTTIME is allowed.
333 //
334 // This only needs to be called upon acquiring the first partial wakelock
335 // after all other partial wakelocks are released.
336 //
337 // We do an empirical measurement of the offset rather than parsing
338 // /proc/timer_list since the latter is not a formal kernel ABI.
339 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
340 int clockbase;
341 switch (timebase) {
342 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
343 clockbase = SYSTEM_TIME_BOOTTIME;
344 break;
345 default:
346 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
347 break;
348 }
349 // try three times to get the clock offset, choose the one
350 // with the minimum gap in measurements.
351 const int tries = 3;
352 nsecs_t bestGap, measured;
353 for (int i = 0; i < tries; ++i) {
354 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
355 const nsecs_t tbase = systemTime(clockbase);
356 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
357 const nsecs_t gap = tmono2 - tmono;
358 if (i == 0 || gap < bestGap) {
359 bestGap = gap;
360 measured = tbase - ((tmono + tmono2) >> 1);
361 }
362 }
363
364 // to avoid micro-adjusting, we don't change the timebase
365 // unless it is significantly different.
366 //
367 // Assumption: It probably takes more than toleranceNs to
368 // suspend and resume the device.
369 static int64_t toleranceNs = 10000; // 10 us
370 if (llabs(*offset - measured) > toleranceNs) {
371 ALOGV("Adjusting timebase offset old: %lld new: %lld",
372 (long long)*offset, (long long)measured);
373 *offset = measured;
374 }
375 }
376
377 pthread_mutex_t mLock;
378 int32_t mCount;
379 int64_t mBoottimeOffset;
380} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800381
382// ----------------------------------------------------------------------------
383// CPU Stats
384// ----------------------------------------------------------------------------
385
386class CpuStats {
387public:
388 CpuStats();
389 void sample(const String8 &title);
390#ifdef DEBUG_CPU_USAGE
391private:
392 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700393 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800394
Andy Hung16698b82018-08-01 10:48:38 -0700395 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800396
397 int mCpuNum; // thread's current CPU number
398 int mCpukHz; // frequency of thread's current CPU in kHz
399#endif
400};
401
402CpuStats::CpuStats()
403#ifdef DEBUG_CPU_USAGE
404 : mCpuNum(-1), mCpukHz(-1)
405#endif
406{
407}
408
Glenn Kasten0f11b512014-01-31 16:18:54 -0800409void CpuStats::sample(const String8 &title
410#ifndef DEBUG_CPU_USAGE
411 __unused
412#endif
413 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800414#ifdef DEBUG_CPU_USAGE
415 // get current thread's delta CPU time in wall clock ns
416 double wcNs;
417 bool valid = mCpuUsage.sampleAndEnable(wcNs);
418
419 // record sample for wall clock statistics
420 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700421 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800422 }
423
424 // get the current CPU number
425 int cpuNum = sched_getcpu();
426
427 // get the current CPU frequency in kHz
428 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
429
430 // check if either CPU number or frequency changed
431 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
432 mCpuNum = cpuNum;
433 mCpukHz = cpukHz;
434 // ignore sample for purposes of cycles
435 valid = false;
436 }
437
438 // if no change in CPU number or frequency, then record sample for cycle statistics
439 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700440 const double cycles = wcNs * cpukHz * 0.000001;
441 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800442 }
443
Eric Tan5b13ff82018-07-27 11:20:17 -0700444 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800445 // mCpuUsage.elapsed() is expensive, so don't call it every loop
446 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700447 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800448 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700449 const double perLoop = elapsed / (double) n;
450 const double perLoop100 = perLoop * 0.01;
451 const double perLoop1k = perLoop * 0.001;
452 const double mean = mWcStats.getMean();
453 const double stddev = mWcStats.getStdDev();
454 const double minimum = mWcStats.getMin();
455 const double maximum = mWcStats.getMax();
456 const double meanCycles = mHzStats.getMean();
457 const double stddevCycles = mHzStats.getStdDev();
458 const double minCycles = mHzStats.getMin();
459 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800460 mCpuUsage.resetElapsed();
461 mWcStats.reset();
462 mHzStats.reset();
463 ALOGD("CPU usage for %s over past %.1f secs\n"
464 " (%u mixer loops at %.1f mean ms per loop):\n"
465 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
466 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
467 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
468 title.string(),
469 elapsed * .000000001, n, perLoop * .000001,
470 mean * .001,
471 stddev * .001,
472 minimum * .001,
473 maximum * .001,
474 mean / perLoop100,
475 stddev / perLoop100,
476 minimum / perLoop100,
477 maximum / perLoop100,
478 meanCycles / perLoop1k,
479 stddevCycles / perLoop1k,
480 minCycles / perLoop1k,
481 maxCycles / perLoop1k);
482
483 }
484 }
485#endif
486};
487
488// ----------------------------------------------------------------------------
489// ThreadBase
490// ----------------------------------------------------------------------------
491
Glenn Kasten97b7b752014-09-28 13:04:24 -0700492// static
493const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
494{
495 switch (type) {
496 case MIXER:
497 return "MIXER";
498 case DIRECT:
499 return "DIRECT";
500 case DUPLICATING:
501 return "DUPLICATING";
502 case RECORD:
503 return "RECORD";
504 case OFFLOAD:
505 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700506 case MMAP_PLAYBACK:
507 return "MMAP_PLAYBACK";
508 case MMAP_CAPTURE:
509 return "MMAP_CAPTURE";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700510 default:
511 return "unknown";
512 }
513}
514
Eric Laurent81784c32012-11-19 14:55:58 -0800515AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700516 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800517 : Thread(false /*canCallJava*/),
518 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700519 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700520 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
521 isOut),
522 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700523 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800524 // are set by PlaybackThread::readOutputParameters_l() or
525 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700526 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700527 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700528 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800529 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700530 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800531 mSystemReady(systemReady),
532 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800533{
Andy Hungcf10d742020-04-28 15:38:24 -0700534 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700535 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800536}
537
538AudioFlinger::ThreadBase::~ThreadBase()
539{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700540 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700541 mConfigEvents.clear();
542
Eric Laurent81784c32012-11-19 14:55:58 -0800543 // do not lock the mutex in destructor
544 releaseWakeLock_l();
545 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800546 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800547 binder->unlinkToDeath(mDeathRecipient);
548 }
Andy Hungd0979812019-02-21 15:51:44 -0800549
550 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800551}
552
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700553status_t AudioFlinger::ThreadBase::readyToRun()
554{
555 status_t status = initCheck();
556 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800557 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700558 } else {
559 ALOGE("No working audio driver found.");
560 }
561 return status;
562}
563
Eric Laurent81784c32012-11-19 14:55:58 -0800564void AudioFlinger::ThreadBase::exit()
565{
566 ALOGV("ThreadBase::exit");
567 // do any cleanup required for exit to succeed
568 preExit();
569 {
570 // This lock prevents the following race in thread (uniprocessor for illustration):
571 // if (!exitPending()) {
572 // // context switch from here to exit()
573 // // exit() calls requestExit(), what exitPending() observes
574 // // exit() calls signal(), which is dropped since no waiters
575 // // context switch back from exit() to here
576 // mWaitWorkCV.wait(...);
577 // // now thread is hung
578 // }
579 AutoMutex lock(mLock);
580 requestExit();
581 mWaitWorkCV.broadcast();
582 }
583 // When Thread::requestExitAndWait is made virtual and this method is renamed to
584 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
585 requestExitAndWait();
586}
587
588status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
589{
Eric Laurent81784c32012-11-19 14:55:58 -0800590 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
591 Mutex::Autolock _l(mLock);
592
Eric Laurent10351942014-05-08 18:49:52 -0700593 return sendSetParameterConfigEvent_l(keyValuePairs);
594}
595
596// sendConfigEvent_l() must be called with ThreadBase::mLock held
597// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
598status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
599{
600 status_t status = NO_ERROR;
601
Eric Laurent72e3f392015-05-20 14:43:50 -0700602 if (event->mRequiresSystemReady && !mSystemReady) {
603 event->mWaitStatus = false;
604 mPendingConfigEvents.add(event);
605 return status;
606 }
Eric Laurent10351942014-05-08 18:49:52 -0700607 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700608 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800609 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700610 mLock.unlock();
611 {
612 Mutex::Autolock _l(event->mLock);
613 while (event->mWaitStatus) {
614 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
615 event->mStatus = TIMED_OUT;
616 event->mWaitStatus = false;
617 }
618 }
619 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800620 }
Eric Laurent10351942014-05-08 18:49:52 -0700621 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800622 return status;
623}
624
Eric Laurent09f1ed22019-04-24 17:45:17 -0700625void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
626 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800627{
628 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700629 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800630}
631
632// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700633void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
634 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800635{
Andy Hungd0979812019-02-21 15:51:44 -0800636 // The audio statistics history is exponentially weighted to forget events
637 // about five or more seconds in the past. In order to have
638 // crisper statistics for mediametrics, we reset the statistics on
639 // an IoConfigEvent, to reflect different properties for a new device.
640 mIoJitterMs.reset();
641 mLatencyMs.reset();
642 mProcessTimeMs.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100643 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800644
Eric Laurent09f1ed22019-04-24 17:45:17 -0700645 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700646 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800647}
648
Mikhail Naganov83f04272017-02-07 10:45:09 -0800649void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700650{
651 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800652 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700653}
654
Eric Laurent81784c32012-11-19 14:55:58 -0800655// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800656void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
657 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800658{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800659 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700660 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800661}
662
Eric Laurent10351942014-05-08 18:49:52 -0700663// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
664status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800665{
Andy Hung2ddee192015-12-18 17:34:44 -0800666 sp<ConfigEvent> configEvent;
667 AudioParameter param(keyValuePair);
668 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700669 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800670 setMasterMono_l(value != 0);
671 if (param.size() == 1) {
672 return NO_ERROR; // should be a solo parameter - we don't pass down
673 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700674 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800675 configEvent = new SetParameterConfigEvent(param.toString());
676 } else {
677 configEvent = new SetParameterConfigEvent(keyValuePair);
678 }
Eric Laurent10351942014-05-08 18:49:52 -0700679 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700680}
681
Eric Laurent1c333e22014-05-20 10:48:17 -0700682status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
683 const struct audio_patch *patch,
684 audio_patch_handle_t *handle)
685{
686 Mutex::Autolock _l(mLock);
687 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
688 status_t status = sendConfigEvent_l(configEvent);
689 if (status == NO_ERROR) {
690 CreateAudioPatchConfigEventData *data =
691 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
692 *handle = data->mHandle;
693 }
694 return status;
695}
696
697status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
698 const audio_patch_handle_t handle)
699{
700 Mutex::Autolock _l(mLock);
701 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
702 return sendConfigEvent_l(configEvent);
703}
704
jiabinc52b1ff2019-10-31 17:20:42 -0700705status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
706 const DeviceDescriptorBaseVector& outDevices)
707{
708 if (type() != RECORD) {
709 // The update out device operation is only for record thread.
710 return INVALID_OPERATION;
711 }
712 Mutex::Autolock _l(mLock);
713 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
714 return sendConfigEvent_l(configEvent);
715}
716
Eric Laurentec376dc2021-04-08 20:41:22 +0200717void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
718{
719 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
720 sp<ConfigEvent> configEvent =
721 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
722 sendConfigEvent_l(configEvent);
723}
Eric Laurent1c333e22014-05-20 10:48:17 -0700724
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700725// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700726void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700727{
Eric Laurent10351942014-05-08 18:49:52 -0700728 bool configChanged = false;
729
Eric Laurent81784c32012-11-19 14:55:58 -0800730 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700731 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700732 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800733 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700734 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700735 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700736 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
737 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800738 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700739 true /*asynchronous*/);
740 if (err != 0) {
741 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700742 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700743 }
744 } break;
745 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700746 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700747 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700748 } break;
749 case CFG_EVENT_SET_PARAMETER: {
750 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
751 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
752 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700753 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
754 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700755 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700756 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700757 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700758 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700759 CreateAudioPatchConfigEventData *data =
760 (CreateAudioPatchConfigEventData *)event->mData.get();
761 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700762 const DeviceTypeSet newDevices = getDeviceTypes();
763 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
764 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
765 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700766 } break;
767 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700768 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700769 ReleaseAudioPatchConfigEventData *data =
770 (ReleaseAudioPatchConfigEventData *)event->mData.get();
771 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700772 const DeviceTypeSet newDevices = getDeviceTypes();
773 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
774 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
775 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
776 } break;
777 case CFG_EVENT_UPDATE_OUT_DEVICE: {
778 UpdateOutDevicesConfigEventData *data =
779 (UpdateOutDevicesConfigEventData *)event->mData.get();
780 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700781 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200782 case CFG_EVENT_RESIZE_BUFFER: {
783 ResizeBufferConfigEventData *data =
784 (ResizeBufferConfigEventData *)event->mData.get();
785 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
786 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700787 default:
Eric Laurent10351942014-05-08 18:49:52 -0700788 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700789 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800790 }
Eric Laurent10351942014-05-08 18:49:52 -0700791 {
792 Mutex::Autolock _l(event->mLock);
793 if (event->mWaitStatus) {
794 event->mWaitStatus = false;
795 event->mCond.signal();
796 }
797 }
798 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
799 }
800
801 if (configChanged) {
802 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800803 }
Eric Laurent81784c32012-11-19 14:55:58 -0800804}
805
Marco Nelissenb2208842014-02-07 14:00:50 -0800806String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
807 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700808 const audio_channel_representation_t representation =
809 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700810
811 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800812 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700813 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
814 if (output) {
815 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
816 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
817 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700818 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700819 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
820 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
821 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
822 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
823 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
824 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
825 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
826 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
827 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
828 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
829 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
830 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700831 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
832 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
833 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
834 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
835 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
836 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
837 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700838 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700839 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
840 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700841 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
842 } else {
843 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
844 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
845 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
846 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
847 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
848 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
849 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
850 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
851 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
852 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
853 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
854 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700855 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
856 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
857 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700858 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700859 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
860 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700861 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
862 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
863 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
864 }
865 const int len = s.length();
866 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700867 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700868 s.unlockBuffer(len - 2); // remove trailing ", "
869 }
870 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800871 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700872 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
873 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
874 return s;
875 default:
876 s.appendFormat("unknown mask, representation:%d bits:%#x",
877 representation, audio_channel_mask_get_bits(mask));
878 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800879 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800880}
881
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700882void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800883{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800884 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
885 this, mThreadName, getTid(), type(), threadTypeToString(type()));
886
Eric Laurent81784c32012-11-19 14:55:58 -0800887 bool locked = AudioFlinger::dumpTryLock(mLock);
888 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800889 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800890 }
891
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700892 dumpBase_l(fd, args);
893 dumpInternals_l(fd, args);
894 dumpTracks_l(fd, args);
895 dumpEffectChains_l(fd, args);
896
897 if (locked) {
898 mLock.unlock();
899 }
900
901 dprintf(fd, " Local log:\n");
902 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
903}
904
905void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
906{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700907 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700908 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700909 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700910 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700911 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700912 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700913 dprintf(fd, " Channel count: %u\n", mChannelCount);
914 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800915 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700916 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700917 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700918 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800919 size_t numConfig = mConfigEvents.size();
920 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700921 const size_t SIZE = 256;
922 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800923 for (size_t i = 0; i < numConfig; i++) {
924 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700925 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800926 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700927 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800928 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700929 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800930 }
Andy Hung293558a2017-03-21 12:19:20 -0700931 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700932 dprintf(fd, " Output devices: %s (%s)\n",
933 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
934 dprintf(fd, " Input device: %#x (%s)\n",
935 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800936 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800937
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700938 // Dump timestamp statistics for the Thread types that support it.
939 if (mType == RECORD
940 || mType == MIXER
941 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700942 || mType == DIRECT
943 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700944 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700945 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700946 }
947
Andy Hung446f4df2019-02-21 12:26:41 -0800948 if (mLastIoBeginNs > 0) { // MMAP may not set this
949 dprintf(fd, " Last %s occurred (msecs): %lld\n",
950 isOutput() ? "write" : "read",
951 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
952 }
953
954 if (mProcessTimeMs.getN() > 0) {
955 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
956 }
957
958 if (mIoJitterMs.getN() > 0) {
959 dprintf(fd, " Hal %s jitter ms stats: %s\n",
960 isOutput() ? "write" : "read",
961 mIoJitterMs.toString().c_str());
962 }
963
Andy Hunge6c37112019-02-26 17:38:10 -0800964 if (mLatencyMs.getN() > 0) {
965 dprintf(fd, " Threadloop %s latency stats: %s\n",
966 isOutput() ? "write" : "read",
967 mLatencyMs.toString().c_str());
968 }
Eric Laurent81784c32012-11-19 14:55:58 -0800969}
970
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700971void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800972{
973 const size_t SIZE = 256;
974 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800975
Marco Nelissenb2208842014-02-07 14:00:50 -0800976 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000977 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800978 write(fd, buffer, strlen(buffer));
979
Marco Nelissenb2208842014-02-07 14:00:50 -0800980 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800981 sp<EffectChain> chain = mEffectChains[i];
982 if (chain != 0) {
983 chain->dump(fd, args);
984 }
985 }
986}
987
Andy Hungdae27702016-10-31 14:01:16 -0700988void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800989{
990 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700991 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800992}
993
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100994String16 AudioFlinger::ThreadBase::getWakeLockTag()
995{
996 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800997 case MIXER:
998 return String16("AudioMix");
999 case DIRECT:
1000 return String16("AudioDirectOut");
1001 case DUPLICATING:
1002 return String16("AudioDup");
1003 case RECORD:
1004 return String16("AudioIn");
1005 case OFFLOAD:
1006 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001007 case MMAP_PLAYBACK:
1008 return String16("MmapPlayback");
1009 case MMAP_CAPTURE:
1010 return String16("MmapCapture");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001011 default:
1012 ALOG_ASSERT(false);
1013 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001014 }
1015}
1016
Andy Hungdae27702016-10-31 14:01:16 -07001017void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001018{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001019 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001020 if (mPowerManager != 0) {
1021 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001022 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001023 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1024 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001025 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001026 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001027 {} /* workSource */,
1028 {} /* historyTag */);
1029 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001030 mWakeLockToken = binder;
1031 }
Chris Ye6597d732020-02-28 22:38:25 -08001032 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001033 }
Wei Jia3f273d12015-11-24 09:06:49 -08001034
Andy Hung3f0c9022016-01-15 17:49:46 -08001035 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001036 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1037 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001038}
1039
1040void AudioFlinger::ThreadBase::releaseWakeLock()
1041{
1042 Mutex::Autolock _l(mLock);
1043 releaseWakeLock_l();
1044}
1045
1046void AudioFlinger::ThreadBase::releaseWakeLock_l()
1047{
Andy Hung3f0c9022016-01-15 17:49:46 -08001048 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001049 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001050 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001051 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001052 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001053 }
1054 mWakeLockToken.clear();
1055 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001056}
1057
1058void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001059 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001060 // use checkService() to avoid blocking if power service is not up yet
1061 sp<IBinder> binder =
1062 defaultServiceManager()->checkService(String16("power"));
1063 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001064 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001065 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001066 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001067 binder->linkToDeath(mDeathRecipient);
1068 }
1069 }
1070}
1071
Andy Hungd01b0f12016-11-07 16:10:30 -08001072void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001073 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001074
1075#if !LOG_NDEBUG
1076 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001077 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001078 s << uid << " ";
1079 }
1080 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1081#endif
1082
Andy Hung438e7572015-12-14 15:51:17 -08001083 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1084 if (mSystemReady) {
1085 ALOGE("no wake lock to update, but system ready!");
1086 } else {
1087 ALOGW("no wake lock to update, system not ready yet");
1088 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 return;
1090 }
1091 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001092 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001093 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1094 mWakeLockToken, uidsAsInt);
1095 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001096 }
1097}
1098
Eric Laurent81784c32012-11-19 14:55:58 -08001099void AudioFlinger::ThreadBase::clearPowerManager()
1100{
1101 Mutex::Autolock _l(mLock);
1102 releaseWakeLock_l();
1103 mPowerManager.clear();
1104}
1105
jiabinc52b1ff2019-10-31 17:20:42 -07001106void AudioFlinger::ThreadBase::updateOutDevices(
1107 const DeviceDescriptorBaseVector& outDevices __unused)
1108{
1109 ALOGE("%s should only be called in RecordThread", __func__);
1110}
1111
Eric Laurentec376dc2021-04-08 20:41:22 +02001112void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1113{
1114 ALOGE("%s should only be called in RecordThread", __func__);
1115}
1116
Glenn Kasten0f11b512014-01-31 16:18:54 -08001117void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001118{
1119 sp<ThreadBase> thread = mThread.promote();
1120 if (thread != 0) {
1121 thread->clearPowerManager();
1122 }
1123 ALOGW("power manager service died !!!");
1124}
1125
Eric Laurent81784c32012-11-19 14:55:58 -08001126void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001127 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 sp<EffectChain> chain = getEffectChain_l(sessionId);
1130 if (chain != 0) {
1131 if (type != NULL) {
1132 chain->setEffectSuspended_l(type, suspend);
1133 } else {
1134 chain->setEffectSuspendedAll_l(suspend);
1135 }
1136 }
1137
1138 updateSuspendedSessions_l(type, suspend, sessionId);
1139}
1140
1141void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1142{
1143 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1144 if (index < 0) {
1145 return;
1146 }
1147
1148 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1149 mSuspendedSessions.valueAt(index);
1150
1151 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001152 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001153 for (int j = 0; j < desc->mRefCount; j++) {
1154 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1155 chain->setEffectSuspendedAll_l(true);
1156 } else {
1157 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1158 desc->mType.timeLow);
1159 chain->setEffectSuspended_l(&desc->mType, true);
1160 }
1161 }
1162 }
1163}
1164
1165void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1166 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001167 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001168{
1169 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1170
1171 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1172
1173 if (suspend) {
1174 if (index >= 0) {
1175 sessionEffects = mSuspendedSessions.valueAt(index);
1176 } else {
1177 mSuspendedSessions.add(sessionId, sessionEffects);
1178 }
1179 } else {
1180 if (index < 0) {
1181 return;
1182 }
1183 sessionEffects = mSuspendedSessions.valueAt(index);
1184 }
1185
1186
1187 int key = EffectChain::kKeyForSuspendAll;
1188 if (type != NULL) {
1189 key = type->timeLow;
1190 }
1191 index = sessionEffects.indexOfKey(key);
1192
1193 sp<SuspendedSessionDesc> desc;
1194 if (suspend) {
1195 if (index >= 0) {
1196 desc = sessionEffects.valueAt(index);
1197 } else {
1198 desc = new SuspendedSessionDesc();
1199 if (type != NULL) {
1200 desc->mType = *type;
1201 }
1202 sessionEffects.add(key, desc);
1203 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1204 }
1205 desc->mRefCount++;
1206 } else {
1207 if (index < 0) {
1208 return;
1209 }
1210 desc = sessionEffects.valueAt(index);
1211 if (--desc->mRefCount == 0) {
1212 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1213 sessionEffects.removeItemsAt(index);
1214 if (sessionEffects.isEmpty()) {
1215 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1216 sessionId);
1217 mSuspendedSessions.removeItem(sessionId);
1218 }
1219 }
1220 }
1221 if (!sessionEffects.isEmpty()) {
1222 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1223 }
1224}
1225
Eric Laurent6b446ce2019-12-13 10:56:31 -08001226void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1227 audio_session_t sessionId,
1228 bool threadLocked) {
1229 if (!threadLocked) {
1230 mLock.lock();
1231 }
Eric Laurent81784c32012-11-19 14:55:58 -08001232
Eric Laurent81784c32012-11-19 14:55:58 -08001233 if (mType != RECORD) {
1234 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1235 // another session. This gives the priority to well behaved effect control panels
1236 // and applications not using global effects.
1237 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1238 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001239 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001240 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1241 }
1242 }
1243
Eric Laurent6b446ce2019-12-13 10:56:31 -08001244 if (!threadLocked) {
1245 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001246 }
1247}
1248
Eric Laurent4c415062016-06-17 16:14:16 -07001249// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1250status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1251 const effect_descriptor_t *desc, audio_session_t sessionId)
1252{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001253 // No global output effect sessions on record threads
1254 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1255 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001256 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1257 desc->name, mThreadName);
1258 return BAD_VALUE;
1259 }
1260 // only pre processing effects on record thread
1261 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1262 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1263 desc->name, mThreadName);
1264 return BAD_VALUE;
1265 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001266
1267 // always allow effects without processing load or latency
1268 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1269 return NO_ERROR;
1270 }
1271
Eric Laurent4c415062016-06-17 16:14:16 -07001272 audio_input_flags_t flags = mInput->flags;
1273 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1274 if (flags & AUDIO_INPUT_FLAG_RAW) {
1275 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1276 desc->name, mThreadName);
1277 return BAD_VALUE;
1278 }
1279 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1280 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1281 desc->name, mThreadName);
1282 return BAD_VALUE;
1283 }
1284 }
jiabineb3bda02020-06-30 14:07:03 -07001285
1286 if (EffectModule::isHapticGenerator(&desc->type)) {
1287 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1288 return BAD_VALUE;
1289 }
Eric Laurent4c415062016-06-17 16:14:16 -07001290 return NO_ERROR;
1291}
1292
1293// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1294status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1295 const effect_descriptor_t *desc, audio_session_t sessionId)
1296{
1297 // no preprocessing on playback threads
1298 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1299 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1300 " thread %s", desc->name, mThreadName);
1301 return BAD_VALUE;
1302 }
1303
Eric Laurent3e4de772017-07-16 16:55:08 -07001304 // always allow effects without processing load or latency
1305 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1306 return NO_ERROR;
1307 }
1308
jiabineb3bda02020-06-30 14:07:03 -07001309 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1310 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1311 __func__);
1312 return BAD_VALUE;
1313 }
1314
Eric Laurent4c415062016-06-17 16:14:16 -07001315 switch (mType) {
1316 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001317#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001318 // Reject any effect on mixer multichannel sinks.
1319 // TODO: fix both format and multichannel issues with effects.
1320 if (mChannelCount != FCC_2) {
1321 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1322 " thread %s", desc->name, mChannelCount, mThreadName);
1323 return BAD_VALUE;
1324 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001325#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001326 audio_output_flags_t flags = mOutput->flags;
1327 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1328 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1329 // global effects are applied only to non fast tracks if they are SW
1330 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1331 break;
1332 }
1333 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1334 // only post processing on output stage session
1335 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1336 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1337 " on output stage session", desc->name);
1338 return BAD_VALUE;
1339 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001340 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1341 // only post processing on output stage session
1342 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1343 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1344 " on device session", desc->name);
1345 return BAD_VALUE;
1346 }
Eric Laurent4c415062016-06-17 16:14:16 -07001347 } else {
1348 // no restriction on effects applied on non fast tracks
1349 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1350 break;
1351 }
1352 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001353
Eric Laurent4c415062016-06-17 16:14:16 -07001354 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1355 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1356 desc->name);
1357 return BAD_VALUE;
1358 }
1359 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1360 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1361 " in fast mode", desc->name);
1362 return BAD_VALUE;
1363 }
1364 }
1365 } break;
1366 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001367 // nothing actionable on offload threads, if the effect:
1368 // - is offloadable: the effect can be created
1369 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1370 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001371 break;
1372 case DIRECT:
1373 // Reject any effect on Direct output threads for now, since the format of
1374 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1375 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1376 desc->name, mThreadName);
1377 return BAD_VALUE;
1378 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001379#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001380 // Reject any effect on mixer multichannel sinks.
1381 // TODO: fix both format and multichannel issues with effects.
1382 if (mChannelCount != FCC_2) {
1383 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1384 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1385 return BAD_VALUE;
1386 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001387#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001388 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001389 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1390 " thread %s", desc->name, mThreadName);
1391 return BAD_VALUE;
1392 }
1393 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1394 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1395 " DUPLICATING thread %s", desc->name, mThreadName);
1396 return BAD_VALUE;
1397 }
1398 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1399 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1400 " DUPLICATING thread %s", desc->name, mThreadName);
1401 return BAD_VALUE;
1402 }
1403 break;
1404 default:
1405 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1406 }
1407
1408 return NO_ERROR;
1409}
1410
Eric Laurent81784c32012-11-19 14:55:58 -08001411// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1412sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1413 const sp<AudioFlinger::Client>& client,
1414 const sp<IEffectClient>& effectClient,
1415 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001416 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001417 effect_descriptor_t *desc,
1418 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001419 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001420 bool pinned,
1421 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001422{
1423 sp<EffectModule> effect;
1424 sp<EffectHandle> handle;
1425 status_t lStatus;
1426 sp<EffectChain> chain;
1427 bool chainCreated = false;
1428 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001429 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001430
1431 lStatus = initCheck();
1432 if (lStatus != NO_ERROR) {
1433 ALOGW("createEffect_l() Audio driver not initialized.");
1434 goto Exit;
1435 }
1436
Eric Laurent81784c32012-11-19 14:55:58 -08001437 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1438
1439 { // scope for mLock
1440 Mutex::Autolock _l(mLock);
1441
Eric Laurent4c415062016-06-17 16:14:16 -07001442 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001443 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001444 goto Exit;
1445 }
1446
Eric Laurent81784c32012-11-19 14:55:58 -08001447 // check for existing effect chain with the requested audio session
1448 chain = getEffectChain_l(sessionId);
1449 if (chain == 0) {
1450 // create a new chain for this session
1451 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1452 chain = new EffectChain(this, sessionId);
1453 addEffectChain_l(chain);
1454 chain->setStrategy(getStrategyForSession_l(sessionId));
1455 chainCreated = true;
1456 } else {
1457 effect = chain->getEffectFromDesc_l(desc);
1458 }
1459
1460 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1461
1462 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001463 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001464 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001465 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001466 if (lStatus != NO_ERROR) {
1467 goto Exit;
1468 }
1469 effectCreated = true;
1470
jiabinc52b1ff2019-10-31 17:20:42 -07001471 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001472 effect->setDevices(outDeviceTypeAddrs());
1473 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001474 effect->setMode(mAudioFlinger->getMode());
1475 effect->setAudioSource(mAudioSource);
1476 }
jiabin1319f5a2021-03-30 22:21:24 +00001477 if (effect->isHapticGenerator()) {
1478 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1479 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001480 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1481 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1482 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001483 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001484 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001485 }
1486 }
Eric Laurent81784c32012-11-19 14:55:58 -08001487 // create effect handle and connect it to effect module
1488 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001489 lStatus = handle->initCheck();
1490 if (lStatus == OK) {
1491 lStatus = effect->addHandle(handle.get());
1492 }
Eric Laurent81784c32012-11-19 14:55:58 -08001493 if (enabled != NULL) {
1494 *enabled = (int)effect->isEnabled();
1495 }
1496 }
1497
1498Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001499 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001500 Mutex::Autolock _l(mLock);
1501 if (effectCreated) {
1502 chain->removeEffect_l(effect);
1503 }
Eric Laurent81784c32012-11-19 14:55:58 -08001504 if (chainCreated) {
1505 removeEffectChain_l(chain);
1506 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001507 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001508 }
1509
Glenn Kasten9156ef32013-08-06 15:39:08 -07001510 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001511 return handle;
1512}
1513
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001514void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1515 bool unpinIfLast)
1516{
1517 bool remove = false;
1518 sp<EffectModule> effect;
1519 {
1520 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001521 sp<EffectBase> effectBase = handle->effect().promote();
1522 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001523 return;
1524 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001525 effect = effectBase->asEffectModule();
1526 if (effect == nullptr) {
1527 return;
1528 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001529 // restore suspended effects if the disconnected handle was enabled and the last one.
1530 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1531 if (remove) {
1532 removeEffect_l(effect, true);
1533 }
1534 }
1535 if (remove) {
1536 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001537 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001538 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001539 }
1540 }
1541}
1542
Eric Laurent6b446ce2019-12-13 10:56:31 -08001543void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001544 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001545 Mutex::Autolock _l(mLock);
1546 broadcast_l();
1547 }
1548 if (!effect->isOffloadable()) {
1549 if (mType == ThreadBase::OFFLOAD) {
1550 PlaybackThread *t = (PlaybackThread *)this;
1551 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1552 }
1553 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1554 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1555 }
1556 }
1557}
1558
1559void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001560 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001561 Mutex::Autolock _l(mLock);
1562 broadcast_l();
1563 }
1564}
1565
Glenn Kastend848eb42016-03-08 13:42:11 -08001566sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1567 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001568{
1569 Mutex::Autolock _l(mLock);
1570 return getEffect_l(sessionId, effectId);
1571}
1572
Glenn Kastend848eb42016-03-08 13:42:11 -08001573sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1574 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001575{
1576 sp<EffectChain> chain = getEffectChain_l(sessionId);
1577 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1578}
1579
Eric Laurent6c796322019-04-09 14:13:17 -07001580std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1581{
1582 sp<EffectChain> chain = getEffectChain_l(sessionId);
1583 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1584}
1585
Eric Laurent81784c32012-11-19 14:55:58 -08001586// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1587// PlaybackThread::mLock held
1588status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1589{
1590 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001591 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001592 sp<EffectChain> chain = getEffectChain_l(sessionId);
1593 bool chainCreated = false;
1594
Eric Laurent5baf2af2013-09-12 17:37:00 -07001595 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001596 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001597 this, effect->desc().name, effect->desc().flags);
1598
Eric Laurent81784c32012-11-19 14:55:58 -08001599 if (chain == 0) {
1600 // create a new chain for this session
1601 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1602 chain = new EffectChain(this, sessionId);
1603 addEffectChain_l(chain);
1604 chain->setStrategy(getStrategyForSession_l(sessionId));
1605 chainCreated = true;
1606 }
1607 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1608
1609 if (chain->getEffectFromId_l(effect->id()) != 0) {
1610 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1611 this, effect->desc().name, chain.get());
1612 return BAD_VALUE;
1613 }
1614
Eric Laurent5baf2af2013-09-12 17:37:00 -07001615 effect->setOffloaded(mType == OFFLOAD, mId);
1616
Eric Laurent81784c32012-11-19 14:55:58 -08001617 status_t status = chain->addEffect_l(effect);
1618 if (status != NO_ERROR) {
1619 if (chainCreated) {
1620 removeEffectChain_l(chain);
1621 }
1622 return status;
1623 }
1624
jiabin8f278ee2019-11-11 12:16:27 -08001625 effect->setDevices(outDeviceTypeAddrs());
1626 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001627 effect->setMode(mAudioFlinger->getMode());
1628 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001629
Eric Laurent81784c32012-11-19 14:55:58 -08001630 return NO_ERROR;
1631}
1632
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001633void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001634
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001635 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001636 effect_descriptor_t desc = effect->desc();
1637 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1638 detachAuxEffect_l(effect->id());
1639 }
1640
Andy Hungfda44002021-06-03 17:23:16 -07001641 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001642 if (chain != 0) {
1643 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001644 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001645 removeEffectChain_l(chain);
1646 }
1647 } else {
1648 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1649 }
1650}
1651
1652void AudioFlinger::ThreadBase::lockEffectChains_l(
1653 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1654{
1655 effectChains = mEffectChains;
1656 for (size_t i = 0; i < mEffectChains.size(); i++) {
1657 mEffectChains[i]->lock();
1658 }
1659}
1660
1661void AudioFlinger::ThreadBase::unlockEffectChains(
1662 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1663{
1664 for (size_t i = 0; i < effectChains.size(); i++) {
1665 effectChains[i]->unlock();
1666 }
1667}
1668
Glenn Kastend848eb42016-03-08 13:42:11 -08001669sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001670{
1671 Mutex::Autolock _l(mLock);
1672 return getEffectChain_l(sessionId);
1673}
1674
Glenn Kastend848eb42016-03-08 13:42:11 -08001675sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1676 const
Eric Laurent81784c32012-11-19 14:55:58 -08001677{
1678 size_t size = mEffectChains.size();
1679 for (size_t i = 0; i < size; i++) {
1680 if (mEffectChains[i]->sessionId() == sessionId) {
1681 return mEffectChains[i];
1682 }
1683 }
1684 return 0;
1685}
1686
1687void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1688{
1689 Mutex::Autolock _l(mLock);
1690 size_t size = mEffectChains.size();
1691 for (size_t i = 0; i < size; i++) {
1692 mEffectChains[i]->setMode_l(mode);
1693 }
1694}
1695
Mikhail Naganovdc769682018-05-04 15:34:08 -07001696void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001697{
1698 config->type = AUDIO_PORT_TYPE_MIX;
1699 config->ext.mix.handle = mId;
1700 config->sample_rate = mSampleRate;
1701 config->format = mFormat;
1702 config->channel_mask = mChannelMask;
1703 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1704 AUDIO_PORT_CONFIG_FORMAT;
1705}
1706
Eric Laurent72e3f392015-05-20 14:43:50 -07001707void AudioFlinger::ThreadBase::systemReady()
1708{
1709 Mutex::Autolock _l(mLock);
1710 if (mSystemReady) {
1711 return;
1712 }
1713 mSystemReady = true;
1714
1715 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1716 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1717 }
1718 mPendingConfigEvents.clear();
1719}
1720
Andy Hungdae27702016-10-31 14:01:16 -07001721template <typename T>
1722ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1723 ssize_t index = mActiveTracks.indexOf(track);
1724 if (index >= 0) {
1725 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1726 return index;
1727 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001728 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001729 mActiveTracksGeneration++;
1730 mLatestActiveTrack = track;
1731 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001732 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001733 return mActiveTracks.add(track);
1734}
1735
1736template <typename T>
1737ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1738 ssize_t index = mActiveTracks.remove(track);
1739 if (index < 0) {
1740 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1741 return index;
1742 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001743 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001744 mActiveTracksGeneration++;
1745 --mBatteryCounter[track->uid()].second;
1746 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001747 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001748#ifdef TEE_SINK
1749 track->dumpTee(-1 /* fd */, "_REMOVE");
1750#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001751 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001752 return index;
1753}
1754
1755template <typename T>
1756void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1757 for (const sp<T> &track : mActiveTracks) {
1758 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001759 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001760 }
1761 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001762 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001763 mActiveTracks.clear();
1764 mLatestActiveTrack.clear();
1765 mBatteryCounter.clear();
1766}
1767
1768template <typename T>
1769void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1770 sp<ThreadBase> thread, bool force) {
1771 // Updates ActiveTracks client uids to the thread wakelock.
1772 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1773 thread->updateWakeLockUids_l(getWakeLockUids());
1774 mLastActiveTracksGeneration = mActiveTracksGeneration;
1775 }
1776
1777 // Updates BatteryNotifier uids
1778 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1779 const uid_t uid = it->first;
1780 ssize_t &previous = it->second.first;
1781 ssize_t &current = it->second.second;
1782 if (current > 0) {
1783 if (previous == 0) {
1784 BatteryNotifier::getInstance().noteStartAudio(uid);
1785 }
1786 previous = current;
1787 ++it;
1788 } else if (current == 0) {
1789 if (previous > 0) {
1790 BatteryNotifier::getInstance().noteStopAudio(uid);
1791 }
1792 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1793 } else /* (current < 0) */ {
1794 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1795 }
1796 }
1797}
Eric Laurent83b88082014-06-20 18:31:16 -07001798
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001799template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001800bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001801 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001802 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001803
1804 for (const sp<T> &track : mActiveTracks) {
1805 // Do not short-circuit as all hasChanged states must be reset
1806 // as all the metadata are going to be sent
1807 hasChanged |= track->readAndClearHasChanged();
1808 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001809 return hasChanged;
1810}
1811
1812template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001813void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1814 const char *funcName, const sp<T> &track) const {
1815 if (mLocalLog != nullptr) {
1816 String8 result;
1817 track->appendDump(result, false /* active */);
1818 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1819 }
1820}
1821
Eric Laurent6acd1d42017-01-04 14:23:29 -08001822void AudioFlinger::ThreadBase::broadcast_l()
1823{
1824 // Thread could be blocked waiting for async
1825 // so signal it to handle state changes immediately
1826 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1827 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1828 mSignalPending = true;
1829 mWaitWorkCV.broadcast();
1830}
1831
Andy Hungd0979812019-02-21 15:51:44 -08001832// Call only from threadLoop() or when it is idle.
1833// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1834void AudioFlinger::ThreadBase::sendStatistics(bool force)
1835{
1836 // Do not log if we have no stats.
1837 // We choose the timestamp verifier because it is the most likely item to be present.
1838 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1839 if (nstats == 0) {
1840 return;
1841 }
1842
1843 // Don't log more frequently than once per 12 hours.
1844 // We use BOOTTIME to include suspend time.
1845 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1846 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1847 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1848 return;
1849 }
1850
1851 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1852 mLastRecordedTimeNs = timeNs;
1853
Ray Essickf27e9872019-12-07 06:28:46 -08001854 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001855
1856#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1857
1858 // thread configuration
1859 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1860 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1861 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1862 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1863 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1864 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1865 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001866 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1867 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001868
1869 // thread statistics
1870 if (mIoJitterMs.getN() > 0) {
1871 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1872 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1873 }
1874 if (mProcessTimeMs.getN() > 0) {
1875 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1876 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1877 }
1878 const auto tsjitter = mTimestampVerifier.getJitterMs();
1879 if (tsjitter.getN() > 0) {
1880 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1881 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1882 }
1883 if (mLatencyMs.getN() > 0) {
1884 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1885 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1886 }
1887
1888 item->selfrecord();
1889}
1890
Eric Laurentd66d7a12021-07-13 13:35:32 +02001891product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1892{
1893 if (!mAudioFlinger->isAudioPolicyReady()) {
1894 return PRODUCT_STRATEGY_NONE;
1895 }
1896 return AudioSystem::getStrategyForStream(stream);
1897}
1898
Eric Laurent81784c32012-11-19 14:55:58 -08001899// ----------------------------------------------------------------------------
1900// Playback
1901// ----------------------------------------------------------------------------
1902
1903AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1904 AudioStreamOut* output,
1905 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001906 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001907 bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07001908 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001909 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001910 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001911 mMixerBuffer(NULL),
1912 mMixerBufferSize(0),
1913 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1914 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001915 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001916 mEffectBuffer(NULL),
1917 mEffectBufferSize(0),
1918 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1919 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001920 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001921 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001922 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001923 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001924 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001925 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001926 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001927 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001928 mMixerStatus(MIXER_IDLE),
1929 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001930 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001931 mBytesRemaining(0),
1932 mCurrentWriteLength(0),
1933 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001934 mWriteAckSequence(0),
1935 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001936 mScreenState(AudioFlinger::mScreenState),
1937 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001938 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001939 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001940 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1941 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001942{
Glenn Kastend7dca052015-03-05 16:05:54 -08001943 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1944 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001945
1946 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1947 // it would be safer to explicitly pass initial masterVolume/masterMute as
1948 // parameter.
1949 //
1950 // If the HAL we are using has support for master volume or master mute,
1951 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1952 // and the mute set to false).
1953 mMasterVolume = audioFlinger->masterVolume_l();
1954 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001955 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001956 if (mOutput->audioHwDev->canSetMasterVolume()) {
1957 mMasterVolume = 1.0;
1958 }
1959
1960 if (mOutput->audioHwDev->canSetMasterMute()) {
1961 mMasterMute = false;
1962 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001963 mIsMsdDevice = strcmp(
1964 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001965 }
1966
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001967 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001968
Andy Hungc8fddf32018-08-08 18:32:37 -07001969 // TODO: We may also match on address as well as device type for
1970 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001971 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001972 // TODO: This property should be ensure that only contains one single device type.
1973 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1974 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001975 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1976 : AUDIO_DEVICE_NONE));
1977 }
1978
Mikhail Naganovf33115d2020-09-25 23:03:05 +00001979 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1980 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08001981 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001982 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1983 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001984 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001985 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1986 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001987 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1988 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001989}
1990
1991AudioFlinger::PlaybackThread::~PlaybackThread()
1992{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001993 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001994 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001995 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001996 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001997}
1998
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001999// Thread virtuals
2000
2001void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002002{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002003 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002004 ALOGE("The stream is not open yet"); // This should not happen.
2005 } else {
2006 // setEventCallback will need a strong pointer as a parameter. Calling it
2007 // here instead of constructor of PlaybackThread so that the onFirstRef
2008 // callback would not be made on an incompletely constructed object.
2009 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002010 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002011 }
2012 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002013 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002014}
2015
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002016// ThreadBase virtuals
2017void AudioFlinger::PlaybackThread::preExit()
2018{
2019 ALOGV(" preExit()");
2020 // FIXME this is using hard-coded strings but in the future, this functionality will be
2021 // converted to use audio HAL extensions required to support tunneling
2022 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2023 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2024}
2025
2026void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002027{
Eric Laurent81784c32012-11-19 14:55:58 -08002028 String8 result;
2029
Marco Nelissenb2208842014-02-07 14:00:50 -08002030 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002031 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2032 const stream_type_t *st = &mStreamTypes[i];
2033 if (i > 0) {
2034 result.appendFormat(", ");
2035 }
2036 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2037 if (st->mute) {
2038 result.append("M");
2039 }
2040 }
2041 result.append("\n");
2042 write(fd, result.string(), result.length());
2043 result.clear();
2044
Eric Laurent81784c32012-11-19 14:55:58 -08002045 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2046 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002047 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002048 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002049
2050 size_t numtracks = mTracks.size();
2051 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002052 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002053 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002054 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002055 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002056 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002057 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002058 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002059 for (size_t i = 0; i < numtracks; ++i) {
2060 sp<Track> track = mTracks[i];
2061 if (track != 0) {
2062 bool active = mActiveTracks.indexOf(track) >= 0;
2063 if (active) {
2064 numactiveseen++;
2065 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002066 result.append(prefix);
2067 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002068 }
2069 }
2070 } else {
2071 result.append("\n");
2072 }
2073 if (numactiveseen != numactive) {
2074 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002075 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002076 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002077 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002078 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002079 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002080 sp<Track> track = mActiveTracks[i];
2081 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002082 result.append(prefix);
2083 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002084 }
2085 }
2086 }
2087
2088 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002089}
2090
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002091void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002092{
Andy Hung04cb8f72020-03-20 13:44:33 -07002093 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002094 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002095 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2096 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2097 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2098 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002099 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002100 dprintf(fd, " Total writes: %d\n", mNumWrites);
2101 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2102 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2103 dprintf(fd, " Suspend count: %d\n", mSuspended);
2104 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2105 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2106 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2107 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002108 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002109 AudioStreamOut *output = mOutput;
2110 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002111 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002112 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002113 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2114 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2115 if (mPipeSink.get() != nullptr) {
2116 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2117 }
2118 if (output != nullptr) {
2119 dprintf(fd, " Hal stream dump:\n");
2120 (void)output->stream->dump(fd);
2121 }
Eric Laurent81784c32012-11-19 14:55:58 -08002122}
2123
Eric Laurent81784c32012-11-19 14:55:58 -08002124// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2125sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2126 const sp<AudioFlinger::Client>& client,
2127 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002128 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002129 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002130 audio_format_t format,
2131 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002132 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002133 size_t *pNotificationFrameCount,
2134 uint32_t notificationsPerBuffer,
2135 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002136 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002137 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002138 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002139 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002140 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002141 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002142 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002143 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002144 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002145{
Glenn Kasten74935e42013-12-19 08:56:45 -08002146 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002147 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002148 sp<Track> track;
2149 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002150 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002151 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002152 uint32_t sampleRate;
2153
2154 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2155 lStatus = BAD_VALUE;
2156 goto Exit;
2157 }
Eric Laurent21da6472017-11-09 16:29:26 -08002158
2159 if (*pSampleRate == 0) {
2160 *pSampleRate = mSampleRate;
2161 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002162 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002163
2164 // special case for FAST flag considered OK if fast mixer is present
2165 if (hasFastMixer()) {
2166 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2167 }
2168
2169 // Check if requested flags are compatible with output stream flags
2170 if ((*flags & outputFlags) != *flags) {
2171 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2172 *flags, outputFlags);
2173 *flags = (audio_output_flags_t)(*flags & outputFlags);
2174 }
Eric Laurent81784c32012-11-19 14:55:58 -08002175
Eric Laurent81784c32012-11-19 14:55:58 -08002176 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002177 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002178 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002179 // PCM data
2180 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002181 // TODO: extract as a data library function that checks that a computationally
2182 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002183 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002184 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2185 (channelMask == AUDIO_CHANNEL_OUT_MONO
2186 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002187 // hardware sample rate
2188 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002189 // normal mixer has an associated fast mixer
2190 hasFastMixer() &&
2191 // there are sufficient fast track slots available
2192 (mFastTrackAvailMask != 0)
2193 // FIXME test that MixerThread for this fast track has a capable output HAL
2194 // FIXME add a permission test also?
2195 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002196 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2197 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002198 // read the fast track multiplier property the first time it is needed
2199 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2200 if (ok != 0) {
2201 ALOGE("%s pthread_once failed: %d", __func__, ok);
2202 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002203 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002204 }
Eric Laurent4c415062016-06-17 16:14:16 -07002205
2206 // check compatibility with audio effects.
2207 { // scope for mLock
2208 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002209 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002210 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002211 AUDIO_SESSION_OUTPUT_STAGE,
2212 AUDIO_SESSION_OUTPUT_MIX,
2213 sessionId,
2214 }) {
2215 sp<EffectChain> chain = getEffectChain_l(session);
2216 if (chain.get() != nullptr) {
2217 audio_output_flags_t old = *flags;
2218 chain->checkOutputFlagCompatibility(flags);
2219 if (old != *flags) {
2220 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2221 (int)session, (int)old, (int)*flags);
2222 }
Eric Laurent4c415062016-06-17 16:14:16 -07002223 }
2224 }
2225 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002226 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002227 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2228 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002229 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002230 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2231 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002232 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002233 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002234 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002235 audio_is_linear_pcm(format), channelMask, sampleRate,
2236 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002237 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002238 }
2239 }
Eric Laurent21da6472017-11-09 16:29:26 -08002240
2241 if (!audio_has_proportional_frames(format)) {
2242 if (sharedBuffer != 0) {
2243 // Same comment as below about ignoring frameCount parameter for set()
2244 frameCount = sharedBuffer->size();
2245 } else if (frameCount == 0) {
2246 frameCount = mNormalFrameCount;
2247 }
2248 if (notificationFrameCount != frameCount) {
2249 notificationFrameCount = frameCount;
2250 }
2251 } else if (sharedBuffer != 0) {
2252 // FIXME: Ensure client side memory buffers need
2253 // not have additional alignment beyond sample
2254 // (e.g. 16 bit stereo accessed as 32 bit frame).
2255 size_t alignment = audio_bytes_per_sample(format);
2256 if (alignment & 1) {
2257 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2258 alignment = 1;
2259 }
2260 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2261 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2262 if (channelCount > 1) {
2263 // More than 2 channels does not require stronger alignment than stereo
2264 alignment <<= 1;
2265 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002266 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002267 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002268 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002269 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002270 goto Exit;
2271 }
Eric Laurent21da6472017-11-09 16:29:26 -08002272
2273 // When initializing a shared buffer AudioTrack via constructors,
2274 // there's no frameCount parameter.
2275 // But when initializing a shared buffer AudioTrack via set(),
2276 // there _is_ a frameCount parameter. We silently ignore it.
2277 frameCount = sharedBuffer->size() / frameSize;
2278 } else {
2279 size_t minFrameCount = 0;
2280 // For fast tracks we try to respect the application's request for notifications per buffer.
2281 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2282 if (notificationsPerBuffer > 0) {
2283 // Avoid possible arithmetic overflow during multiplication.
2284 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2285 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2286 notificationsPerBuffer, mFrameCount);
2287 } else {
2288 minFrameCount = mFrameCount * notificationsPerBuffer;
2289 }
2290 }
2291 } else {
2292 // For normal PCM streaming tracks, update minimum frame count.
2293 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2294 // cover audio hardware latency.
2295 // This is probably too conservative, but legacy application code may depend on it.
2296 // If you change this calculation, also review the start threshold which is related.
2297 uint32_t latencyMs = latency_l();
2298 if (latencyMs == 0) {
2299 ALOGE("Error when retrieving output stream latency");
2300 lStatus = UNKNOWN_ERROR;
2301 goto Exit;
2302 }
2303
2304 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2305 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2306
Eric Laurent81784c32012-11-19 14:55:58 -08002307 }
Eric Laurent21da6472017-11-09 16:29:26 -08002308 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002309 frameCount = minFrameCount;
2310 }
Eric Laurent81784c32012-11-19 14:55:58 -08002311 }
Eric Laurent21da6472017-11-09 16:29:26 -08002312
2313 // Make sure that application is notified with sufficient margin before underrun.
2314 // The client can divide the AudioTrack buffer into sub-buffers,
2315 // and expresses its desire to server as the notification frame count.
2316 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2317 size_t maxNotificationFrames;
2318 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2319 // notify every HAL buffer, regardless of the size of the track buffer
2320 maxNotificationFrames = mFrameCount;
2321 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002322 // Triple buffer the notification period for a triple buffered mixer period;
2323 // otherwise, double buffering for the notification period is fine.
2324 //
2325 // TODO: This should be moved to AudioTrack to modify the notification period
2326 // on AudioTrack::setBufferSizeInFrames() changes.
2327 const int nBuffering =
2328 (uint64_t{frameCount} * mSampleRate)
2329 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2330
Eric Laurent21da6472017-11-09 16:29:26 -08002331 maxNotificationFrames = frameCount / nBuffering;
2332 // If client requested a fast track but this was denied, then use the smaller maximum.
2333 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2334 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2335 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2336 maxNotificationFrames = maxNotificationFramesFastDenied;
2337 }
2338 }
2339 }
2340 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2341 if (notificationFrameCount == 0) {
2342 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2343 maxNotificationFrames, frameCount);
2344 } else {
2345 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2346 notificationFrameCount, maxNotificationFrames, frameCount);
2347 }
2348 notificationFrameCount = maxNotificationFrames;
2349 }
2350 }
2351
Glenn Kasten74935e42013-12-19 08:56:45 -08002352 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002353 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002354
Glenn Kastenc3df8382014-03-13 15:05:25 -07002355 switch (mType) {
2356
2357 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002358 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002359 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002360 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2361 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002362 sampleRate, format, channelMask, mOutput, mFormat);
2363 lStatus = BAD_VALUE;
2364 goto Exit;
2365 }
2366 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002367 break;
2368
2369 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002370 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002371 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2372 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002373 sampleRate, format, channelMask, mOutput, mFormat);
2374 lStatus = BAD_VALUE;
2375 goto Exit;
2376 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002377 break;
2378
2379 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002380 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002381 ALOGE("createTrack_l() Bad parameter: format %#x \""
2382 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002383 format, mOutput, mFormat);
2384 lStatus = BAD_VALUE;
2385 goto Exit;
2386 }
Andy Hungcd044842014-08-07 11:04:34 -07002387 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002388 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2389 lStatus = BAD_VALUE;
2390 goto Exit;
2391 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002392 break;
2393
Eric Laurent81784c32012-11-19 14:55:58 -08002394 }
2395
2396 lStatus = initCheck();
2397 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002398 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002399 goto Exit;
2400 }
2401
2402 { // scope for mLock
2403 Mutex::Autolock _l(mLock);
2404
2405 // all tracks in same audio session must share the same routing strategy otherwise
2406 // conflicts will happen when tracks are moved from one output to another by audio policy
2407 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002408 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002409 for (size_t i = 0; i < mTracks.size(); ++i) {
2410 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002411 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002412 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002413 if (sessionId == t->sessionId() && strategy != actual) {
2414 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2415 strategy, actual);
2416 lStatus = BAD_VALUE;
2417 goto Exit;
2418 }
2419 }
2420 }
2421
yucliuc9c49cd2020-07-13 16:25:21 -07002422 // Set DIRECT flag if current thread is DirectOutputThread. This can
2423 // happen when the playback is rerouted to direct output thread by
2424 // dynamic audio policy.
2425 // Do NOT report the flag changes back to client, since the client
2426 // doesn't explicitly request a direct flag.
2427 audio_output_flags_t trackFlags = *flags;
2428 if (mType == DIRECT) {
2429 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2430 }
2431
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002432 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002433 channelMask, frameCount,
2434 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002435 sessionId, creatorPid, attributionSource, trackFlags,
2436 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/, speed);
Glenn Kasten03003332013-08-06 15:40:54 -07002437
Glenn Kasten03003332013-08-06 15:40:54 -07002438 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2439 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002440 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002441 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002442 goto Exit;
2443 }
2444 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002445 {
2446 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2447 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002448 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002449 }
2450 }
Eric Laurent81784c32012-11-19 14:55:58 -08002451
2452 sp<EffectChain> chain = getEffectChain_l(sessionId);
2453 if (chain != 0) {
2454 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2455 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002456 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002457 chain->incTrackCnt();
2458 }
2459
Eric Laurent05067782016-06-01 18:27:28 -07002460 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002461 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2462 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2463 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002464 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002465 }
2466 }
2467
2468 lStatus = NO_ERROR;
2469
2470Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002471 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002472 return track;
2473}
2474
Andy Hung1bc088a2018-02-09 15:57:31 -08002475template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002476ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2477{
Andy Hungc0691382018-09-12 18:01:57 -07002478 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002479 const ssize_t index = mTracks.remove(track);
2480 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002481 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002482 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002483 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002484 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002485 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002486 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002487 }
2488 return index;
2489}
2490
Eric Laurent81784c32012-11-19 14:55:58 -08002491uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2492{
2493 return latency;
2494}
2495
2496uint32_t AudioFlinger::PlaybackThread::latency() const
2497{
2498 Mutex::Autolock _l(mLock);
2499 return latency_l();
2500}
2501uint32_t AudioFlinger::PlaybackThread::latency_l() const
2502{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002503 uint32_t latency;
2504 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2505 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002506 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002507 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002508}
2509
2510void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2511{
2512 Mutex::Autolock _l(mLock);
2513 // Don't apply master volume in SW if our HAL can do it for us.
2514 if (mOutput && mOutput->audioHwDev &&
2515 mOutput->audioHwDev->canSetMasterVolume()) {
2516 mMasterVolume = 1.0;
2517 } else {
2518 mMasterVolume = value;
2519 }
2520}
2521
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002522void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2523{
2524 mMasterBalance.store(balance);
2525}
2526
Eric Laurent81784c32012-11-19 14:55:58 -08002527void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2528{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002529 if (isDuplicating()) {
2530 return;
2531 }
Eric Laurent81784c32012-11-19 14:55:58 -08002532 Mutex::Autolock _l(mLock);
2533 // Don't apply master mute in SW if our HAL can do it for us.
2534 if (mOutput && mOutput->audioHwDev &&
2535 mOutput->audioHwDev->canSetMasterMute()) {
2536 mMasterMute = false;
2537 } else {
2538 mMasterMute = muted;
2539 }
2540}
2541
2542void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2543{
2544 Mutex::Autolock _l(mLock);
2545 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002546 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002547}
2548
2549void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2550{
2551 Mutex::Autolock _l(mLock);
2552 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002553 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002554}
2555
2556float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2557{
2558 Mutex::Autolock _l(mLock);
2559 return mStreamTypes[stream].volume;
2560}
2561
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002562void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2563{
2564 mOutput->stream->setVolume(left, right);
2565}
2566
Eric Laurent81784c32012-11-19 14:55:58 -08002567// addTrack_l() must be called with ThreadBase::mLock held
2568status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2569{
2570 status_t status = ALREADY_EXISTS;
2571
Eric Laurent81784c32012-11-19 14:55:58 -08002572 if (mActiveTracks.indexOf(track) < 0) {
2573 // the track is newly added, make sure it fills up all its
2574 // buffers before playing. This is to ensure the client will
2575 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002576 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002577 TrackBase::track_state state = track->mState;
2578 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002579 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002580 mLock.lock();
2581 // abort track was stopped/paused while we released the lock
2582 if (state != track->mState) {
2583 if (status == NO_ERROR) {
2584 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002585 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002586 mLock.lock();
2587 }
2588 return INVALID_OPERATION;
2589 }
2590 // abort if start is rejected by audio policy manager
2591 if (status != NO_ERROR) {
2592 return PERMISSION_DENIED;
2593 }
2594#ifdef ADD_BATTERY_DATA
2595 // to track the speaker usage
2596 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2597#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002598 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 }
2600
Eric Laurent51716182016-02-29 18:00:56 -08002601 // set retry count for buffer fill
2602 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002603 if (track->isStopping_1()) {
2604 track->mRetryCount = kMaxTrackStopRetriesOffload;
2605 } else {
2606 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2607 }
2608 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002609 } else {
2610 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002611 track->mFillingUpStatus =
2612 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002613 }
2614
jiabineb3bda02020-06-30 14:07:03 -07002615 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2616 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2617 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2618 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002619 // Unlock due to VibratorService will lock for this call and will
2620 // call Tracks.mute/unmute which also require thread's lock.
2621 mLock.unlock();
2622 const int intensity = AudioFlinger::onExternalVibrationStart(
2623 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002624 std::optional<media::AudioVibratorInfo> vibratorInfo;
2625 {
2626 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2627 // used to play this track.
2628 Mutex::Autolock _l(mAudioFlinger->mLock);
2629 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2630 }
jiabin57303cc2018-12-18 15:45:57 -08002631 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002632 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002633 if (vibratorInfo) {
2634 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2635 }
2636
jiabin57303cc2018-12-18 15:45:57 -08002637 // Haptic playback should be enabled by vibrator service.
2638 if (track->getHapticPlaybackEnabled()) {
2639 // Disable haptic playback of all active track to ensure only
2640 // one track playing haptic if current track should play haptic.
2641 for (const auto &t : mActiveTracks) {
2642 t->setHapticPlaybackEnabled(false);
2643 }
jiabin245cdd92018-12-07 17:55:15 -08002644 }
jiabine70bc7f2020-06-30 22:07:55 -07002645
2646 // Set haptic intensity for effect
2647 if (chain != nullptr) {
2648 chain->setHapticIntensity_l(track->id(), intensity);
2649 }
jiabin245cdd92018-12-07 17:55:15 -08002650 }
2651
Eric Laurent81784c32012-11-19 14:55:58 -08002652 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002653 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002654 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002655 if (chain != 0) {
2656 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2657 track->sessionId());
2658 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002659 }
2660
Andy Hungc2b11cb2020-04-22 09:04:01 -07002661 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002662 status = NO_ERROR;
2663 }
2664
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002665 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002666 return status;
2667}
2668
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002670{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002672 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2674 track->mState = TrackBase::STOPPED;
2675 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002676 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002677 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002678 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002679 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002680
2681 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002682}
2683
2684void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2685{
2686 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002687
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002688 String8 result;
2689 track->appendDump(result, false /* active */);
2690 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002691
Eric Laurent81784c32012-11-19 14:55:58 -08002692 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002693 {
2694 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2695 mAudioTrackCallbacks.erase(track);
2696 }
Eric Laurent81784c32012-11-19 14:55:58 -08002697 if (track->isFastTrack()) {
2698 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002699 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002700 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2701 mFastTrackAvailMask |= 1 << index;
2702 // redundant as track is about to be destroyed, for dumpsys only
2703 track->mFastIndex = -1;
2704 }
2705 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2706 if (chain != 0) {
2707 chain->decTrackCnt();
2708 }
2709}
2710
2711String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2712{
Eric Laurent81784c32012-11-19 14:55:58 -08002713 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002714 String8 out_s8;
2715 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2716 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002717 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002718 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002719}
2720
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002721status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2722 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002723 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002724 return NO_INIT;
2725 }
2726 return mOutput->stream->selectPresentation(presentationId, programId);
2727}
2728
Eric Laurent09f1ed22019-04-24 17:45:17 -07002729void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2730 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002731 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2732 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002733
Eric Laurent73e26b62015-04-27 16:55:58 -07002734 desc->mIoHandle = mId;
Eric Laurent74c38dc2020-12-23 18:19:44 +01002735 struct audio_patch patch = mPatch;
2736 if (isMsdDevice()) {
2737 patch = mDownStreamPatch;
2738 }
Eric Laurent81784c32012-11-19 14:55:58 -08002739
2740 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002741 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002742 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002743 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002744 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002745 desc->mChannelMask = mChannelMask;
2746 desc->mSamplingRate = mSampleRate;
2747 desc->mFormat = mFormat;
2748 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002749 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002750 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002751 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002752 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002753 case AUDIO_CLIENT_STARTED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002754 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002755 desc->mPortId = portId;
2756 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002757 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002758 default:
2759 break;
2760 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002761 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002762}
2763
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002764void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002765{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002766 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002767}
2768
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002769void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002770{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002771 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002772}
2773
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002774void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002775{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002776 mCallbackThread->setAsyncError();
2777}
2778
jiabinf6eb4c32020-02-25 14:06:25 -08002779void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2780 const std::basic_string<uint8_t>& metadataBs)
2781{
2782 std::thread([this, metadataBs]() {
2783 audio_utils::metadata::Data metadata =
2784 audio_utils::metadata::dataFromByteString(metadataBs);
2785 if (metadata.empty()) {
2786 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2787 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2788 (int)metadataBs.size());
2789 return;
2790 }
2791
2792 audio_utils::metadata::ByteString metaDataStr =
2793 audio_utils::metadata::byteStringFromData(metadata);
2794 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2795 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002796 for (const auto& callbackPair : mAudioTrackCallbacks) {
2797 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002798 }
2799 }).detach();
2800}
2801
Eric Laurent3b4529e2013-09-05 18:09:19 -07002802void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002803{
2804 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002805 // reject out of sequence requests
2806 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2807 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002808 mWaitWorkCV.signal();
2809 }
2810}
2811
Eric Laurent3b4529e2013-09-05 18:09:19 -07002812void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002813{
2814 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002815 // reject out of sequence requests
2816 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002817 // Register discontinuity when HW drain is completed because that can cause
2818 // the timestamp frame position to reset to 0 for direct and offload threads.
2819 // (Out of sequence requests are ignored, since the discontinuity would be handled
2820 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002821 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002822 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002823 mWaitWorkCV.signal();
2824 }
2825}
2826
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002827void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002828{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002829 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002830 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2831 mSampleRate = audioConfig.sample_rate;
2832 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002833 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002834 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002835 }
Andy Hung9a592762014-07-21 21:56:01 -07002836 if ((mType == MIXER || mType == DUPLICATING)
2837 && !isValidPcmSinkChannelMask(mChannelMask)) {
2838 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2839 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002840 }
Andy Hunge5412692014-05-16 11:25:07 -07002841 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002842 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002843
2844 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002845 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002846 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002847 // Get format from the shim, which will be different than the HAL format
2848 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002849 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002850 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002851 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002852 }
Andy Hung6146c082014-03-18 11:56:15 -07002853 if ((mType == MIXER || mType == DUPLICATING)
2854 && !isValidPcmSinkFormat(mFormat)) {
2855 LOG_FATAL("HAL format %#x not supported for mixed output",
2856 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002857 }
Phil Burk062e67a2015-02-11 13:40:50 -08002858 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002859 result = mOutput->stream->getBufferSize(&mBufferSize);
2860 LOG_ALWAYS_FATAL_IF(result != OK,
2861 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002862 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002863 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002864 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002865 mFrameCount);
2866 }
2867
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002868 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2869 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002871 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002872 }
2873 }
2874
Eric Laurentd1f69b02014-12-15 14:33:13 -08002875 mHwSupportsPause = false;
2876 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002877 bool supportsPause = false, supportsResume = false;
2878 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2879 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002880 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002881 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002882 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002883 } else if (supportsResume) {
2884 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002885 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002886 }
2887 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002888 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2889 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2890 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002891
Andy Hungfbfc3952015-01-15 13:33:51 -08002892 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2893 // For best precision, we use float instead of the associated output
2894 // device format (typically PCM 16 bit).
2895
2896 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2897 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2898 mBufferSize = mFrameSize * mFrameCount;
2899
2900 // TODO: We currently use the associated output device channel mask and sample rate.
2901 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2902 // (if a valid mask) to avoid premature downmix.
2903 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2904 // instead of the output device sample rate to avoid loss of high frequency information.
2905 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2906 }
2907
Andy Hung09a50072014-02-27 14:30:47 -08002908 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002909 double multiplier = 1.0;
2910 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2911 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002912 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2913 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002914
Eric Laurent81784c32012-11-19 14:55:58 -08002915 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2916 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2917 maxNormalFrameCount = maxNormalFrameCount & ~15;
2918 if (maxNormalFrameCount < minNormalFrameCount) {
2919 maxNormalFrameCount = minNormalFrameCount;
2920 }
2921 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2922 if (multiplier <= 1.0) {
2923 multiplier = 1.0;
2924 } else if (multiplier <= 2.0) {
2925 if (2 * mFrameCount <= maxNormalFrameCount) {
2926 multiplier = 2.0;
2927 } else {
2928 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2929 }
2930 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002931 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002932 }
2933 }
2934 mNormalFrameCount = multiplier * mFrameCount;
2935 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002936 if (mType == MIXER || mType == DUPLICATING) {
2937 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2938 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002939 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002940 mNormalFrameCount);
2941
Andy Hung08fb1742015-05-31 23:22:10 -07002942 // Check if we want to throttle the processing to no more than 2x normal rate
2943 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002944 mThreadThrottleTimeMs = 0;
2945 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002946 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2947
Andy Hung010a1a12014-03-13 13:57:33 -07002948 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2949 // Originally this was int16_t[] array, need to remove legacy implications.
2950 free(mSinkBuffer);
2951 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002952 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2953 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2954 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002955 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002956
Andy Hung69aed5f2014-02-25 17:24:40 -08002957 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2958 // drives the output.
2959 free(mMixerBuffer);
2960 mMixerBuffer = NULL;
2961 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002962 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002963 mMixerBufferSize = mNormalFrameCount * mChannelCount
2964 * audio_bytes_per_sample(mMixerBufferFormat);
2965 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2966 }
Andy Hung98ef9782014-03-04 14:46:50 -08002967 free(mEffectBuffer);
2968 mEffectBuffer = NULL;
2969 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002970 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002971 mEffectBufferSize = mNormalFrameCount * mChannelCount
2972 * audio_bytes_per_sample(mEffectBufferFormat);
2973 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2974 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002975
Mikhail Naganov55773032020-10-01 15:08:13 -07002976 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2977 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002978 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2979 mChannelCount -= mHapticChannelCount;
2980
Eric Laurent81784c32012-11-19 14:55:58 -08002981 // force reconfiguration of effect chains and engines to take new buffer size and audio
2982 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002983 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002984 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2985 // matter.
2986 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2987 Vector< sp<EffectChain> > effectChains = mEffectChains;
2988 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002989 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2990 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002991 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002992
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002993 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002994 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002995 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2996 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2997 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2998 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2999 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3000 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3001 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3002 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3003 (int32_t)mHapticChannelMask)
3004 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3005 (int32_t)mHapticChannelCount)
3006 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3007 formatToString(mHALFormat).c_str())
3008 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3009 (int32_t)mFrameCount) // sic - added HAL
3010 ;
3011 uint32_t latencyMs;
3012 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3013 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3014 }
3015 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003016}
3017
Kevin Rocard069c2712018-03-29 19:09:14 -07003018void AudioFlinger::PlaybackThread::updateMetadata_l()
3019{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003020 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003021 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003022 }
3023 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003024 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003025 for (const sp<Track> &track : mActiveTracks) {
3026 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003027 // Do not forward metadata for PatchTrack with unspecified stream type
3028 if (track->streamType() != AUDIO_STREAM_PATCH) {
3029 track->copyMetadataTo(backInserter);
3030 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003031 }
Kevin Rocard12381092018-04-11 09:19:59 -07003032 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003033}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003034
Kevin Rocard12381092018-04-11 09:19:59 -07003035void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3036 const StreamOutHalInterface::SourceMetadata& metadata)
3037{
3038 mOutput->stream->updateSourceMetadata(metadata);
3039};
3040
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003041status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003042{
3043 if (halFrames == NULL || dspFrames == NULL) {
3044 return BAD_VALUE;
3045 }
3046 Mutex::Autolock _l(mLock);
3047 if (initCheck() != NO_ERROR) {
3048 return INVALID_OPERATION;
3049 }
Andy Hung818e7a32016-02-16 18:08:07 -08003050 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003051 *halFrames = framesWritten;
3052
3053 if (isSuspended()) {
3054 // return an estimation of rendered frames when the output is suspended
3055 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003056 *dspFrames = (uint32_t)
3057 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003058 return NO_ERROR;
3059 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003060 status_t status;
3061 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003062 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003063 *dspFrames = (size_t)frames;
3064 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003065 }
3066}
3067
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003068product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003069{
3070 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3071 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3072 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003073 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003074 }
3075 for (size_t i = 0; i < mTracks.size(); i++) {
3076 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003077 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003078 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003079 }
3080 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003081 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003082}
3083
3084
Phil Burk062e67a2015-02-11 13:40:50 -08003085AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003086{
3087 Mutex::Autolock _l(mLock);
3088 return mOutput;
3089}
3090
Phil Burk062e67a2015-02-11 13:40:50 -08003091AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003092{
3093 Mutex::Autolock _l(mLock);
3094 AudioStreamOut *output = mOutput;
3095 mOutput = NULL;
3096 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3097 // must push a NULL and wait for ack
3098 mOutputSink.clear();
3099 mPipeSink.clear();
3100 mNormalSink.clear();
3101 return output;
3102}
3103
3104// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003105sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003106{
3107 if (mOutput == NULL) {
3108 return NULL;
3109 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003110 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003111}
3112
3113uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3114{
3115 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3116}
3117
3118status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3119{
3120 if (!isValidSyncEvent(event)) {
3121 return BAD_VALUE;
3122 }
3123
3124 Mutex::Autolock _l(mLock);
3125
3126 for (size_t i = 0; i < mTracks.size(); ++i) {
3127 sp<Track> track = mTracks[i];
3128 if (event->triggerSession() == track->sessionId()) {
3129 (void) track->setSyncEvent(event);
3130 return NO_ERROR;
3131 }
3132 }
3133
3134 return NAME_NOT_FOUND;
3135}
3136
3137bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3138{
3139 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3140}
3141
3142void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3143 const Vector< sp<Track> >& tracksToRemove)
3144{
Andy Hungfe726a62018-09-27 15:17:25 -07003145 // Miscellaneous track cleanup when removed from the active list,
3146 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003147#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003148 for (const auto& track : tracksToRemove) {
3149 if (track->isExternalTrack()) {
3150 // to track the speaker usage
3151 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003152 }
3153 }
Andy Hungfe726a62018-09-27 15:17:25 -07003154#else
3155 (void)tracksToRemove; // suppress unused warning
3156#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003157}
3158
3159void AudioFlinger::PlaybackThread::checkSilentMode_l()
3160{
3161 if (!mMasterMute) {
3162 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003163 if (mOutDeviceTypeAddrs.empty()) {
3164 ALOGD("ro.audio.silent is ignored since no output device is set");
3165 return;
3166 }
jiabinc52b1ff2019-10-31 17:20:42 -07003167 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003168 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3169 return;
3170 }
Eric Laurent81784c32012-11-19 14:55:58 -08003171 if (property_get("ro.audio.silent", value, "0") > 0) {
3172 char *endptr;
3173 unsigned long ul = strtoul(value, &endptr, 0);
3174 if (*endptr == '\0' && ul != 0) {
3175 ALOGD("Silence is golden");
3176 // The setprop command will not allow a property to be changed after
3177 // the first time it is set, so we don't have to worry about un-muting.
3178 setMasterMute_l(true);
3179 }
3180 }
3181 }
3182}
3183
3184// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003185ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003186{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003187 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003188 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003189 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003190 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003191
3192 // If an NBAIO sink is present, use it to write the normal mixer's submix
3193 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003194
Andy Hung010a1a12014-03-13 13:57:33 -07003195 const size_t count = mBytesRemaining / mFrameSize;
3196
Simon Wilson2d590962012-11-29 15:18:50 -08003197 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003198 // update the setpoint when AudioFlinger::mScreenState changes
3199 uint32_t screenState = AudioFlinger::mScreenState;
3200 if (screenState != mScreenState) {
3201 mScreenState = screenState;
3202 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3203 if (pipe != NULL) {
3204 pipe->setAvgFrames((mScreenState & 1) ?
3205 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3206 }
3207 }
Andy Hung010a1a12014-03-13 13:57:33 -07003208 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003209 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003210 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003211 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003212#ifdef TEE_SINK
3213 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3214#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003215 } else {
3216 bytesWritten = framesWritten;
3217 }
3218 // otherwise use the HAL / AudioStreamOut directly
3219 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003220 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003221
Eric Laurentbfb1b832013-01-07 09:53:42 -08003222 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003223 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3224 mWriteAckSequence += 2;
3225 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003226 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003227 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003228 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003229 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003230 // FIXME We should have an implementation of timestamps for direct output threads.
3231 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003232 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003233 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003234
Eric Laurentbfb1b832013-01-07 09:53:42 -08003235 if (mUseAsyncWrite &&
3236 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3237 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003238 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003239 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003240 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241 }
Eric Laurent81784c32012-11-19 14:55:58 -08003242 }
3243
Eric Laurent81784c32012-11-19 14:55:58 -08003244 mNumWrites++;
3245 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003246 if (mStandby) {
3247 mThreadMetrics.logBeginInterval();
3248 mStandby = false;
3249 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003250 return bytesWritten;
3251}
3252
3253void AudioFlinger::PlaybackThread::threadLoop_drain()
3254{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003255 bool supportsDrain = false;
3256 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003257 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3258 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003259 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3260 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003261 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003262 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003263 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003264 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003265 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003266 }
3267}
3268
3269void AudioFlinger::PlaybackThread::threadLoop_exit()
3270{
Eric Laurent275e8e92014-11-30 15:14:47 -08003271 {
3272 Mutex::Autolock _l(mLock);
3273 for (size_t i = 0; i < mTracks.size(); i++) {
3274 sp<Track> track = mTracks[i];
3275 track->invalidate();
3276 }
Andy Hungdae27702016-10-31 14:01:16 -07003277 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3278 // After we exit there are no more track changes sent to BatteryNotifier
3279 // because that requires an active threadLoop.
3280 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3281 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003282 }
Eric Laurent81784c32012-11-19 14:55:58 -08003283}
3284
3285/*
3286The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003287 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003288 - mActiveSleepTimeUs from activeSleepTimeUs()
3289 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003290 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3291 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003292 - maxPeriod from frame count and sample rate (MIXER only)
3293
3294The parameters that affect these derived values are:
3295 - frame count
3296 - frame size
3297 - sample rate
3298 - device type: A2DP or not
3299 - device latency
3300 - format: PCM or not
3301 - active sleep time
3302 - idle sleep time
3303*/
3304
3305void AudioFlinger::PlaybackThread::cacheParameters_l()
3306{
Andy Hung25c2dac2014-02-27 14:56:00 -08003307 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003308 mActiveSleepTimeUs = activeSleepTimeUs();
3309 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003310
3311 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3312 // truncating audio when going to standby.
3313 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003314 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003315 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3316 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3317 }
3318 }
Eric Laurent81784c32012-11-19 14:55:58 -08003319}
3320
Eric Laurent13084622016-05-17 10:51:49 -07003321bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003322{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003323 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003324 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003325 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003326 size_t size = mTracks.size();
3327 for (size_t i = 0; i < size; i++) {
3328 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003329 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003330 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003331 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003332 }
3333 }
Eric Laurent13084622016-05-17 10:51:49 -07003334 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003335}
3336
Haynes Mathew George05317d22016-05-03 16:34:26 -07003337void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3338{
3339 Mutex::Autolock _l(mLock);
3340 invalidateTracks_l(streamType);
3341}
3342
jiabinf042b9b2021-05-07 23:46:28 +00003343// getTrackById_l must be called with holding thread lock
3344AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3345 audio_port_handle_t trackPortId) {
3346 for (size_t i = 0; i < mTracks.size(); i++) {
3347 if (mTracks[i]->portId() == trackPortId) {
3348 return mTracks[i].get();
3349 }
3350 }
3351 return nullptr;
3352}
3353
Eric Laurent81784c32012-11-19 14:55:58 -08003354status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3355{
Glenn Kastend848eb42016-03-08 13:42:11 -08003356 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003357 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003358 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003359 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3360 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3361 &halInBuffer);
3362 if (result != OK) return result;
3363 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003364 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003365 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003366 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003367 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003368 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003369 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003370 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003371 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003372 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003373 &halInBuffer);
3374 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003375#ifdef FLOAT_EFFECT_CHAIN
3376 buffer = halInBuffer->audioBuffer()->f32;
3377#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003378 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003379#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003380 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3381 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003382 }
3383
3384 // Attach all tracks with same session ID to this chain.
3385 for (size_t i = 0; i < mTracks.size(); ++i) {
3386 sp<Track> track = mTracks[i];
3387 if (session == track->sessionId()) {
3388 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3389 buffer);
3390 track->setMainBuffer(buffer);
3391 chain->incTrackCnt();
3392 }
3393 }
3394
3395 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003396 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003397 if (session == track->sessionId()) {
3398 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3399 chain->incActiveTrackCnt();
3400 }
3401 }
3402 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003403 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003404 chain->setInBuffer(halInBuffer);
3405 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003406 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3407 // chains list in order to be processed last as it contains output device effects.
3408 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3409 // processing effects specific to an output stream before effects applied to all streams
3410 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003411 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3412 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003413 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003414 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003415 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003416 // Effect chain for other sessions are inserted at beginning of effect
3417 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003418 // sessions is not important.
3419 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003420 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3421 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003422 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003423 size_t size = mEffectChains.size();
3424 size_t i = 0;
3425 for (i = 0; i < size; i++) {
3426 if (mEffectChains[i]->sessionId() < session) {
3427 break;
3428 }
3429 }
3430 mEffectChains.insertAt(chain, i);
3431 checkSuspendOnAddEffectChain_l(chain);
3432
3433 return NO_ERROR;
3434}
3435
3436size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3437{
Glenn Kastend848eb42016-03-08 13:42:11 -08003438 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003439
3440 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3441
3442 for (size_t i = 0; i < mEffectChains.size(); i++) {
3443 if (chain == mEffectChains[i]) {
3444 mEffectChains.removeAt(i);
3445 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003446 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003447 if (session == track->sessionId()) {
3448 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3449 chain.get(), session);
3450 chain->decActiveTrackCnt();
3451 }
3452 }
3453
3454 // detach all tracks with same session ID from this chain
3455 for (size_t i = 0; i < mTracks.size(); ++i) {
3456 sp<Track> track = mTracks[i];
3457 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003458 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003459 chain->decTrackCnt();
3460 }
3461 }
3462 break;
3463 }
3464 }
3465 return mEffectChains.size();
3466}
3467
3468status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003469 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003470{
3471 Mutex::Autolock _l(mLock);
3472 return attachAuxEffect_l(track, EffectId);
3473}
3474
3475status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003476 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003477{
3478 status_t status = NO_ERROR;
3479
3480 if (EffectId == 0) {
3481 track->setAuxBuffer(0, NULL);
3482 } else {
3483 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3484 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3485 if (effect != 0) {
3486 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3487 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3488 } else {
3489 status = INVALID_OPERATION;
3490 }
3491 } else {
3492 status = BAD_VALUE;
3493 }
3494 }
3495 return status;
3496}
3497
3498void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3499{
3500 for (size_t i = 0; i < mTracks.size(); ++i) {
3501 sp<Track> track = mTracks[i];
3502 if (track->auxEffectId() == effectId) {
3503 attachAuxEffect_l(track, 0);
3504 }
3505 }
3506}
3507
3508bool AudioFlinger::PlaybackThread::threadLoop()
3509{
Glenn Kasten388d5712017-04-07 14:38:41 -07003510 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003511
Eric Laurent81784c32012-11-19 14:55:58 -08003512 Vector< sp<Track> > tracksToRemove;
3513
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003514 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003515 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003516
3517 // MIXER
3518 nsecs_t lastWarning = 0;
3519
3520 // DUPLICATING
3521 // FIXME could this be made local to while loop?
3522 writeFrames = 0;
3523
3524 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003525 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003526
3527 if (mType == MIXER) {
3528 sleepTimeShift = 0;
3529 }
3530
3531 CpuStats cpuStats;
3532 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3533
3534 acquireWakeLock();
3535
Glenn Kasteneef598c2017-04-03 14:41:13 -07003536 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3537 // thread associated with this PlaybackThread.
3538 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3539 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003540 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3541 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003542 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003543 const char *logString = NULL;
3544
rago1bb90822017-05-02 18:31:48 -07003545 // Estimated time for next buffer to be written to hal. This is used only on
3546 // suspended mode (for now) to help schedule the wait time until next iteration.
3547 nsecs_t timeLoopNextNs = 0;
3548
Eric Laurent664539d2013-09-23 18:24:31 -07003549 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003550
Andy Hung2dbffc22018-08-08 18:50:41 -07003551 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003552
Andy Hung446f4df2019-02-21 12:26:41 -08003553 // loopCount is used for statistics and diagnostics.
3554 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003555 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003556 // Log merge requests are performed during AudioFlinger binder transactions, but
3557 // that does not cover audio playback. It's requested here for that reason.
3558 mAudioFlinger->requestLogMerge();
3559
Eric Laurent81784c32012-11-19 14:55:58 -08003560 cpuStats.sample(myName);
3561
3562 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003563 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003564 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003565
Andy Hung2dbffc22018-08-08 18:50:41 -07003566 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3567 //
jiabinc52b1ff2019-10-31 17:20:42 -07003568 // Note: we access outDeviceTypes() outside of mLock.
3569 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003570 // Here, we try for the AF lock, but do not block on it as the latency
3571 // is more informational.
3572 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3573 std::vector<PatchPanel::SoftwarePatch> swPatches;
3574 double latencyMs;
3575 status_t status = INVALID_OPERATION;
3576 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3577 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3578 && swPatches.size() > 0) {
3579 status = swPatches[0].getLatencyMs_l(&latencyMs);
3580 downstreamPatchHandle = swPatches[0].getPatchHandle();
3581 }
3582 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003583 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003584 lastDownstreamPatchHandle = downstreamPatchHandle;
3585 }
3586 if (status == OK) {
3587 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003588 // latency of 5 seconds).
3589 const double minLatency = 0., maxLatency = 5000.;
3590 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003591 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003592 } else {
3593 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003594 if (latencyMs < minLatency) latencyMs = minLatency;
3595 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003596 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003597 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003598 }
3599 mAudioFlinger->mLock.unlock();
3600 }
3601 } else {
3602 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3603 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003604 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003605 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3606 }
3607 }
3608
Eric Laurent81784c32012-11-19 14:55:58 -08003609 { // scope for mLock
3610
3611 Mutex::Autolock _l(mLock);
3612
Eric Laurent021cf962014-05-13 10:18:14 -07003613 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003614
Glenn Kasteneef598c2017-04-03 14:41:13 -07003615 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003616 if (logString != NULL) {
3617 mNBLogWriter->logTimestamp();
3618 mNBLogWriter->log(logString);
3619 logString = NULL;
3620 }
3621
Dean Wheatley12473e92021-03-18 23:00:55 +11003622 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003623
Eric Laurent81784c32012-11-19 14:55:58 -08003624 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003625 if (mSignalPending) {
3626 // A signal was raised while we were unlocked
3627 mSignalPending = false;
3628 } else if (waitingAsyncCallback_l()) {
3629 if (exitPending()) {
3630 break;
3631 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003632 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003633 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003634 releaseWakeLock_l();
3635 released = true;
3636 }
Andy Hung10cbff12017-02-21 17:30:14 -08003637
3638 const int64_t waitNs = computeWaitTimeNs_l();
3639 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3640 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3641 if (status == TIMED_OUT) {
3642 mSignalPending = true; // if timeout recheck everything
3643 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003644 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003645 if (released) {
3646 acquireWakeLock_l();
3647 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003648 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3649 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003650
3651 continue;
3652 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003653 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003654 isSuspended()) {
3655 // put audio hardware into standby after short delay
3656 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003657
3658 threadLoop_standby();
3659
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003660 // This is where we go into standby
3661 if (!mStandby) {
3662 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003663 mThreadMetrics.logEndInterval();
3664 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003665 }
Andy Hungd0979812019-02-21 15:51:44 -08003666 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003667 }
3668
Eric Tan39ec8d62018-07-24 09:49:29 -07003669 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003670 // we're about to wait, flush the binder command buffer
3671 IPCThreadState::self()->flushCommands();
3672
3673 clearOutputTracks();
3674
3675 if (exitPending()) {
3676 break;
3677 }
3678
3679 releaseWakeLock_l();
3680 // wait until we have something to do...
3681 ALOGV("%s going to sleep", myName.string());
3682 mWaitWorkCV.wait(mLock);
3683 ALOGV("%s waking up", myName.string());
3684 acquireWakeLock_l();
3685
3686 mMixerStatus = MIXER_IDLE;
3687 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3688 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003689 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003690 checkSilentMode_l();
3691
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003692 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3693 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003694 if (mType == MIXER) {
3695 sleepTimeShift = 0;
3696 }
3697
3698 continue;
3699 }
3700 }
Eric Laurent81784c32012-11-19 14:55:58 -08003701 // mMixerStatusIgnoringFastTracks is also updated internally
3702 mMixerStatus = prepareTracks_l(&tracksToRemove);
3703
Andy Hungdae27702016-10-31 14:01:16 -07003704 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003705
Kevin Rocard069c2712018-03-29 19:09:14 -07003706 updateMetadata_l();
3707
Eric Laurent81784c32012-11-19 14:55:58 -08003708 // prevent any changes in effect chain list and in each effect chain
3709 // during mixing and effect process as the audio buffers could be deleted
3710 // or modified if an effect is created or deleted
3711 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003712
3713 // Determine which session to pick up haptic data.
3714 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003715 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003716 // TODO: Write haptic data directly to sink buffer when mixing.
3717 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3718 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003719 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3720 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3721 activeHapticSessionId = track->sessionId();
3722 break;
3723 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003724 if (track->getHapticPlaybackEnabled()) {
3725 activeHapticSessionId = track->sessionId();
3726 break;
3727 }
3728 }
3729 }
3730
Andy Hungc1646382019-04-30 16:12:10 -07003731 // Acquire a local copy of active tracks with lock (release w/o lock).
3732 //
3733 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3734 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3735 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3736 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003737 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003738
Eric Laurentbfb1b832013-01-07 09:53:42 -08003739 if (mBytesRemaining == 0) {
3740 mCurrentWriteLength = 0;
3741 if (mMixerStatus == MIXER_TRACKS_READY) {
3742 // threadLoop_mix() sets mCurrentWriteLength
3743 threadLoop_mix();
3744 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3745 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003746 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003747 // must be written to HAL
3748 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003749 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003750 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003751
3752 // Tally underrun frames as we are inserting 0s here.
3753 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003754 if (track->mFillingUpStatus == Track::FS_ACTIVE
3755 && !track->isStopped()
3756 && !track->isPaused()
3757 && !track->isTerminated()) {
3758 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3759 __func__, track->id(), track->getTrackStateAsString(),
3760 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003761 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3762 }
3763 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003764 }
3765 }
Andy Hung98ef9782014-03-04 14:46:50 -08003766 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003767 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003768 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3769 // or mSinkBuffer (if there are no effects).
3770 //
3771 // This is done pre-effects computation; if effects change to
3772 // support higher precision, this needs to move.
3773 //
3774 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003775 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003776 if (mMixerBufferValid) {
3777 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3778 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3779
Andy Hung2ddee192015-12-18 17:34:44 -08003780 // mono blend occurs for mixer threads only (not direct or offloaded)
3781 // and is handled here if we're going directly to the sink.
3782 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003783 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3784 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003785 }
3786
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003787 if (!hasFastMixer()) {
3788 // Balance must take effect after mono conversion.
3789 // We do it here if there is no FastMixer.
3790 // mBalance detects zero balance within the class for speed (not needed here).
3791 mBalance.setBalance(mMasterBalance.load());
3792 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3793 }
3794
Andy Hung98ef9782014-03-04 14:46:50 -08003795 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003796 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3797
3798 // If we're going directly to the sink and there are haptic channels,
3799 // we should adjust channels as the sample data is partially interleaved
3800 // in this case.
3801 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3802 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3803 mChannelCount + mHapticChannelCount,
3804 audio_bytes_per_sample(format),
3805 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3806 }
Andy Hung98ef9782014-03-04 14:46:50 -08003807 }
3808
Eric Laurentbfb1b832013-01-07 09:53:42 -08003809 mBytesRemaining = mCurrentWriteLength;
3810 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003811 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3812 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3813 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3814 mBytesWritten += mBytesRemaining;
3815 mFramesWritten += framesRemaining;
3816 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003817 mBytesRemaining = 0;
3818 }
Eric Laurent81784c32012-11-19 14:55:58 -08003819
Eric Laurentbfb1b832013-01-07 09:53:42 -08003820 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003821 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003822 for (size_t i = 0; i < effectChains.size(); i ++) {
3823 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003824 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003825 if (activeHapticSessionId != AUDIO_SESSION_NONE
3826 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003827 // Haptic data is active in this case, copy it directly from
3828 // in buffer to out buffer.
3829 const size_t audioBufferSize = mNormalFrameCount
3830 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3831 memcpy_by_audio_format(
3832 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3833 EFFECT_BUFFER_FORMAT,
3834 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3835 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3836 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003837 }
Eric Laurent81784c32012-11-19 14:55:58 -08003838 }
3839 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003840 // Process effect chains for offloaded thread even if no audio
3841 // was read from audio track: process only updates effect state
3842 // and thus does have to be synchronized with audio writes but may have
3843 // to be called while waiting for async write callback
3844 if (mType == OFFLOAD) {
3845 for (size_t i = 0; i < effectChains.size(); i ++) {
3846 effectChains[i]->process_l();
3847 }
3848 }
Eric Laurent81784c32012-11-19 14:55:58 -08003849
Andy Hung98ef9782014-03-04 14:46:50 -08003850 // Only if the Effects buffer is enabled and there is data in the
3851 // Effects buffer (buffer valid), we need to
3852 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003853 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003854 if (mEffectBufferValid) {
3855 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003856
3857 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003858 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3859 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003860 }
3861
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003862 if (!hasFastMixer()) {
3863 // Balance must take effect after mono conversion.
3864 // We do it here if there is no FastMixer.
3865 // mBalance detects zero balance within the class for speed (not needed here).
3866 mBalance.setBalance(mMasterBalance.load());
3867 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3868 }
3869
Andy Hung98ef9782014-03-04 14:46:50 -08003870 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003871 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3872 // The sample data is partially interleaved when haptic channels exist,
3873 // we need to adjust channels here.
3874 if (mHapticChannelCount > 0) {
3875 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3876 mChannelCount + mHapticChannelCount,
3877 audio_bytes_per_sample(mFormat),
3878 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3879 }
Andy Hung98ef9782014-03-04 14:46:50 -08003880 }
3881
Eric Laurent81784c32012-11-19 14:55:58 -08003882 // enable changes in effect chain
3883 unlockEffectChains(effectChains);
3884
Eric Laurentbfb1b832013-01-07 09:53:42 -08003885 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003886 // mSleepTimeUs == 0 means we must write to audio hardware
3887 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003888 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003889 // writePeriodNs is updated >= 0 when ret > 0.
3890 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003891 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003892 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003893 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003894 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003895 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003896 if (ret < 0) {
3897 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003898 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003899 mBytesWritten += ret;
3900 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003901 const int64_t frames = ret / mFrameSize;
3902 mFramesWritten += frames;
3903
3904 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3905 // process information relating to write time.
3906 if (audio_has_proportional_frames(mFormat)) {
3907 // we are in a continuous mixing cycle
3908 if (mMixerStatus == MIXER_TRACKS_READY &&
3909 loopCount == lastLoopCountWritten + 1) {
3910
3911 const double jitterMs =
3912 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3913 {frames, writePeriodNs},
3914 {0, 0} /* lastTimestamp */, mSampleRate);
3915 const double processMs =
3916 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3917
3918 Mutex::Autolock _l(mLock);
3919 mIoJitterMs.add(jitterMs);
3920 mProcessTimeMs.add(processMs);
3921 }
3922
3923 // write blocked detection
3924 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3925 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3926 mNumDelayedWrites++;
3927 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3928 ATRACE_NAME("underrun");
3929 ALOGW("write blocked for %lld msecs, "
3930 "%d delayed writes, thread %d",
3931 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3932 mNumDelayedWrites, mId);
3933 lastWarning = lastIoEndNs;
3934 }
3935 }
3936 }
3937 // update timing info.
3938 mLastIoBeginNs = lastIoBeginNs;
3939 mLastIoEndNs = lastIoEndNs;
3940 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941 }
3942 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3943 (mMixerStatus == MIXER_DRAIN_ALL)) {
3944 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003945 }
Andy Hung08fb1742015-05-31 23:22:10 -07003946 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003947
3948 if (mThreadThrottle
3949 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003950 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003951 // Limit MixerThread data processing to no more than twice the
3952 // expected processing rate.
3953 //
3954 // This helps prevent underruns with NuPlayer and other applications
3955 // which may set up buffers that are close to the minimum size, or use
3956 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3957 //
3958 // The throttle smooths out sudden large data drains from the device,
3959 // e.g. when it comes out of standby, which often causes problems with
3960 // (1) mixer threads without a fast mixer (which has its own warm-up)
3961 // (2) minimum buffer sized tracks (even if the track is full,
3962 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003963 //
3964 // Total time spent in last processing cycle equals time spent in
3965 // 1. threadLoop_write, as well as time spent in
3966 // 2. threadLoop_mix (significant for heavy mixing, especially
3967 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003968
Andy Hung446f4df2019-02-21 12:26:41 -08003969 // it's OK if deltaMs is an overestimate.
3970
3971 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003972
Ivan Lozanoea04d392017-11-07 14:37:07 -08003973 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003974 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07003975 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08003976
Andy Hung08fb1742015-05-31 23:22:10 -07003977 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003978 // notify of throttle start on verbose log
3979 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3980 "mixer(%p) throttle begin:"
3981 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003982 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003983 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003984 // Throttle must be attributed to the previous mixer loop's write time
3985 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003986 // This also ensures proper timing statistics.
3987 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003988 } else {
3989 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3990 if (diff > 0) {
3991 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003992 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07003993 ALOGD_IF(!isSingleDeviceType(
3994 outDeviceTypes(), audio_is_a2dp_out_device) &&
3995 !isSingleDeviceType(
3996 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003997 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003998 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3999 }
Andy Hung08fb1742015-05-31 23:22:10 -07004000 }
4001 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004002 }
Eric Laurent81784c32012-11-19 14:55:58 -08004003
Eric Laurentbfb1b832013-01-07 09:53:42 -08004004 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004005 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004006 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004007 // suspended requires accurate metering of sleep time.
4008 if (isSuspended()) {
4009 // advance by expected sleepTime
4010 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4011 const nsecs_t nowNs = systemTime();
4012
4013 // compute expected next time vs current time.
4014 // (negative deltas are treated as delays).
4015 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4016 if (deltaNs < -kMaxNextBufferDelayNs) {
4017 // Delays longer than the max allowed trigger a reset.
4018 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4019 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4020 timeLoopNextNs = nowNs + deltaNs;
4021 } else if (deltaNs < 0) {
4022 // Delays within the max delay allowed: zero the delta/sleepTime
4023 // to help the system catch up in the next iteration(s)
4024 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4025 deltaNs = 0;
4026 }
4027 // update sleep time (which is >= 0)
4028 mSleepTimeUs = deltaNs / 1000;
4029 }
Eric Laurente93cc032016-05-05 10:15:10 -07004030 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4031 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004032 }
Glenn Kastene7754022014-10-31 12:11:26 -07004033 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004034 }
Eric Laurent81784c32012-11-19 14:55:58 -08004035 }
4036
4037 // Finally let go of removed track(s), without the lock held
4038 // since we can't guarantee the destructors won't acquire that
4039 // same lock. This will also mutate and push a new fast mixer state.
4040 threadLoop_removeTracks(tracksToRemove);
4041 tracksToRemove.clear();
4042
4043 // FIXME I don't understand the need for this here;
4044 // it was in the original code but maybe the
4045 // assignment in saveOutputTracks() makes this unnecessary?
4046 clearOutputTracks();
4047
4048 // Effect chains will be actually deleted here if they were removed from
4049 // mEffectChains list during mixing or effects processing
4050 effectChains.clear();
4051
4052 // FIXME Note that the above .clear() is no longer necessary since effectChains
4053 // is now local to this block, but will keep it for now (at least until merge done).
4054 }
4055
Eric Laurentbfb1b832013-01-07 09:53:42 -08004056 threadLoop_exit();
4057
Eric Laurentcf817a22014-08-04 20:36:31 -07004058 if (!mStandby) {
4059 threadLoop_standby();
4060 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004061 }
4062
4063 releaseWakeLock();
4064
4065 ALOGV("Thread %p type %d exiting", this, mType);
4066 return false;
4067}
4068
Dean Wheatley12473e92021-03-18 23:00:55 +11004069void AudioFlinger::PlaybackThread::collectTimestamps_l()
4070{
4071 // Collect timestamp statistics for the Playback Thread types that support it.
4072 if (mType != MIXER
4073 && mType != DUPLICATING
4074 && mType != DIRECT
4075 && mType != OFFLOAD) {
4076 return;
4077 }
4078 if (mStandby) {
4079 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4080 return;
4081 } else if (mHwPaused) {
4082 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4083 return;
4084 }
4085
4086 // Gather the framesReleased counters for all active tracks,
4087 // and associate with the sink frames written out. We need
4088 // this to convert the sink timestamp to the track timestamp.
4089 bool kernelLocationUpdate = false;
4090 ExtendedTimestamp timestamp; // use private copy to fetch
4091
4092 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4093 // HAL may be draining some small duration buffered data for fade out.
4094 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4095 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4096 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4097 mSampleRate);
4098
4099 if (isTimestampCorrectionEnabled()) {
4100 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4101 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4102 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4103 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4104 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4105 = correctedTimestamp.mFrames;
4106 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4107 = correctedTimestamp.mTimeNs;
4108 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4109 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4110 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4111
4112 // Note: Downstream latency only added if timestamp correction enabled.
4113 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4114 const int64_t newPosition =
4115 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4116 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4117 // prevent retrograde
4118 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4119 newPosition,
4120 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4121 - mSuspendedFrames));
4122 }
4123 }
4124
4125 // We always fetch the timestamp here because often the downstream
4126 // sink will block while writing.
4127
4128 // We keep track of the last valid kernel position in case we are in underrun
4129 // and the normal mixer period is the same as the fast mixer period, or there
4130 // is some error from the HAL.
4131 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4132 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4133 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4134 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4135 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4136
4137 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4138 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4139 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4140 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4141 }
4142
4143 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4144 kernelLocationUpdate = true;
4145 } else {
4146 ALOGVV("getTimestamp error - no valid kernel position");
4147 }
4148
4149 // copy over kernel info
4150 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4151 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4152 + mSuspendedFrames; // add frames discarded when suspended
4153 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4154 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4155 } else {
4156 mTimestampVerifier.error();
4157 }
4158
4159 // mFramesWritten for non-offloaded tracks are contiguous
4160 // even after standby() is called. This is useful for the track frame
4161 // to sink frame mapping.
4162 bool serverLocationUpdate = false;
4163 if (mFramesWritten != mLastFramesWritten) {
4164 serverLocationUpdate = true;
4165 mLastFramesWritten = mFramesWritten;
4166 }
4167 // Only update timestamps if there is a meaningful change.
4168 // Either the kernel timestamp must be valid or we have written something.
4169 if (kernelLocationUpdate || serverLocationUpdate) {
4170 if (serverLocationUpdate) {
4171 // use the time before we called the HAL write - it is a bit more accurate
4172 // to when the server last read data than the current time here.
4173 //
4174 // If we haven't written anything, mLastIoBeginNs will be -1
4175 // and we use systemTime().
4176 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4177 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4178 ? systemTime() : mLastIoBeginNs;
4179 }
4180
4181 for (const sp<Track> &t : mActiveTracks) {
4182 if (!t->isFastTrack()) {
4183 t->updateTrackFrameInfo(
4184 t->mAudioTrackServerProxy->framesReleased(),
4185 mFramesWritten,
4186 mSampleRate,
4187 mTimestamp);
4188 }
4189 }
4190 }
4191
4192 if (audio_has_proportional_frames(mFormat)) {
4193 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4194 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4195 mLatencyMs.add(latencyMs);
4196 }
4197 }
4198#if 0
4199 // logFormat example
4200 if (z % 100 == 0) {
4201 timespec ts;
4202 clock_gettime(CLOCK_MONOTONIC, &ts);
4203 LOGT("This is an integer %d, this is a float %f, this is my "
4204 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4205 LOGT("A deceptive null-terminated string %\0");
4206 }
4207 ++z;
4208#endif
4209}
4210
Eric Laurentbfb1b832013-01-07 09:53:42 -08004211// removeTracks_l() must be called with ThreadBase::mLock held
4212void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4213{
Andy Hungfe726a62018-09-27 15:17:25 -07004214 for (const auto& track : tracksToRemove) {
4215 mActiveTracks.remove(track);
4216 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4217 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4218 if (chain != 0) {
4219 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4220 __func__, track->id(), chain.get(), track->sessionId());
4221 chain->decActiveTrackCnt();
4222 }
4223 // If an external client track, inform APM we're no longer active, and remove if needed.
4224 // We do this under lock so that the state is consistent if the Track is destroyed.
4225 if (track->isExternalTrack()) {
4226 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004227 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004228 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004229 }
4230 }
Andy Hungfe726a62018-09-27 15:17:25 -07004231 if (track->isTerminated()) {
4232 // remove from our tracks vector
4233 removeTrack_l(track);
4234 }
jiabineb3bda02020-06-30 14:07:03 -07004235 if (mHapticChannelCount > 0 &&
4236 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4237 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004238 mLock.unlock();
4239 // Unlock due to VibratorService will lock for this call and will
4240 // call Tracks.mute/unmute which also require thread's lock.
4241 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4242 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004243
4244 // When the track is stop, set the haptic intensity as MUTE
4245 // for the HapticGenerator effect.
4246 if (chain != nullptr) {
4247 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4248 }
jiabin245cdd92018-12-07 17:55:15 -08004249 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004250 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004251}
Eric Laurent81784c32012-11-19 14:55:58 -08004252
Eric Laurentaccc1472013-09-20 09:36:34 -07004253status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4254{
4255 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004256 ExtendedTimestamp ets;
4257 status_t status = mNormalSink->getTimestamp(ets);
4258 if (status == NO_ERROR) {
4259 status = ets.getBestTimestamp(&timestamp);
4260 }
4261 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004262 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004263 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004264 collectTimestamps_l();
4265 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4266 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004267 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004268 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4269 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4270 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4271 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4272 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004273 }
4274 return INVALID_OPERATION;
4275}
Eric Laurent1c333e22014-05-20 10:48:17 -07004276
Eric Laurenteab90452019-06-24 15:17:46 -07004277// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4278// still applied by the mixer.
4279// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4280// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4281// if more than one track are active
4282status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4283{
4284 status_t result = NO_ERROR;
4285 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4286 if (*volume != mLeftVolFloat) {
4287 result = mOutput->stream->setVolume(*volume, *volume);
4288 ALOGE_IF(result != OK,
4289 "Error when setting output stream volume: %d", result);
4290 if (result == NO_ERROR) {
4291 mLeftVolFloat = *volume;
4292 }
4293 }
4294 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4295 // remove stream volume contribution from software volume.
4296 if (mLeftVolFloat == *volume) {
4297 *volume = 1.0f;
4298 }
4299 }
4300 return result;
4301}
4302
Eric Laurent054d9d32015-04-24 08:48:48 -07004303status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4304 audio_patch_handle_t *handle)
4305{
Andy Hungf60abce2016-08-26 11:37:54 -07004306 status_t status;
4307 if (property_get_bool("af.patch_park", false /* default_value */)) {
4308 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4309 // or if HAL does not properly lock against access.
4310 AutoPark<FastMixer> park(mFastMixer);
4311 status = PlaybackThread::createAudioPatch_l(patch, handle);
4312 } else {
4313 status = PlaybackThread::createAudioPatch_l(patch, handle);
4314 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004315 return status;
4316}
4317
Eric Laurent1c333e22014-05-20 10:48:17 -07004318status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4319 audio_patch_handle_t *handle)
4320{
4321 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004322
4323 // store new device and send to effects
4324 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004325 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004326 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004327 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4328 && !mOutput->audioHwDev->supportsAudioPatches(),
4329 "Enumerated device type(%#x) must not be used "
4330 "as it does not support audio patches",
4331 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004332 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004333 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4334 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004335 }
4336
François Gaffie0c280aa2018-07-25 10:02:15 +02004337 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004338#ifdef ADD_BATTERY_DATA
4339 // when changing the audio output device, call addBatteryData to notify
4340 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004341 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004342 uint32_t params = 0;
4343 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004344 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004345 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004346 }
4347
Eric Laurent054d9d32015-04-24 08:48:48 -07004348 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004349 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004350 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4351 }
4352
4353 if (params != 0) {
4354 addBatteryData(params);
4355 }
4356 }
4357#endif
4358
4359 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004360 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004361 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004362
jiabinc52b1ff2019-10-31 17:20:42 -07004363 // mPatch.num_sinks is not set when the thread is created so that
4364 // the first patch creation triggers an ioConfigChanged callback
4365 bool configChanged = (mPatch.num_sinks == 0) ||
4366 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004367 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004368 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004369 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004370
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004371 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004372 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4373 status = hwDevice->createAudioPatch(patch->num_sources,
4374 patch->sources,
4375 patch->num_sinks,
4376 patch->sinks,
4377 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004378 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004379 char *address;
4380 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4381 //FIXME: we only support address on first sink with HAL version < 3.0
4382 address = audio_device_address_to_parameter(
4383 patch->sinks[0].ext.device.type,
4384 patch->sinks[0].ext.device.address);
4385 } else {
4386 address = (char *)calloc(1, 1);
4387 }
4388 AudioParameter param = AudioParameter(String8(address));
4389 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004390 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004391 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004392 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004393 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004394 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004395
4396 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004397 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004398 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004399 // also dispatch to active AudioTracks for MediaMetrics
4400 for (const auto &track : mActiveTracks) {
4401 track->logEndInterval();
4402 track->logBeginInterval(patchSinksAsString);
4403 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004404
Eric Laurente8726fe2015-06-26 09:39:24 -07004405 if (configChanged) {
4406 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4407 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004408 return status;
4409}
4410
Eric Laurent054d9d32015-04-24 08:48:48 -07004411status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4412{
Andy Hungf60abce2016-08-26 11:37:54 -07004413 status_t status;
4414 if (property_get_bool("af.patch_park", false /* default_value */)) {
4415 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4416 // or if HAL does not properly lock against access.
4417 AutoPark<FastMixer> park(mFastMixer);
4418 status = PlaybackThread::releaseAudioPatch_l(handle);
4419 } else {
4420 status = PlaybackThread::releaseAudioPatch_l(handle);
4421 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004422 return status;
4423}
4424
Eric Laurent1c333e22014-05-20 10:48:17 -07004425status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4426{
4427 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004428
jiabinc52b1ff2019-10-31 17:20:42 -07004429 mPatch = audio_patch{};
4430 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004431
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004432 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004433 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4434 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004435 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004436 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004437 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004438 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004439 }
4440 return status;
4441}
4442
Eric Laurent83b88082014-06-20 18:31:16 -07004443void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4444{
4445 Mutex::Autolock _l(mLock);
4446 mTracks.add(track);
4447}
4448
4449void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4450{
4451 Mutex::Autolock _l(mLock);
4452 destroyTrack_l(track);
4453}
4454
Mikhail Naganovdc769682018-05-04 15:34:08 -07004455void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004456{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004457 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004458 config->role = AUDIO_PORT_ROLE_SOURCE;
4459 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4460 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004461 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4462 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4463 config->flags.output = mOutput->flags;
4464 }
Eric Laurent83b88082014-06-20 18:31:16 -07004465}
4466
Eric Laurent81784c32012-11-19 14:55:58 -08004467// ----------------------------------------------------------------------------
4468
4469AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004470 audio_io_handle_t id, bool systemReady, type_t type)
4471 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004472 // mAudioMixer below
4473 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004474 mFastMixerFutex(0),
4475 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004476 // mOutputSink below
4477 // mPipeSink below
4478 // mNormalSink below
4479{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004480 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004481 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004482 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004483 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004484 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4485 mNormalFrameCount);
4486 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4487
Andy Hungfbfc3952015-01-15 13:33:51 -08004488 if (type == DUPLICATING) {
4489 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4490 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4491 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4492 return;
4493 }
Eric Laurent81784c32012-11-19 14:55:58 -08004494 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004495 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004496 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004497 const NBAIO_Format offers[1] = {Format_from_SR_C(
4498 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004499#if !LOG_NDEBUG
4500 ssize_t index =
4501#else
4502 (void)
4503#endif
4504 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004505 ALOG_ASSERT(index == 0);
4506
4507 // initialize fast mixer depending on configuration
4508 bool initFastMixer;
4509 switch (kUseFastMixer) {
4510 case FastMixer_Never:
4511 initFastMixer = false;
4512 break;
4513 case FastMixer_Always:
4514 initFastMixer = true;
4515 break;
4516 case FastMixer_Static:
4517 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004518 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4519 // where the period is less than an experimentally determined threshold that can be
4520 // scheduled reliably with CFS. However, the BT A2DP HAL is
4521 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4522 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004523 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004524 break;
4525 }
Andy Hungfda69402017-02-15 14:33:12 -08004526 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4527 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4528 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004529 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004530 audio_format_t fastMixerFormat;
4531 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4532 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4533 } else {
4534 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4535 }
4536 if (mFormat != fastMixerFormat) {
4537 // change our Sink format to accept our intermediate precision
4538 mFormat = fastMixerFormat;
4539 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004540 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004541 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4542 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4543 }
Eric Laurent81784c32012-11-19 14:55:58 -08004544
4545 // create a MonoPipe to connect our submix to FastMixer
4546 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004547
Andy Hung1258c1a2014-05-23 21:22:17 -07004548 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004549 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004550 format.mFormat = fastMixerFormat;
4551 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4552
Eric Laurent81784c32012-11-19 14:55:58 -08004553 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4554 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4555 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4556 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4557 const NBAIO_Format offers[1] = {format};
4558 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004559#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004560 ssize_t index =
4561#else
4562 (void)
4563#endif
4564 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004565 ALOG_ASSERT(index == 0);
4566 monoPipe->setAvgFrames((mScreenState & 1) ?
4567 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4568 mPipeSink = monoPipe;
4569
Eric Laurent81784c32012-11-19 14:55:58 -08004570 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004571 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004572 FastMixerStateQueue *sq = mFastMixer->sq();
4573#ifdef STATE_QUEUE_DUMP
4574 sq->setObserverDump(&mStateQueueObserverDump);
4575 sq->setMutatorDump(&mStateQueueMutatorDump);
4576#endif
4577 FastMixerState *state = sq->begin();
4578 FastTrack *fastTrack = &state->mFastTracks[0];
4579 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4580 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4581 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004582 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4583 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4584 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004585 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004586 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004587 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004588 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004589 fastTrack->mGeneration++;
4590 state->mFastTracksGen++;
4591 state->mTrackMask = 1;
4592 // fast mixer will use the HAL output sink
4593 state->mOutputSink = mOutputSink.get();
4594 state->mOutputSinkGen++;
4595 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004596 // specify sink channel mask when haptic channel mask present as it can not
4597 // be calculated directly from channel count
4598 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004599 ? AUDIO_CHANNEL_NONE
4600 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004601 state->mCommand = FastMixerState::COLD_IDLE;
4602 // already done in constructor initialization list
4603 //mFastMixerFutex = 0;
4604 state->mColdFutexAddr = &mFastMixerFutex;
4605 state->mColdGen++;
4606 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004607 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4608 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004609 sq->end();
4610 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4611
Eric Tan0513b5d2018-09-17 10:32:48 -07004612 NBLog::thread_info_t info;
4613 info.id = mId;
4614 info.type = NBLog::FASTMIXER;
4615 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4616
Eric Laurent81784c32012-11-19 14:55:58 -08004617 // start the fast mixer
4618 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4619 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004620 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004621 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004622
4623#ifdef AUDIO_WATCHDOG
4624 // create and start the watchdog
4625 mAudioWatchdog = new AudioWatchdog();
4626 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4627 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4628 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004629 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004630#endif
Andy Hung8946a282018-04-19 20:04:56 -07004631 } else {
4632#ifdef TEE_SINK
4633 // Only use the MixerThread tee if there is no FastMixer.
4634 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4635 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4636#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004637 }
4638
4639 switch (kUseFastMixer) {
4640 case FastMixer_Never:
4641 case FastMixer_Dynamic:
4642 mNormalSink = mOutputSink;
4643 break;
4644 case FastMixer_Always:
4645 mNormalSink = mPipeSink;
4646 break;
4647 case FastMixer_Static:
4648 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4649 break;
4650 }
4651}
4652
4653AudioFlinger::MixerThread::~MixerThread()
4654{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004655 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004656 FastMixerStateQueue *sq = mFastMixer->sq();
4657 FastMixerState *state = sq->begin();
4658 if (state->mCommand == FastMixerState::COLD_IDLE) {
4659 int32_t old = android_atomic_inc(&mFastMixerFutex);
4660 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004661 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004662 }
4663 }
4664 state->mCommand = FastMixerState::EXIT;
4665 sq->end();
4666 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4667 mFastMixer->join();
4668 // Though the fast mixer thread has exited, it's state queue is still valid.
4669 // We'll use that extract the final state which contains one remaining fast track
4670 // corresponding to our sub-mix.
4671 state = sq->begin();
4672 ALOG_ASSERT(state->mTrackMask == 1);
4673 FastTrack *fastTrack = &state->mFastTracks[0];
4674 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4675 delete fastTrack->mBufferProvider;
4676 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004677 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004678#ifdef AUDIO_WATCHDOG
4679 if (mAudioWatchdog != 0) {
4680 mAudioWatchdog->requestExit();
4681 mAudioWatchdog->requestExitAndWait();
4682 mAudioWatchdog.clear();
4683 }
4684#endif
4685 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004686 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004687 delete mAudioMixer;
4688}
4689
4690
4691uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4692{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004693 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004694 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4695 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4696 }
4697 return latency;
4698}
4699
Eric Laurentbfb1b832013-01-07 09:53:42 -08004700ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004701{
4702 // FIXME we should only do one push per cycle; confirm this is true
4703 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004704 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004705 FastMixerStateQueue *sq = mFastMixer->sq();
4706 FastMixerState *state = sq->begin();
4707 if (state->mCommand != FastMixerState::MIX_WRITE &&
4708 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4709 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004710
4711 // FIXME workaround for first HAL write being CPU bound on some devices
4712 ATRACE_BEGIN("write");
4713 mOutput->write((char *)mSinkBuffer, 0);
4714 ATRACE_END();
4715
Eric Laurent81784c32012-11-19 14:55:58 -08004716 int32_t old = android_atomic_inc(&mFastMixerFutex);
4717 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004718 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004719 }
4720#ifdef AUDIO_WATCHDOG
4721 if (mAudioWatchdog != 0) {
4722 mAudioWatchdog->resume();
4723 }
4724#endif
4725 }
4726 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004727#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004728 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004729 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004730#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004731 sq->end();
4732 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4733 if (kUseFastMixer == FastMixer_Dynamic) {
4734 mNormalSink = mPipeSink;
4735 }
4736 } else {
4737 sq->end(false /*didModify*/);
4738 }
4739 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004740 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004741}
4742
4743void AudioFlinger::MixerThread::threadLoop_standby()
4744{
4745 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004746 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004747 FastMixerStateQueue *sq = mFastMixer->sq();
4748 FastMixerState *state = sq->begin();
4749 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004750 // Report any frames trapped in the Monopipe
4751 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4752 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4753 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4754 "monoPipeWritten:%lld monoPipeLeft:%lld",
4755 (long long)mFramesWritten, (long long)mSuspendedFrames,
4756 (long long)mPipeSink->framesWritten(), pipeFrames);
4757 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4758
Eric Laurent81784c32012-11-19 14:55:58 -08004759 state->mCommand = FastMixerState::COLD_IDLE;
4760 state->mColdFutexAddr = &mFastMixerFutex;
4761 state->mColdGen++;
4762 mFastMixerFutex = 0;
4763 sq->end();
4764 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4765 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4766 if (kUseFastMixer == FastMixer_Dynamic) {
4767 mNormalSink = mOutputSink;
4768 }
4769#ifdef AUDIO_WATCHDOG
4770 if (mAudioWatchdog != 0) {
4771 mAudioWatchdog->pause();
4772 }
4773#endif
4774 } else {
4775 sq->end(false /*didModify*/);
4776 }
4777 }
4778 PlaybackThread::threadLoop_standby();
4779}
4780
Eric Laurentbfb1b832013-01-07 09:53:42 -08004781bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4782{
4783 return false;
4784}
4785
4786bool AudioFlinger::PlaybackThread::shouldStandby_l()
4787{
4788 return !mStandby;
4789}
4790
4791bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4792{
4793 Mutex::Autolock _l(mLock);
4794 return waitingAsyncCallback_l();
4795}
4796
Eric Laurent81784c32012-11-19 14:55:58 -08004797// shared by MIXER and DIRECT, overridden by DUPLICATING
4798void AudioFlinger::PlaybackThread::threadLoop_standby()
4799{
4800 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004801 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004802 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004803 // discard any pending drain or write ack by incrementing sequence
4804 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4805 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004806 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004807 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4808 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004809 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004810 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004811}
4812
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004813void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4814{
4815 ALOGV("signal playback thread");
4816 broadcast_l();
4817}
4818
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004819void AudioFlinger::PlaybackThread::onAsyncError()
4820{
4821 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4822 invalidateTracks((audio_stream_type_t)i);
4823 }
4824}
4825
Eric Laurent81784c32012-11-19 14:55:58 -08004826void AudioFlinger::MixerThread::threadLoop_mix()
4827{
Eric Laurent81784c32012-11-19 14:55:58 -08004828 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004829 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004830 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004831 // increase sleep time progressively when application underrun condition clears.
4832 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4833 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4834 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004835 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004836 sleepTimeShift--;
4837 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004838 mSleepTimeUs = 0;
4839 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004840 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004841
Eric Laurent81784c32012-11-19 14:55:58 -08004842}
4843
4844void AudioFlinger::MixerThread::threadLoop_sleepTime()
4845{
4846 // If no tracks are ready, sleep once for the duration of an output
4847 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004848 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004849 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004850 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4851 // Using the Monopipe availableToWrite, we estimate the
4852 // sleep time to retry for more data (before we underrun).
4853 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4854 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4855 const size_t pipeFrames = monoPipe->maxFrames();
4856 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4857 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4858 const size_t framesDelay = std::min(
4859 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4860 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4861 pipeFrames, framesLeft, framesDelay);
4862 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4863 } else {
4864 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4865 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4866 mSleepTimeUs = kMinThreadSleepTimeUs;
4867 }
4868 // reduce sleep time in case of consecutive application underruns to avoid
4869 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4870 // duration we would end up writing less data than needed by the audio HAL if
4871 // the condition persists.
4872 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4873 sleepTimeShift++;
4874 }
Eric Laurent81784c32012-11-19 14:55:58 -08004875 }
4876 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004877 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004878 }
4879 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004880 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4881 // before effects processing or output.
4882 if (mMixerBufferValid) {
4883 memset(mMixerBuffer, 0, mMixerBufferSize);
4884 } else {
4885 memset(mSinkBuffer, 0, mSinkBufferSize);
4886 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004887 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004888 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4889 "anticipated start");
4890 }
4891 // TODO add standby time extension fct of effect tail
4892}
4893
4894// prepareTracks_l() must be called with ThreadBase::mLock held
4895AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4896 Vector< sp<Track> > *tracksToRemove)
4897{
Andy Hungc0691382018-09-12 18:01:57 -07004898 // clean up deleted track ids in AudioMixer before allocating new tracks
4899 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4900 // for each trackId, destroy it in the AudioMixer
4901 if (mAudioMixer->exists(trackId)) {
4902 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004903 }
4904 });
Andy Hungc0691382018-09-12 18:01:57 -07004905 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004906
4907 mixer_state mixerStatus = MIXER_IDLE;
4908 // find out which tracks need to be processed
4909 size_t count = mActiveTracks.size();
4910 size_t mixedTracks = 0;
4911 size_t tracksWithEffect = 0;
4912 // counts only _active_ fast tracks
4913 size_t fastTracks = 0;
4914 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4915
4916 float masterVolume = mMasterVolume;
4917 bool masterMute = mMasterMute;
4918
4919 if (masterMute) {
4920 masterVolume = 0;
4921 }
4922 // Delegate master volume control to effect in output mix effect chain if needed
4923 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4924 if (chain != 0) {
4925 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4926 chain->setVolume_l(&v, &v);
4927 masterVolume = (float)((v + (1 << 23)) >> 24);
4928 chain.clear();
4929 }
4930
4931 // prepare a new state to push
4932 FastMixerStateQueue *sq = NULL;
4933 FastMixerState *state = NULL;
4934 bool didModify = false;
4935 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004936 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004937 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004938 sq = mFastMixer->sq();
4939 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004940 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004941 }
4942
Andy Hung69aed5f2014-02-25 17:24:40 -08004943 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004944 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004945
Andy Hungbd3b2b02018-05-21 10:53:11 -07004946 // DeferredOperations handles statistics after setting mixerStatus.
4947 class DeferredOperations {
4948 public:
Andy Hungea840382020-05-05 21:50:17 -07004949 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4950 : mMixerStatus(mixerStatus)
4951 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004952
4953 // when leaving scope, tally frames properly.
4954 ~DeferredOperations() {
4955 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4956 // because that is when the underrun occurs.
4957 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004958 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004959 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004960 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004961 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004962 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004963 }
4964 }
Andy Hungea840382020-05-05 21:50:17 -07004965 // send the max underrun frames for this mixer period
4966 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004967 }
4968
4969 // tallyUnderrunFrames() is called to update the track counters
4970 // with the number of underrun frames for a particular mixer period.
4971 // We defer tallying until we know the final mixer status.
4972 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4973 mUnderrunFrames.emplace_back(track, underrunFrames);
4974 }
4975
4976 private:
4977 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004978 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004979 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004980 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004981 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004982
jiabin245cdd92018-12-07 17:55:15 -08004983 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004984 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004985 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004986
4987 // this const just means the local variable doesn't change
4988 Track* const track = t.get();
4989
4990 // process fast tracks
4991 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004992 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4993 "%s(%d): FastTrack(%d) present without FastMixer",
4994 __func__, id(), track->id());
4995
jiabin245cdd92018-12-07 17:55:15 -08004996 if (track->getHapticPlaybackEnabled()) {
4997 noFastHapticTrack = false;
4998 }
Eric Laurent81784c32012-11-19 14:55:58 -08004999
5000 // It's theoretically possible (though unlikely) for a fast track to be created
5001 // and then removed within the same normal mix cycle. This is not a problem, as
5002 // the track never becomes active so it's fast mixer slot is never touched.
5003 // The converse, of removing an (active) track and then creating a new track
5004 // at the identical fast mixer slot within the same normal mix cycle,
5005 // is impossible because the slot isn't marked available until the end of each cycle.
5006 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005007 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005008 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5009 FastTrack *fastTrack = &state->mFastTracks[j];
5010
5011 // Determine whether the track is currently in underrun condition,
5012 // and whether it had a recent underrun.
5013 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5014 FastTrackUnderruns underruns = ftDump->mUnderruns;
5015 uint32_t recentFull = (underruns.mBitFields.mFull -
5016 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5017 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5018 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5019 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5020 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5021 uint32_t recentUnderruns = recentPartial + recentEmpty;
5022 track->mObservedUnderruns = underruns;
5023 // don't count underruns that occur while stopping or pausing
5024 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005025 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005026 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5027 recentUnderruns > 0) {
5028 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005029 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005030 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005031 // Immediately account for FastTrack underruns.
5032 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005033
5034 // This is similar to the state machine for normal tracks,
5035 // with a few modifications for fast tracks.
5036 bool isActive = true;
5037 switch (track->mState) {
5038 case TrackBase::STOPPING_1:
5039 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005040 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005041 track->mState = TrackBase::STOPPING_2;
5042 }
5043 break;
5044 case TrackBase::PAUSING:
5045 // ramp down is not yet implemented
5046 track->setPaused();
5047 break;
5048 case TrackBase::RESUMING:
5049 // ramp up is not yet implemented
5050 track->mState = TrackBase::ACTIVE;
5051 break;
5052 case TrackBase::ACTIVE:
5053 if (recentFull > 0 || recentPartial > 0) {
5054 // track has provided at least some frames recently: reset retry count
5055 track->mRetryCount = kMaxTrackRetries;
5056 }
5057 if (recentUnderruns == 0) {
5058 // no recent underruns: stay active
5059 break;
5060 }
5061 // there has recently been an underrun of some kind
5062 if (track->sharedBuffer() == 0) {
5063 // were any of the recent underruns "empty" (no frames available)?
5064 if (recentEmpty == 0) {
5065 // no, then ignore the partial underruns as they are allowed indefinitely
5066 break;
5067 }
5068 // there has recently been an "empty" underrun: decrement the retry counter
5069 if (--(track->mRetryCount) > 0) {
5070 break;
5071 }
5072 // indicate to client process that the track was disabled because of underrun;
5073 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005074 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005075 // remove from active list, but state remains ACTIVE [confusing but true]
5076 isActive = false;
5077 break;
5078 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005079 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005080 case TrackBase::STOPPING_2:
5081 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005082 case TrackBase::STOPPED:
5083 case TrackBase::FLUSHED: // flush() while active
5084 // Check for presentation complete if track is inactive
5085 // We have consumed all the buffers of this track.
5086 // This would be incomplete if we auto-paused on underrun
5087 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005088 uint32_t latency = 0;
5089 status_t result = mOutput->stream->getLatency(&latency);
5090 ALOGE_IF(result != OK,
5091 "Error when retrieving output stream latency: %d", result);
5092 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005093 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005094 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5095 // track stays in active list until presentation is complete
5096 break;
5097 }
5098 }
5099 if (track->isStopping_2()) {
5100 track->mState = TrackBase::STOPPED;
5101 }
5102 if (track->isStopped()) {
5103 // Can't reset directly, as fast mixer is still polling this track
5104 // track->reset();
5105 // So instead mark this track as needing to be reset after push with ack
5106 resetMask |= 1 << i;
5107 }
5108 isActive = false;
5109 break;
5110 case TrackBase::IDLE:
5111 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005112 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005113 }
5114
5115 if (isActive) {
5116 // was it previously inactive?
5117 if (!(state->mTrackMask & (1 << j))) {
5118 ExtendedAudioBufferProvider *eabp = track;
5119 VolumeProvider *vp = track;
5120 fastTrack->mBufferProvider = eabp;
5121 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005122 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005123 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005124 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005125 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005126 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005127 fastTrack->mGeneration++;
5128 state->mTrackMask |= 1 << j;
5129 didModify = true;
5130 // no acknowledgement required for newly active tracks
5131 }
Kevin Rocard12381092018-04-11 09:19:59 -07005132 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005133 float volume;
5134 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5135 volume = 0.f;
5136 } else {
5137 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5138 }
5139
5140 handleVoipVolume_l(&volume);
5141
Eric Laurent81784c32012-11-19 14:55:58 -08005142 // cache the combined master volume and stream type volume for fast mixer; this
5143 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005144 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005145 proxy->framesReleased()).first;
5146 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005147 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005148 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5149 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5150 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005151
Kevin Rocard12381092018-04-11 09:19:59 -07005152 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005153 ++fastTracks;
5154 } else {
5155 // was it previously active?
5156 if (state->mTrackMask & (1 << j)) {
5157 fastTrack->mBufferProvider = NULL;
5158 fastTrack->mGeneration++;
5159 state->mTrackMask &= ~(1 << j);
5160 didModify = true;
5161 // If any fast tracks were removed, we must wait for acknowledgement
5162 // because we're about to decrement the last sp<> on those tracks.
5163 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5164 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005165 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5166 // AudioTrack may start (which may not be with a start() but with a write()
5167 // after underrun) and immediately paused or released. In that case the
5168 // FastTrack state hasn't had time to update.
5169 // TODO Remove the ALOGW when this theory is confirmed.
5170 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005171 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5172 j, track->mState, state->mTrackMask, recentUnderruns,
5173 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005174 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005175 }
5176 tracksToRemove->add(track);
5177 // Avoids a misleading display in dumpsys
5178 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5179 }
jiabin245cdd92018-12-07 17:55:15 -08005180 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5181 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5182 didModify = true;
5183 }
Eric Laurent81784c32012-11-19 14:55:58 -08005184 continue;
5185 }
5186
5187 { // local variable scope to avoid goto warning
5188
5189 audio_track_cblk_t* cblk = track->cblk();
5190
5191 // The first time a track is added we wait
5192 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005193 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005194
5195 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005196 // use the trackId as the AudioMixer name.
5197 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005198 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005199 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005200 track->mChannelMask,
5201 track->mFormat,
5202 track->mSessionId);
5203 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005204 ALOGW("%s(): AudioMixer cannot create track(%d)"
5205 " mask %#x, format %#x, sessionId %d",
5206 __func__, trackId,
5207 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005208 tracksToRemove->add(track);
5209 track->invalidate(); // consider it dead.
5210 continue;
5211 }
5212 }
5213
Eric Laurent81784c32012-11-19 14:55:58 -08005214 // make sure that we have enough frames to mix one full buffer.
5215 // enforce this condition only once to enable draining the buffer in case the client
5216 // app does not call stop() and relies on underrun to stop:
5217 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5218 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005219 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005220 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005221 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005222
5223 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005224 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005225 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5226 // add frames already consumed but not yet released by the resampler
5227 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005228 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005229
Eric Laurent81784c32012-11-19 14:55:58 -08005230 uint32_t minFrames = 1;
5231 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5232 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005233 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005234 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005235
5236 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005237 if (ATRACE_ENABLED()) {
5238 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005239 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005240 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005241 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005242 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005243 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005244 !track->isPaused() && !track->isTerminated())
5245 {
Andy Hungc0691382018-09-12 18:01:57 -07005246 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005247
5248 mixedTracks++;
5249
Andy Hung69aed5f2014-02-25 17:24:40 -08005250 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5251 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005252 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005253 if (track->mainBuffer() != mSinkBuffer &&
5254 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005255 if (mEffectBufferEnabled) {
5256 mEffectBufferValid = true; // Later can set directly.
5257 }
Eric Laurent81784c32012-11-19 14:55:58 -08005258 chain = getEffectChain_l(track->sessionId());
5259 // Delegate volume control to effect in track effect chain if needed
5260 if (chain != 0) {
5261 tracksWithEffect++;
5262 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005263 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005264 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005265 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005266 }
5267 }
5268
5269
5270 int param = AudioMixer::VOLUME;
5271 if (track->mFillingUpStatus == Track::FS_FILLED) {
5272 // no ramp for the first volume setting
5273 track->mFillingUpStatus = Track::FS_ACTIVE;
5274 if (track->mState == TrackBase::RESUMING) {
5275 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005276 // If a new track is paused immediately after start, do not ramp on resume.
5277 if (cblk->mServer != 0) {
5278 param = AudioMixer::RAMP_VOLUME;
5279 }
Eric Laurent81784c32012-11-19 14:55:58 -08005280 }
Andy Hungc0691382018-09-12 18:01:57 -07005281 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005282 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005283 // FIXME should not make a decision based on mServer
5284 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005285 // If the track is stopped before the first frame was mixed,
5286 // do not apply ramp
5287 param = AudioMixer::RAMP_VOLUME;
5288 }
5289
5290 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005291 uint32_t vl, vr; // in U8.24 integer format
5292 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005293 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005294 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005295 // Always fetch volumeshaper volume to ensure state is updated.
5296 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5297 const float vh = track->getVolumeHandler()->getVolume(
5298 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005299
Eric Laurenteab90452019-06-24 15:17:46 -07005300 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5301 v = 0;
5302 }
5303
5304 handleVoipVolume_l(&v);
5305
5306 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005307 vl = vr = 0;
5308 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005309 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005310 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005311 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005312 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5313 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005314 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005315 if (vlf > GAIN_FLOAT_UNITY) {
5316 ALOGV("Track left volume out of range: %.3g", vlf);
5317 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005318 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005319 if (vrf > GAIN_FLOAT_UNITY) {
5320 ALOGV("Track right volume out of range: %.3g", vrf);
5321 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005322 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005323 // now apply the master volume and stream type volume and shaper volume
5324 vlf *= v * vh;
5325 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005326 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005327 // then derive vl and vr as U8.24 versions for the effect chain
5328 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5329 vl = (uint32_t) (scaleto8_24 * vlf);
5330 vr = (uint32_t) (scaleto8_24 * vrf);
5331 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005332 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005333 // send level comes from shared memory and so may be corrupt
5334 if (sendLevel > MAX_GAIN_INT) {
5335 ALOGV("Track send level out of range: %04X", sendLevel);
5336 sendLevel = MAX_GAIN_INT;
5337 }
Andy Hung6be49402014-05-30 10:42:03 -07005338 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5339 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005340 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341
Kevin Rocard12381092018-04-11 09:19:59 -07005342 track->setFinalVolume((vrf + vlf) / 2.f);
5343
Eric Laurent81784c32012-11-19 14:55:58 -08005344 // Delegate volume control to effect in track effect chain if needed
5345 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5346 // Do not ramp volume if volume is controlled by effect
5347 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005348 // Update remaining floating point volume levels
5349 vlf = (float)vl / (1 << 24);
5350 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005351 track->mHasVolumeController = true;
5352 } else {
5353 // force no volume ramp when volume controller was just disabled or removed
5354 // from effect chain to avoid volume spike
5355 if (track->mHasVolumeController) {
5356 param = AudioMixer::VOLUME;
5357 }
5358 track->mHasVolumeController = false;
5359 }
5360
Eric Laurent81784c32012-11-19 14:55:58 -08005361 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005362 mAudioMixer->setBufferProvider(trackId, track);
5363 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005364
Andy Hungc0691382018-09-12 18:01:57 -07005365 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5366 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5367 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005368 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005369 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005370 AudioMixer::TRACK,
5371 AudioMixer::FORMAT, (void *)track->format());
5372 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005373 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005374 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005375 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005376 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005377 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005378 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005379 AudioMixer::MIXER_CHANNEL_MASK,
5380 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005381 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005382 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005383 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005384 if (reqSampleRate == 0) {
5385 reqSampleRate = mSampleRate;
5386 } else if (reqSampleRate > maxSampleRate) {
5387 reqSampleRate = maxSampleRate;
5388 }
Eric Laurent81784c32012-11-19 14:55:58 -08005389 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005390 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005391 AudioMixer::RESAMPLE,
5392 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005393 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005394
Andy Hung333ab962019-05-28 20:23:35 -07005395 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005396 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005397 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005398 AudioMixer::TIMESTRETCH,
5399 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005400 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005401
Andy Hung69aed5f2014-02-25 17:24:40 -08005402 /*
5403 * Select the appropriate output buffer for the track.
5404 *
Andy Hung98ef9782014-03-04 14:46:50 -08005405 * Tracks with effects go into their own effects chain buffer
5406 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005407 *
5408 * Other tracks can use mMixerBuffer for higher precision
5409 * channel accumulation. If this buffer is enabled
5410 * (mMixerBufferEnabled true), then selected tracks will accumulate
5411 * into it.
5412 *
5413 */
5414 if (mMixerBufferEnabled
5415 && (track->mainBuffer() == mSinkBuffer
5416 || track->mainBuffer() == mMixerBuffer)) {
5417 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005418 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005419 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005420 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005421 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005422 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005423 AudioMixer::TRACK,
5424 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5425 // TODO: override track->mainBuffer()?
5426 mMixerBufferValid = true;
5427 } else {
5428 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005429 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005430 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005431 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005432 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005433 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005434 AudioMixer::TRACK,
5435 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5436 }
Eric Laurent81784c32012-11-19 14:55:58 -08005437 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005438 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005439 AudioMixer::TRACK,
5440 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005441 mAudioMixer->setParameter(
5442 trackId,
5443 AudioMixer::TRACK,
5444 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005445 mAudioMixer->setParameter(
5446 trackId,
5447 AudioMixer::TRACK,
5448 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005449 mAudioMixer->setParameter(
5450 trackId,
5451 AudioMixer::TRACK,
5452 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005453
5454 // reset retry count
5455 track->mRetryCount = kMaxTrackRetries;
5456
5457 // If one track is ready, set the mixer ready if:
5458 // - the mixer was not ready during previous round OR
5459 // - no other track is not ready
5460 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5461 mixerStatus != MIXER_TRACKS_ENABLED) {
5462 mixerStatus = MIXER_TRACKS_READY;
5463 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005464
5465 // Enable the next few lines to instrument a test for underrun log handling.
5466 // TODO: Remove when we have a better way of testing the underrun log.
5467#if 0
5468 static int i;
5469 if ((++i & 0xf) == 0) {
5470 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5471 }
5472#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005473 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005474 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005475 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005476 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5477 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005478 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005479 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005480 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005481
Eric Laurent81784c32012-11-19 14:55:58 -08005482 // clear effect chain input buffer if an active track underruns to avoid sending
5483 // previous audio buffer again to effects
5484 chain = getEffectChain_l(track->sessionId());
5485 if (chain != 0) {
5486 chain->clearInputBuffer();
5487 }
5488
Andy Hungc0691382018-09-12 18:01:57 -07005489 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005490 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5491 track->isStopped() || track->isPaused()) {
5492 // We have consumed all the buffers of this track.
5493 // Remove it from the list of active tracks.
5494 // TODO: use actual buffer filling status instead of latency when available from
5495 // audio HAL
5496 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005497 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005498 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5499 if (track->isStopped()) {
5500 track->reset();
5501 }
5502 tracksToRemove->add(track);
5503 }
5504 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005505 // No buffers for this track. Give it a few chances to
5506 // fill a buffer, then remove it from active list.
5507 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005508 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5509 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005510 tracksToRemove->add(track);
5511 // indicate to client process that the track was disabled because of underrun;
5512 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005513 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005514 // If one track is not ready, mark the mixer also not ready if:
5515 // - the mixer was ready during previous round OR
5516 // - no other track is ready
5517 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5518 mixerStatus != MIXER_TRACKS_READY) {
5519 mixerStatus = MIXER_TRACKS_ENABLED;
5520 }
5521 }
Andy Hungc0691382018-09-12 18:01:57 -07005522 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005523 }
5524
5525 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005526
5527 }
5528
jiabin245cdd92018-12-07 17:55:15 -08005529 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5530 // When there is no fast track playing haptic and FastMixer exists,
5531 // enabling the first FastTrack, which provides mixed data from normal
5532 // tracks, to play haptic data.
5533 FastTrack *fastTrack = &state->mFastTracks[0];
5534 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5535 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5536 didModify = true;
5537 }
5538 }
5539
Eric Laurent81784c32012-11-19 14:55:58 -08005540 // Push the new FastMixer state if necessary
5541 bool pauseAudioWatchdog = false;
5542 if (didModify) {
5543 state->mFastTracksGen++;
5544 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5545 if (kUseFastMixer == FastMixer_Dynamic &&
5546 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5547 state->mCommand = FastMixerState::COLD_IDLE;
5548 state->mColdFutexAddr = &mFastMixerFutex;
5549 state->mColdGen++;
5550 mFastMixerFutex = 0;
5551 if (kUseFastMixer == FastMixer_Dynamic) {
5552 mNormalSink = mOutputSink;
5553 }
5554 // If we go into cold idle, need to wait for acknowledgement
5555 // so that fast mixer stops doing I/O.
5556 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5557 pauseAudioWatchdog = true;
5558 }
Eric Laurent81784c32012-11-19 14:55:58 -08005559 }
5560 if (sq != NULL) {
5561 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005562 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5563 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5564 // when bringing the output sink into standby.)
5565 //
5566 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5567 //
5568 // This occurs with BT suspend when we idle the FastMixer with
5569 // active tracks, which may be added or removed.
5570 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005571 }
5572#ifdef AUDIO_WATCHDOG
5573 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5574 mAudioWatchdog->pause();
5575 }
5576#endif
5577
5578 // Now perform the deferred reset on fast tracks that have stopped
5579 while (resetMask != 0) {
5580 size_t i = __builtin_ctz(resetMask);
5581 ALOG_ASSERT(i < count);
5582 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005583 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005584 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5585 track->reset();
5586 }
5587
Andy Hung80d03d22018-04-10 10:32:11 -07005588 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5589 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5590 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5591 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5592 // See also the implementation of destroyTrack_l().
5593 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005594 const int trackId = track->id();
5595 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5596 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005597 }
5598 }
5599
Eric Laurent81784c32012-11-19 14:55:58 -08005600 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005601 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005602
Eric Laurent97d547d2014-09-02 14:45:53 -07005603 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5604 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005605 }
5606
5607 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005608 // as long as there are effects we should clear the effects buffer, to avoid
5609 // passing a non-clean buffer to the effect chain
5610 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005611 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005612 // sink or mix buffer must be cleared if all tracks are connected to an
5613 // effect chain as in this case the mixer will not write to the sink or mix buffer
5614 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005615 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5616 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005617 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005618 if (mMixerBufferValid) {
5619 memset(mMixerBuffer, 0, mMixerBufferSize);
5620 // TODO: In testing, mSinkBuffer below need not be cleared because
5621 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5622 // after mixing.
5623 //
5624 // To enforce this guarantee:
5625 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5626 // (mixedTracks == 0 && fastTracks > 0))
5627 // must imply MIXER_TRACKS_READY.
5628 // Later, we may clear buffers regardless, and skip much of this logic.
5629 }
Andy Hung98ef9782014-03-04 14:46:50 -08005630 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005631 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005632 }
5633
5634 // if any fast tracks, then status is ready
5635 mMixerStatusIgnoringFastTracks = mixerStatus;
5636 if (fastTracks > 0) {
5637 mixerStatus = MIXER_TRACKS_READY;
5638 }
5639 return mixerStatus;
5640}
5641
Eric Laurentad7dd962016-09-22 12:38:37 -07005642// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005643uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005644{
5645 uint32_t trackCount = 0;
5646 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005647 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005648 trackCount++;
5649 }
5650 }
5651 return trackCount;
5652}
5653
Andy Hung1bc088a2018-02-09 15:57:31 -08005654// isTrackAllowed_l() must be called with ThreadBase::mLock held
5655bool AudioFlinger::MixerThread::isTrackAllowed_l(
5656 audio_channel_mask_t channelMask, audio_format_t format,
5657 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005658{
Andy Hung1bc088a2018-02-09 15:57:31 -08005659 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5660 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005661 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005662 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005663 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005664 ALOGW("%s: invalid format: %#x", __func__, format);
5665 return false;
5666 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005667 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005668 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5669 return false;
5670 }
5671 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005672}
5673
Eric Laurent10351942014-05-08 18:49:52 -07005674// checkForNewParameter_l() must be called with ThreadBase::mLock held
5675bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5676 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005677{
Eric Laurent81784c32012-11-19 14:55:58 -08005678 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005679 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005680
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005681 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005682
Eric Laurent10351942014-05-08 18:49:52 -07005683 AudioParameter param = AudioParameter(keyValuePair);
5684 int value;
5685 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5686 reconfig = true;
5687 }
5688 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005689 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005690 status = BAD_VALUE;
5691 } else {
5692 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005693 reconfig = true;
5694 }
Eric Laurent10351942014-05-08 18:49:52 -07005695 }
5696 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005697 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005698 status = BAD_VALUE;
5699 } else {
5700 // no need to save value, since it's constant
5701 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005702 }
Eric Laurent10351942014-05-08 18:49:52 -07005703 }
5704 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5705 // do not accept frame count changes if tracks are open as the track buffer
5706 // size depends on frame count and correct behavior would not be guaranteed
5707 // if frame count is changed after track creation
5708 if (!mTracks.isEmpty()) {
5709 status = INVALID_OPERATION;
5710 } else {
5711 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005712 }
Eric Laurent10351942014-05-08 18:49:52 -07005713 }
5714 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005715 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005716 }
Eric Laurent81784c32012-11-19 14:55:58 -08005717
Eric Laurent10351942014-05-08 18:49:52 -07005718 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005719 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005720 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005721 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005722 if (!mStandby) {
5723 mThreadMetrics.logEndInterval();
5724 mStandby = true;
5725 }
Eric Laurent10351942014-05-08 18:49:52 -07005726 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005727 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005728 }
Eric Laurent10351942014-05-08 18:49:52 -07005729 if (status == NO_ERROR && reconfig) {
5730 readOutputParameters_l();
5731 delete mAudioMixer;
5732 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005733 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005734 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005735 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005736 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005737 track->mChannelMask,
5738 track->mFormat,
5739 track->mSessionId);
5740 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005741 "%s(): AudioMixer cannot create track(%d)"
5742 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005743 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005744 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005745 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005746 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005747 }
Eric Laurent81784c32012-11-19 14:55:58 -08005748 }
5749
Dean Wheatley68918102021-03-19 22:09:19 +11005750 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005751}
5752
5753
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005754void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005755{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005756 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005757 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005758 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005759 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005760 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5761 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5762 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005763 if (hasFastMixer()) {
5764 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5765
5766 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5767 // while we are dumping it. It may be inconsistent, but it won't mutate!
5768 // This is a large object so we place it on the heap.
5769 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005770 const std::unique_ptr<FastMixerDumpState> copy =
5771 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005772 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005773
5774#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005775 // Similar for state queue
5776 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5777 observerCopy.dump(fd);
5778 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5779 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005780#endif
5781
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005782#ifdef AUDIO_WATCHDOG
5783 if (mAudioWatchdog != 0) {
5784 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5785 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5786 wdCopy.dump(fd);
5787 }
5788#endif
5789
5790 } else {
5791 dprintf(fd, " No FastMixer\n");
5792 }
Eric Laurent81784c32012-11-19 14:55:58 -08005793}
5794
5795uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5796{
5797 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5798}
5799
5800uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5801{
5802 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5803}
5804
5805void AudioFlinger::MixerThread::cacheParameters_l()
5806{
5807 PlaybackThread::cacheParameters_l();
5808
5809 // FIXME: Relaxed timing because of a certain device that can't meet latency
5810 // Should be reduced to 2x after the vendor fixes the driver issue
5811 // increase threshold again due to low power audio mode. The way this warning
5812 // threshold is calculated and its usefulness should be reconsidered anyway.
5813 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5814}
5815
5816// ----------------------------------------------------------------------------
5817
5818AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005819 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5820 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005821{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005822 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005823}
5824
Eric Laurent81784c32012-11-19 14:55:58 -08005825AudioFlinger::DirectOutputThread::~DirectOutputThread()
5826{
5827}
5828
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005829void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005830{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005831 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005832 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5833 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5834}
5835
5836void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5837{
5838 Mutex::Autolock _l(mLock);
5839 if (mMasterBalance != balance) {
5840 mMasterBalance.store(balance);
5841 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5842 broadcast_l();
5843 }
5844}
5845
Eric Laurent5850c4c2016-11-10 13:04:31 -08005846void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005847{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005848 float left, right;
5849
Andy Hung333ab962019-05-28 20:23:35 -07005850 // Ensure volumeshaper state always advances even when muted.
5851 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5852 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5853 proxy->framesReleased());
5854 mVolumeShaperActive = shaperActive;
5855
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005856 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005857 left = right = 0;
5858 } else {
5859 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005860 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005861
Glenn Kastenc56f3422014-03-21 17:53:17 -07005862 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5863 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5864 if (left > GAIN_FLOAT_UNITY) {
5865 left = GAIN_FLOAT_UNITY;
5866 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005867 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005868 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5869 if (right > GAIN_FLOAT_UNITY) {
5870 right = GAIN_FLOAT_UNITY;
5871 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005872 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005873 }
5874
5875 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005876 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005877 if (left != mLeftVolFloat || right != mRightVolFloat) {
5878 mLeftVolFloat = left;
5879 mRightVolFloat = right;
5880
Eric Laurentbfb1b832013-01-07 09:53:42 -08005881 // Delegate volume control to effect in track effect chain if needed
5882 // only one effect chain can be present on DirectOutputThread, so if
5883 // there is one, the track is connected to it
5884 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005885 // if effect chain exists, volume is handled by it.
5886 // Convert volumes from float to 8.24
5887 uint32_t vl = (uint32_t)(left * (1 << 24));
5888 uint32_t vr = (uint32_t)(right * (1 << 24));
5889 // Direct/Offload effect chains set output volume in setVolume_l().
5890 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5891 } else {
5892 // otherwise we directly set the volume.
5893 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005894 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005895 }
5896 }
5897}
5898
Phil Burk43b4dcc2015-06-09 16:53:44 -07005899void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5900{
5901 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005902 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005903
Eric Laurent0f0631e2015-07-06 18:01:25 -07005904 if (previousTrack != 0 && latestTrack != 0) {
5905 if (mType == DIRECT) {
5906 if (previousTrack.get() != latestTrack.get()) {
5907 mFlushPending = true;
5908 }
5909 } else /* mType == OFFLOAD */ {
5910 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5911 mFlushPending = true;
5912 }
5913 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005914 } else if (previousTrack == 0) {
5915 // there could be an old track added back during track transition for direct
5916 // output, so always issues flush to flush data of the previous track if it
5917 // was already destroyed with HAL paused, then flush can resume the playback
5918 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005919 }
5920 PlaybackThread::onAddNewTrack_l();
5921}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005922
Eric Laurent81784c32012-11-19 14:55:58 -08005923AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5924 Vector< sp<Track> > *tracksToRemove
5925)
5926{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005927 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005928 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005929 bool doHwPause = false;
5930 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005931
5932 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005933 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005934 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005935 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005936 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005937 continue;
5938 }
5939
Eric Laurent5850c4c2016-11-10 13:04:31 -08005940 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005941#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005942 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005943#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005944 // Only consider last track started for volume and mixer state control.
5945 // In theory an older track could underrun and restart after the new one starts
5946 // but as we only care about the transition phase between two tracks on a
5947 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005948 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005949 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005950
Kuowei Li23666472021-01-20 10:23:25 +08005951 if (track->isPausePending()) {
5952 track->pauseAck();
5953 // It is possible a track might have been flushed or stopped.
5954 // Other operations such as flush pending might occur on the next prepare.
5955 if (track->isPausing()) {
5956 track->setPaused();
5957 }
5958 // Always perform pause, as an immediate flush will change
5959 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005960 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005961 doHwPause = true;
5962 mHwPaused = true;
5963 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005964 } else if (track->isFlushPending()) {
5965 track->flushAck();
5966 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005967 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005968 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005969 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005970 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005971 if (last) {
5972 mLeftVolFloat = mRightVolFloat = -1.0;
5973 if (mHwPaused) {
5974 doHwResume = true;
5975 mHwPaused = false;
5976 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005977 }
5978 }
5979
Eric Laurent81784c32012-11-19 14:55:58 -08005980 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005981 // for all its buffers to be filled before processing it.
5982 // Allow draining the buffer in case the client
5983 // app does not call stop() and relies on underrun to stop:
5984 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07005985 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
5986 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
5987 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07005988 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07005989
5990 // target retry count that we will use is based on the time we wait for retries.
5991 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
5992 // the retry threshold is when we accept any size for PCM data. This is slightly
5993 // smaller than the retry count so we can push small bits of data without a glitch.
5994 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08005995 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005996 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07005997 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005998 minFrames = mNormalFrameCount;
5999 } else {
6000 minFrames = 1;
6001 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006002
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006003 const size_t framesReady = track->framesReady();
6004 const int trackId = track->id();
6005 if (ATRACE_ENABLED()) {
6006 std::string traceName("nRdy");
6007 traceName += std::to_string(trackId);
6008 ATRACE_INT(traceName.c_str(), framesReady);
6009 }
6010 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006011 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006012 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006013 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006014
6015 if (track->mFillingUpStatus == Track::FS_FILLED) {
6016 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006017 if (last) {
6018 // make sure processVolume_l() will apply new volume even if 0
6019 mLeftVolFloat = mRightVolFloat = -1.0;
6020 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006021 if (!mHwSupportsPause) {
6022 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006023 }
6024 }
6025
6026 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006027 processVolume_l(track, last);
6028 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006029 sp<Track> previousTrack = mPreviousTrack.promote();
6030 if (previousTrack != 0) {
6031 if (track != previousTrack.get()) {
6032 // Flush any data still being written from last track
6033 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006034 // Invalidate previous track to force a seek when resuming.
6035 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006036 }
6037 }
6038 mPreviousTrack = track;
6039
Eric Laurentd595b7c2013-04-03 17:27:56 -07006040 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006041 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006042 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006043 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006044 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006045 doHwResume = true;
6046 mHwPaused = false;
6047 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006048 }
Eric Laurent81784c32012-11-19 14:55:58 -08006049 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006050 // clear effect chain input buffer if the last active track started underruns
6051 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006052 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006053 mEffectChains[0]->clearInputBuffer();
6054 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006055 if (track->isStopping_1()) {
6056 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006057 if (last && mHwPaused) {
6058 doHwResume = true;
6059 mHwPaused = false;
6060 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006061 }
6062 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6063 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006064 // We have consumed all the buffers of this track.
6065 // Remove it from the list of active tracks.
Eric Laurentfd477972013-10-25 18:10:40 -07006066 if (mStandby || !last ||
Andy Hung59de4262021-06-14 10:53:54 -07006067 track->presentationComplete(latency_l()) ||
Jindong32dc26e2019-11-11 18:10:01 +08006068 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006069 if (track->isStopping_2()) {
6070 track->mState = TrackBase::STOPPED;
6071 }
Eric Laurent81784c32012-11-19 14:55:58 -08006072 if (track->isStopped()) {
6073 track->reset();
6074 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006075 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006076 }
6077 } else {
6078 // No buffers for this track. Give it a few chances to
6079 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006080 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006081 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006082 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006083 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006084 // indicate to client process that the track was disabled because of underrun;
6085 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006086 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006087 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6088 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006089 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6090 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006091 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006092 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006093 doHwPause = true;
6094 mHwPaused = true;
6095 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006096 } else if (last) {
6097 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006098 }
6099 }
6100 }
6101 }
6102
Eric Laurentd1f69b02014-12-15 14:33:13 -08006103 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006104 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006105 for (size_t i = 0; i < mTracks.size(); i++) {
6106 if (mTracks[i]->isFlushPending()) {
6107 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006108 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006109 }
6110 }
6111 }
6112
6113 // make sure the pause/flush/resume sequence is executed in the right order.
6114 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6115 // before flush and then resume HW. This can happen in case of pause/flush/resume
6116 // if resume is received before pause is executed.
6117 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006118 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006119 status_t result = mOutput->stream->pause();
6120 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006121 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006122 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006123 flushHw_l();
6124 }
6125 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006126 status_t result = mOutput->stream->resume();
6127 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006128 }
Eric Laurent81784c32012-11-19 14:55:58 -08006129 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006130 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006131
6132 return mixerStatus;
6133}
6134
6135void AudioFlinger::DirectOutputThread::threadLoop_mix()
6136{
Eric Laurent81784c32012-11-19 14:55:58 -08006137 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006138 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006139 // output audio to hardware
6140 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006141 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006142 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006143 status_t status = mActiveTrack->getNextBuffer(&buffer);
6144 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006145 // no need to pad with 0 for compressed audio
6146 if (audio_has_proportional_frames(mFormat)) {
6147 memset(curBuf, 0, frameCount * mFrameSize);
6148 }
Eric Laurent81784c32012-11-19 14:55:58 -08006149 break;
6150 }
6151 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6152 frameCount -= buffer.frameCount;
6153 curBuf += buffer.frameCount * mFrameSize;
6154 mActiveTrack->releaseBuffer(&buffer);
6155 }
Andy Hung2098f272014-02-27 14:00:06 -08006156 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006157 mSleepTimeUs = 0;
6158 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006159 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006160}
6161
6162void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6163{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006164 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006165 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006166 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006167 return;
6168 }
Andy Hung85ba3332021-04-27 17:40:26 -07006169 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6170 mSleepTimeUs = mActiveSleepTimeUs;
6171 } else {
6172 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006173 }
Andy Hung85ba3332021-04-27 17:40:26 -07006174 // Note: In S or later, we do not write zeroes for
6175 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006176}
6177
Eric Laurentd1f69b02014-12-15 14:33:13 -08006178void AudioFlinger::DirectOutputThread::threadLoop_exit()
6179{
6180 {
6181 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006182 for (size_t i = 0; i < mTracks.size(); i++) {
6183 if (mTracks[i]->isFlushPending()) {
6184 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006185 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006186 }
6187 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006188 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006189 flushHw_l();
6190 }
6191 }
6192 PlaybackThread::threadLoop_exit();
6193}
6194
6195// must be called with thread mutex locked
6196bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6197{
6198 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006199 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006200
6201 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6202 // after a timeout and we will enter standby then.
6203 if (mTracks.size() > 0) {
6204 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006205 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6206 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006207 }
6208
Eric Laurent5cff4032015-05-26 13:49:58 -07006209 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006210}
6211
Eric Laurent10351942014-05-08 18:49:52 -07006212// checkForNewParameter_l() must be called with ThreadBase::mLock held
6213bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6214 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006215{
6216 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006217 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006218
Eric Laurent10351942014-05-08 18:49:52 -07006219 AudioParameter param = AudioParameter(keyValuePair);
6220 int value;
6221 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006222 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006223 }
Eric Laurent10351942014-05-08 18:49:52 -07006224 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6225 // do not accept frame count changes if tracks are open as the track buffer
6226 // size depends on frame count and correct behavior would not be garantied
6227 // if frame count is changed after track creation
6228 if (!mTracks.isEmpty()) {
6229 status = INVALID_OPERATION;
6230 } else {
6231 reconfig = true;
6232 }
6233 }
6234 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006235 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006236 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006237 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006238 if (!mStandby) {
6239 mThreadMetrics.logEndInterval();
6240 mStandby = true;
6241 }
Eric Laurent10351942014-05-08 18:49:52 -07006242 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006243 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006244 }
6245 if (status == NO_ERROR && reconfig) {
6246 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006247 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006248 }
6249 }
6250
Dean Wheatley68918102021-03-19 22:09:19 +11006251 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006252}
6253
6254uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6255{
6256 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006257 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006258 time = PlaybackThread::activeSleepTimeUs();
6259 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006260 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006261 }
6262 return time;
6263}
6264
6265uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6266{
6267 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006268 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006269 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6270 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006271 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006272 }
6273 return time;
6274}
6275
6276uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6277{
6278 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006279 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006280 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6281 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006282 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006283 }
6284 return time;
6285}
6286
6287void AudioFlinger::DirectOutputThread::cacheParameters_l()
6288{
6289 PlaybackThread::cacheParameters_l();
6290
6291 // use shorter standby delay as on normal output to release
6292 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006293 // no delay on outputs with HW A/V sync
6294 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006295 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006296 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006297 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006298 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006299 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006300 }
Eric Laurent81784c32012-11-19 14:55:58 -08006301}
6302
Eric Laurente659ef42014-09-29 13:06:46 -07006303void AudioFlinger::DirectOutputThread::flushHw_l()
6304{
Phil Burk062e67a2015-02-11 13:40:50 -08006305 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006306 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006307 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006308 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006309 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006310}
6311
Andy Hung10cbff12017-02-21 17:30:14 -08006312int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6313 // If a VolumeShaper is active, we must wake up periodically to update volume.
6314 const int64_t NS_PER_MS = 1000000;
6315 return mVolumeShaperActive ?
6316 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6317}
6318
Eric Laurent81784c32012-11-19 14:55:58 -08006319// ----------------------------------------------------------------------------
6320
Eric Laurentbfb1b832013-01-07 09:53:42 -08006321AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006322 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006323 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006324 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006325 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006326 mDrainSequence(0),
6327 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006328{
6329}
6330
6331AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6332{
6333}
6334
6335void AudioFlinger::AsyncCallbackThread::onFirstRef()
6336{
6337 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6338}
6339
6340bool AudioFlinger::AsyncCallbackThread::threadLoop()
6341{
6342 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006343 uint32_t writeAckSequence;
6344 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006345 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006346
6347 {
6348 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006349 while (!((mWriteAckSequence & 1) ||
6350 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006351 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006352 exitPending())) {
6353 mWaitWorkCV.wait(mLock);
6354 }
6355
Eric Laurentbfb1b832013-01-07 09:53:42 -08006356 if (exitPending()) {
6357 break;
6358 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006359 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6360 mWriteAckSequence, mDrainSequence);
6361 writeAckSequence = mWriteAckSequence;
6362 mWriteAckSequence &= ~1;
6363 drainSequence = mDrainSequence;
6364 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006365 asyncError = mAsyncError;
6366 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006367 }
6368 {
Eric Laurent4de95592013-09-26 15:28:21 -07006369 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6370 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006371 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006372 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006373 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006374 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006375 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006376 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006377 if (asyncError) {
6378 playbackThread->onAsyncError();
6379 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006380 }
6381 }
6382 }
6383 return false;
6384}
6385
6386void AudioFlinger::AsyncCallbackThread::exit()
6387{
6388 ALOGV("AsyncCallbackThread::exit");
6389 Mutex::Autolock _l(mLock);
6390 requestExit();
6391 mWaitWorkCV.broadcast();
6392}
6393
Eric Laurent3b4529e2013-09-05 18:09:19 -07006394void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006395{
6396 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006397 // bit 0 is cleared
6398 mWriteAckSequence = sequence << 1;
6399}
6400
6401void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6402{
6403 Mutex::Autolock _l(mLock);
6404 // ignore unexpected callbacks
6405 if (mWriteAckSequence & 2) {
6406 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006407 mWaitWorkCV.signal();
6408 }
6409}
6410
Eric Laurent3b4529e2013-09-05 18:09:19 -07006411void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006412{
6413 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006414 // bit 0 is cleared
6415 mDrainSequence = sequence << 1;
6416}
6417
6418void AudioFlinger::AsyncCallbackThread::resetDraining()
6419{
6420 Mutex::Autolock _l(mLock);
6421 // ignore unexpected callbacks
6422 if (mDrainSequence & 2) {
6423 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006424 mWaitWorkCV.signal();
6425 }
6426}
6427
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006428void AudioFlinger::AsyncCallbackThread::setAsyncError()
6429{
6430 Mutex::Autolock _l(mLock);
6431 mAsyncError = true;
6432 mWaitWorkCV.signal();
6433}
6434
Eric Laurentbfb1b832013-01-07 09:53:42 -08006435
6436// ----------------------------------------------------------------------------
6437AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006438 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6439 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006440 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6441 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006442{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006443 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006444 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006445 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006446}
6447
Eric Laurentbfb1b832013-01-07 09:53:42 -08006448void AudioFlinger::OffloadThread::threadLoop_exit()
6449{
6450 if (mFlushPending || mHwPaused) {
6451 // If a flush is pending or track was paused, just discard buffered data
6452 flushHw_l();
6453 } else {
6454 mMixerStatus = MIXER_DRAIN_ALL;
6455 threadLoop_drain();
6456 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006457 if (mUseAsyncWrite) {
6458 ALOG_ASSERT(mCallbackThread != 0);
6459 mCallbackThread->exit();
6460 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006461 PlaybackThread::threadLoop_exit();
6462}
6463
6464AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6465 Vector< sp<Track> > *tracksToRemove
6466)
6467{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006468 size_t count = mActiveTracks.size();
6469
6470 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006471 bool doHwPause = false;
6472 bool doHwResume = false;
6473
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006474 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006475
Eric Laurentbfb1b832013-01-07 09:53:42 -08006476 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006477 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006478 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006479#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006480 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006481#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006482 // Only consider last track started for volume and mixer state control.
6483 // In theory an older track could underrun and restart after the new one starts
6484 // but as we only care about the transition phase between two tracks on a
6485 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006486 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006487 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006488
Haynes Mathew George7844f672014-01-15 12:32:55 -08006489 if (track->isInvalid()) {
6490 ALOGW("An invalidated track shouldn't be in active list");
6491 tracksToRemove->add(track);
6492 continue;
6493 }
6494
6495 if (track->mState == TrackBase::IDLE) {
6496 ALOGW("An idle track shouldn't be in active list");
6497 continue;
6498 }
6499
Kuowei Li23666472021-01-20 10:23:25 +08006500 if (track->isPausePending()) {
6501 track->pauseAck();
6502 // It is possible a track might have been flushed or stopped.
6503 // Other operations such as flush pending might occur on the next prepare.
6504 if (track->isPausing()) {
6505 track->setPaused();
6506 }
6507 // Always perform pause if last, as an immediate flush will change
6508 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006509 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006510 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006511 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006512 mHwPaused = true;
6513 }
6514 // If we were part way through writing the mixbuffer to
6515 // the HAL we must save this until we resume
6516 // BUG - this will be wrong if a different track is made active,
6517 // in that case we want to discard the pending data in the
6518 // mixbuffer and tell the client to present it again when the
6519 // track is resumed
6520 mPausedWriteLength = mCurrentWriteLength;
6521 mPausedBytesRemaining = mBytesRemaining;
6522 mBytesRemaining = 0; // stop writing
6523 }
6524 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006525 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006526 if (track->isStopping_1()) {
6527 track->mRetryCount = kMaxTrackStopRetriesOffload;
6528 } else {
6529 track->mRetryCount = kMaxTrackRetriesOffload;
6530 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006531 track->flushAck();
6532 if (last) {
6533 mFlushPending = true;
6534 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006535 } else if (track->isResumePending()){
6536 track->resumeAck();
6537 if (last) {
6538 if (mPausedBytesRemaining) {
6539 // Need to continue write that was interrupted
6540 mCurrentWriteLength = mPausedWriteLength;
6541 mBytesRemaining = mPausedBytesRemaining;
6542 mPausedBytesRemaining = 0;
6543 }
6544 if (mHwPaused) {
6545 doHwResume = true;
6546 mHwPaused = false;
6547 // threadLoop_mix() will handle the case that we need to
6548 // resume an interrupted write
6549 }
6550 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006551 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006552
Eric Laurent3df841a2016-07-15 15:15:40 -07006553 mLeftVolFloat = mRightVolFloat = -1.0;
6554
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006555 // Do not handle new data in this iteration even if track->framesReady()
6556 mixerStatus = MIXER_TRACKS_ENABLED;
6557 }
6558 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006559 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006560 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006561 if (track->mFillingUpStatus == Track::FS_FILLED) {
6562 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006563 if (last) {
6564 // make sure processVolume_l() will apply new volume even if 0
6565 mLeftVolFloat = mRightVolFloat = -1.0;
6566 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006567 }
6568
6569 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006570 sp<Track> previousTrack = mPreviousTrack.promote();
6571 if (previousTrack != 0) {
6572 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006573 // Flush any data still being written from last track
6574 mBytesRemaining = 0;
6575 if (mPausedBytesRemaining) {
6576 // Last track was paused so we also need to flush saved
6577 // mixbuffer state and invalidate track so that it will
6578 // re-submit that unwritten data when it is next resumed
6579 mPausedBytesRemaining = 0;
6580 // Invalidate is a bit drastic - would be more efficient
6581 // to have a flag to tell client that some of the
6582 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006583 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006584 }
6585 // flush data already sent to the DSP if changing audio session as audio
6586 // comes from a different source. Also invalidate previous track to force a
6587 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006588 if (previousTrack->sessionId() != track->sessionId()) {
6589 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006590 }
6591 }
6592 }
6593 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006594 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006595 if (track->isStopping_1()) {
6596 track->mRetryCount = kMaxTrackStopRetriesOffload;
6597 } else {
6598 track->mRetryCount = kMaxTrackRetriesOffload;
6599 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006600 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006601 mixerStatus = MIXER_TRACKS_READY;
6602 }
6603 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006604 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006605 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006606 if (--(track->mRetryCount) <= 0) {
6607 // Hardware buffer can hold a large amount of audio so we must
6608 // wait for all current track's data to drain before we say
6609 // that the track is stopped.
6610 if (mBytesRemaining == 0) {
6611 // Only start draining when all data in mixbuffer
6612 // has been written
6613 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6614 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6615 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6616 if (last && !mStandby) {
6617 // do not modify drain sequence if we are already draining. This happens
6618 // when resuming from pause after drain.
6619 if ((mDrainSequence & 1) == 0) {
6620 mSleepTimeUs = 0;
6621 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6622 mixerStatus = MIXER_DRAIN_TRACK;
6623 mDrainSequence += 2;
6624 }
6625 if (mHwPaused) {
6626 // It is possible to move from PAUSED to STOPPING_1 without
6627 // a resume so we must ensure hardware is running
6628 doHwResume = true;
6629 mHwPaused = false;
6630 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006631 }
6632 }
Eric Laurente93cc032016-05-05 10:15:10 -07006633 } else if (last) {
6634 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6635 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006636 }
6637 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006638 // Drain has completed or we are in standby, signal presentation complete
6639 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006640 track->mState = TrackBase::STOPPED;
Andy Hung59de4262021-06-14 10:53:54 -07006641 track->presentationComplete(latency_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006642 track->reset();
6643 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006644 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006645 if (!mUseAsyncWrite) {
6646 // If we don't get explicit drain notification we must
6647 // register discontinuity regardless of whether this is
6648 // the previous (!last) or the upcoming (last) track
6649 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006650 mTimestampVerifier.discontinuity(
6651 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006652 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006653 }
6654 } else {
6655 // No buffers for this track. Give it a few chances to
6656 // fill a buffer, then remove it from active list.
6657 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006658 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006659 uint64_t position = 0;
6660 struct timespec unused;
6661 // The running check restarts the retry counter at least once.
6662 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6663 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6664 running = true;
6665 mOffloadUnderrunPosition = position;
6666 }
6667 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006668 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6669 (long long)position, (long long)mOffloadUnderrunPosition);
6670 }
6671 if (running) { // still running, give us more time.
6672 track->mRetryCount = kMaxTrackRetriesOffload;
6673 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006674 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6675 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006676 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006677 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006678 // it will then automatically call start() when data is available
6679 track->disable();
6680 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006681 } else if (last){
6682 mixerStatus = MIXER_TRACKS_ENABLED;
6683 }
6684 }
6685 }
6686 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006687 if (track->isReady()) { // check ready to prevent premature start.
6688 processVolume_l(track, last);
6689 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006690 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006691
Eric Laurentea0fade2013-10-04 16:23:48 -07006692 // make sure the pause/flush/resume sequence is executed in the right order.
6693 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6694 // before flush and then resume HW. This can happen in case of pause/flush/resume
6695 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006696 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006697 status_t result = mOutput->stream->pause();
6698 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006699 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006700 if (mFlushPending) {
6701 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006702 }
Eric Laurentfd477972013-10-25 18:10:40 -07006703 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006704 status_t result = mOutput->stream->resume();
6705 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006706 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006707
Eric Laurentbfb1b832013-01-07 09:53:42 -08006708 // remove all the tracks that need to be...
6709 removeTracks_l(*tracksToRemove);
6710
6711 return mixerStatus;
6712}
6713
Eric Laurentbfb1b832013-01-07 09:53:42 -08006714// must be called with thread mutex locked
6715bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6716{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006717 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6718 mWriteAckSequence, mDrainSequence);
6719 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006720 return true;
6721 }
6722 return false;
6723}
6724
Eric Laurentbfb1b832013-01-07 09:53:42 -08006725bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6726{
6727 Mutex::Autolock _l(mLock);
6728 return waitingAsyncCallback_l();
6729}
6730
6731void AudioFlinger::OffloadThread::flushHw_l()
6732{
Eric Laurente659ef42014-09-29 13:06:46 -07006733 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006734 // Flush anything still waiting in the mixbuffer
6735 mCurrentWriteLength = 0;
6736 mBytesRemaining = 0;
6737 mPausedWriteLength = 0;
6738 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006739 // reset bytes written count to reflect that DSP buffers are empty after flush.
6740 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006741 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006742
Eric Laurentbfb1b832013-01-07 09:53:42 -08006743 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006744 // discard any pending drain or write ack by incrementing sequence
6745 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6746 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006747 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006748 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6749 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006750 }
6751}
6752
Haynes Mathew George05317d22016-05-03 16:34:26 -07006753void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6754{
6755 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006756 if (PlaybackThread::invalidateTracks_l(streamType)) {
6757 mFlushPending = true;
6758 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006759}
6760
Eric Laurentbfb1b832013-01-07 09:53:42 -08006761// ----------------------------------------------------------------------------
6762
Eric Laurent81784c32012-11-19 14:55:58 -08006763AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006764 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006765 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006766 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006767 mWaitTimeMs(UINT_MAX)
6768{
6769 addOutputTrack(mainThread);
6770}
6771
6772AudioFlinger::DuplicatingThread::~DuplicatingThread()
6773{
6774 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6775 mOutputTracks[i]->destroy();
6776 }
6777}
6778
6779void AudioFlinger::DuplicatingThread::threadLoop_mix()
6780{
6781 // mix buffers...
6782 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006783 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006784 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006785 if (mMixerBufferValid) {
6786 memset(mMixerBuffer, 0, mMixerBufferSize);
6787 } else {
6788 memset(mSinkBuffer, 0, mSinkBufferSize);
6789 }
Eric Laurent81784c32012-11-19 14:55:58 -08006790 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006791 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006792 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006793 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006794 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006795}
6796
6797void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6798{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006799 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006800 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006801 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006802 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006803 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006804 }
6805 } else if (mBytesWritten != 0) {
6806 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6807 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006808 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006809 } else {
6810 // flush remaining overflow buffers in output tracks
6811 writeFrames = 0;
6812 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006813 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006814 }
6815}
6816
Eric Laurentbfb1b832013-01-07 09:53:42 -08006817ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006818{
6819 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006820 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6821
6822 // Consider the first OutputTrack for timestamp and frame counting.
6823
6824 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6825 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6826 // we always claim success.
6827 if (i == 0) {
6828 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6829 ALOGD_IF(correction != 0 && writeFrames != 0,
6830 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6831 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6832 mFramesWritten -= correction;
6833 }
6834
6835 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006836 }
Andy Hungcf10d742020-04-28 15:38:24 -07006837 if (mStandby) {
6838 mThreadMetrics.logBeginInterval();
6839 mStandby = false;
6840 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006841 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006842}
6843
6844void AudioFlinger::DuplicatingThread::threadLoop_standby()
6845{
6846 // DuplicatingThread implements standby by stopping all tracks
6847 for (size_t i = 0; i < outputTracks.size(); i++) {
6848 outputTracks[i]->stop();
6849 }
6850}
6851
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006852void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006853{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006854 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006855
6856 std::stringstream ss;
6857 const size_t numTracks = mOutputTracks.size();
6858 ss << " " << numTracks << " OutputTracks";
6859 if (numTracks > 0) {
6860 ss << ":";
6861 for (const auto &track : mOutputTracks) {
6862 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006863 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006864 if (thread.get() != nullptr) {
6865 ss << thread.get() << ", " << thread->id();
6866 } else {
6867 ss << "null";
6868 }
6869 ss << ")";
6870 }
6871 }
6872 ss << "\n";
6873 std::string result = ss.str();
6874 write(fd, result.c_str(), result.size());
6875}
6876
Eric Laurent81784c32012-11-19 14:55:58 -08006877void AudioFlinger::DuplicatingThread::saveOutputTracks()
6878{
6879 outputTracks = mOutputTracks;
6880}
6881
6882void AudioFlinger::DuplicatingThread::clearOutputTracks()
6883{
6884 outputTracks.clear();
6885}
6886
6887void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6888{
6889 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006890 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6891 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6892 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6893 const size_t frameCount =
6894 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6895 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6896 // from different OutputTracks and their associated MixerThreads (e.g. one may
6897 // nearly empty and the other may be dropping data).
6898
Svet Ganov33761132021-05-13 22:51:08 +00006899 // TODO b/182392769: use attribution source util, move to server edge
6900 AttributionSourceState attributionSource = AttributionSourceState();
6901 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006902 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00006903 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006904 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00006905 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08006906 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006907 this,
6908 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006909 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006910 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006911 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00006912 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006913 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6914 if (status != NO_ERROR) {
6915 ALOGE("addOutputTrack() initCheck failed %d", status);
6916 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006917 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006918 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6919 mOutputTracks.add(outputTrack);
6920 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6921 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006922}
6923
6924void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6925{
6926 Mutex::Autolock _l(mLock);
6927 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6928 if (mOutputTracks[i]->thread() == thread) {
6929 mOutputTracks[i]->destroy();
6930 mOutputTracks.removeAt(i);
6931 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006932 if (thread->getOutput() == mOutput) {
6933 mOutput = NULL;
6934 }
Eric Laurent81784c32012-11-19 14:55:58 -08006935 return;
6936 }
6937 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006938 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006939}
6940
6941// caller must hold mLock
6942void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6943{
6944 mWaitTimeMs = UINT_MAX;
6945 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6946 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6947 if (strong != 0) {
6948 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6949 if (waitTimeMs < mWaitTimeMs) {
6950 mWaitTimeMs = waitTimeMs;
6951 }
6952 }
6953 }
6954}
6955
6956
6957bool AudioFlinger::DuplicatingThread::outputsReady(
6958 const SortedVector< sp<OutputTrack> > &outputTracks)
6959{
6960 for (size_t i = 0; i < outputTracks.size(); i++) {
6961 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6962 if (thread == 0) {
6963 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6964 outputTracks[i].get());
6965 return false;
6966 }
6967 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6968 // see note at standby() declaration
6969 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6970 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6971 thread.get());
6972 return false;
6973 }
6974 }
6975 return true;
6976}
6977
Kevin Rocard12381092018-04-11 09:19:59 -07006978void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6979 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006980{
Kevin Rocard12381092018-04-11 09:19:59 -07006981 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6982 outputTrack->setMetadatas(metadata.tracks);
6983 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006984}
6985
Eric Laurent81784c32012-11-19 14:55:58 -08006986uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6987{
6988 return (mWaitTimeMs * 1000) / 2;
6989}
6990
6991void AudioFlinger::DuplicatingThread::cacheParameters_l()
6992{
6993 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6994 updateWaitTime_l();
6995
6996 MixerThread::cacheParameters_l();
6997}
6998
Eric Laurent6acd1d42017-01-04 14:23:29 -08006999
Eric Laurent81784c32012-11-19 14:55:58 -08007000// ----------------------------------------------------------------------------
7001// Record
7002// ----------------------------------------------------------------------------
7003
7004AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7005 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007006 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007007 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007008 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007009 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007010 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007011 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007012 mActiveTracks(&this->mLocalLog),
7013 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007014 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007015 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007016 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7017 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007018 // mFastCapture below
7019 , mFastCaptureFutex(0)
7020 // mInputSource
7021 // mPipeSink
7022 // mPipeSource
7023 , mPipeFramesP2(0)
7024 // mPipeMemory
7025 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007026 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007027 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007028{
Glenn Kastend7dca052015-03-05 16:05:54 -08007029 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7030 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007031
George Burgess IVa8f90c12020-05-14 11:27:19 -07007032 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007033 mIsMsdDevice = strcmp(
7034 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7035 }
7036
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007037 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007038
Andy Hungc8fddf32018-08-08 18:32:37 -07007039 // TODO: We may also match on address as well as device type for
7040 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007041 // TODO: This property should be ensure that only contains one single device type.
7042 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7043 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007044 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7045 : AUDIO_DEVICE_NONE));
7046
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007047 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007048 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007049 size_t numCounterOffers = 0;
7050 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007051#if !LOG_NDEBUG
7052 ssize_t index =
7053#else
7054 (void)
7055#endif
7056 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007057 ALOG_ASSERT(index == 0);
7058
7059 // initialize fast capture depending on configuration
7060 bool initFastCapture;
7061 switch (kUseFastCapture) {
7062 case FastCapture_Never:
7063 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007064 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007065 break;
7066 case FastCapture_Always:
7067 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007068 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007069 break;
7070 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007071 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007072 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7073 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7074 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007075 break;
7076 // case FastCapture_Dynamic:
7077 }
7078
7079 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007080 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007081 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007082 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7083 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007084 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007085 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007086 const sp<MemoryDealer> roHeap(readOnlyHeap());
7087 sp<IMemory> pipeMemory;
7088 if ((roHeap == 0) ||
7089 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007090 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007091 ALOGE("not enough memory for pipe buffer size=%zu; "
7092 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7093 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7094 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007095 goto failed;
7096 }
7097 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7098 memset(pipeBuffer, 0, pipeSize);
7099 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7100 const NBAIO_Format offers[1] = {format};
7101 size_t numCounterOffers = 0;
7102 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7103 ALOG_ASSERT(index == 0);
7104 mPipeSink = pipe;
7105 PipeReader *pipeReader = new PipeReader(*pipe);
7106 numCounterOffers = 0;
7107 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7108 ALOG_ASSERT(index == 0);
7109 mPipeSource = pipeReader;
7110 mPipeFramesP2 = pipeFramesP2;
7111 mPipeMemory = pipeMemory;
7112
7113 // create fast capture
7114 mFastCapture = new FastCapture();
7115 FastCaptureStateQueue *sq = mFastCapture->sq();
7116#ifdef STATE_QUEUE_DUMP
7117 // FIXME
7118#endif
7119 FastCaptureState *state = sq->begin();
7120 state->mCblk = NULL;
7121 state->mInputSource = mInputSource.get();
7122 state->mInputSourceGen++;
7123 state->mPipeSink = pipe;
7124 state->mPipeSinkGen++;
7125 state->mFrameCount = mFrameCount;
7126 state->mCommand = FastCaptureState::COLD_IDLE;
7127 // already done in constructor initialization list
7128 //mFastCaptureFutex = 0;
7129 state->mColdFutexAddr = &mFastCaptureFutex;
7130 state->mColdGen++;
7131 state->mDumpState = &mFastCaptureDumpState;
7132#ifdef TEE_SINK
7133 // FIXME
7134#endif
7135 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7136 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7137 sq->end();
7138 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7139
7140 // start the fast capture
7141 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7142 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007143 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007144 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007145#ifdef AUDIO_WATCHDOG
7146 // FIXME
7147#endif
7148
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007149 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007150 }
Andy Hung8946a282018-04-19 20:04:56 -07007151#ifdef TEE_SINK
7152 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7153 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7154#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007155failed: ;
7156
7157 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007158}
7159
Eric Laurent81784c32012-11-19 14:55:58 -08007160AudioFlinger::RecordThread::~RecordThread()
7161{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007162 if (mFastCapture != 0) {
7163 FastCaptureStateQueue *sq = mFastCapture->sq();
7164 FastCaptureState *state = sq->begin();
7165 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7166 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7167 if (old == -1) {
7168 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7169 }
7170 }
7171 state->mCommand = FastCaptureState::EXIT;
7172 sq->end();
7173 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7174 mFastCapture->join();
7175 mFastCapture.clear();
7176 }
7177 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007178 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007179 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007180}
7181
7182void AudioFlinger::RecordThread::onFirstRef()
7183{
Glenn Kastend7dca052015-03-05 16:05:54 -08007184 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007185}
7186
Eric Laurent555530a2017-02-07 18:17:24 -08007187void AudioFlinger::RecordThread::preExit()
7188{
7189 ALOGV(" preExit()");
7190 Mutex::Autolock _l(mLock);
7191 for (size_t i = 0; i < mTracks.size(); i++) {
7192 sp<RecordTrack> track = mTracks[i];
7193 track->invalidate();
7194 }
7195 mActiveTracks.clear();
7196 mStartStopCond.broadcast();
7197}
7198
Eric Laurent81784c32012-11-19 14:55:58 -08007199bool AudioFlinger::RecordThread::threadLoop()
7200{
Eric Laurent81784c32012-11-19 14:55:58 -08007201 nsecs_t lastWarning = 0;
7202
7203 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007204
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007205reacquire_wakelock:
7206 sp<RecordTrack> activeTrack;
7207 {
7208 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007209 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007210 }
7211
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007212 // used to request a deferred sleep, to be executed later while mutex is unlocked
7213 uint32_t sleepUs = 0;
7214
Andy Hung446f4df2019-02-21 12:26:41 -08007215 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7216
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007217 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007218 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007219 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007220
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007221 // activeTracks accumulates a copy of a subset of mActiveTracks
7222 Vector< sp<RecordTrack> > activeTracks;
7223
Glenn Kasten735f45f2014-08-18 15:51:59 -07007224 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007225 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007226
Glenn Kasten735f45f2014-08-18 15:51:59 -07007227 // reference to a fast track which is about to be removed
7228 sp<RecordTrack> fastTrackToRemove;
7229
Eric Laurent33403f02020-05-29 18:35:06 -07007230 bool silenceFastCapture = false;
7231
Eric Laurent81784c32012-11-19 14:55:58 -08007232 { // scope for mLock
7233 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007234
Eric Laurent021cf962014-05-13 10:18:14 -07007235 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007236
Eric Laurent000a4192014-01-29 15:17:32 -08007237 // check exitPending here because checkForNewParameters_l() and
7238 // checkForNewParameters_l() can temporarily release mLock
7239 if (exitPending()) {
7240 break;
7241 }
7242
Eric Laurent5c25d562016-07-13 17:17:45 -07007243 // sleep with mutex unlocked
7244 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007245 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007246 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7247 ATRACE_END();
7248 sleepUs = 0;
7249 continue;
7250 }
7251
Glenn Kasten2b806402013-11-20 16:37:38 -08007252 // if no active track(s), then standby and release wakelock
7253 size_t size = mActiveTracks.size();
7254 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007255 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007256 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007257 releaseWakeLock_l();
7258 ALOGV("RecordThread: loop stopping");
7259 // go to sleep
7260 mWaitWorkCV.wait(mLock);
7261 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007262 goto reacquire_wakelock;
7263 }
7264
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007265 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007266 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007267 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007268
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007269 activeTrack = mActiveTracks[i];
7270 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007271 if (activeTrack->isFastTrack()) {
7272 ALOG_ASSERT(fastTrackToRemove == 0);
7273 fastTrackToRemove = activeTrack;
7274 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007275 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007276 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007277 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007278 continue;
7279 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007280
7281 TrackBase::track_state activeTrackState = activeTrack->mState;
7282 switch (activeTrackState) {
7283
7284 case TrackBase::PAUSING:
7285 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007286 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007287 doBroadcast = true;
7288 size--;
7289 continue;
7290
7291 case TrackBase::STARTING_1:
7292 sleepUs = 10000;
7293 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007294 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007295 continue;
7296
7297 case TrackBase::STARTING_2:
7298 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007299 if (mStandby) {
7300 mThreadMetrics.logBeginInterval();
7301 mStandby = false;
7302 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007303 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007304 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007305 break;
7306
7307 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007308 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007309 break;
7310
Andy Hungce685402018-10-05 17:23:27 -07007311 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7312 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7313 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007314 default:
Andy Hungce685402018-10-05 17:23:27 -07007315 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7316 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007317 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007318
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007319 if (activeTrack->isFastTrack()) {
7320 ALOG_ASSERT(!mFastTrackAvail);
7321 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007322 // if the active fast track is silenced either:
7323 // 1) silence the whole capture from fast capture buffer if this is
7324 // the only active track
7325 // 2) invalidate this track: this will cause the client to reconnect and possibly
7326 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007327 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007328 if (activeTrack->isSilenced()) {
7329 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007330 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007331 } else {
7332 silenceFastCapture = true;
7333 }
7334 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007335 // Invalidate fast tracks if access to audio history is required as this is not
7336 // possible with fast tracks. Once the fast track has been invalidated, no new
7337 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7338 if (mMaxSharedAudioHistoryMs != 0) {
7339 invalidate = true;
7340 }
7341 if (invalidate) {
7342 activeTrack->invalidate();
7343 ALOG_ASSERT(fastTrackToRemove == 0);
7344 fastTrackToRemove = activeTrack;
7345 removeTrack_l(activeTrack);
7346 mActiveTracks.remove(activeTrack);
7347 size--;
7348 continue;
7349 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007350 fastTrack = activeTrack;
7351 }
Eric Laurent33403f02020-05-29 18:35:06 -07007352
7353 activeTracks.add(activeTrack);
7354 i++;
7355
Glenn Kasten9e982352013-08-14 14:39:50 -07007356 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007357
Andy Hungdae27702016-10-31 14:01:16 -07007358 mActiveTracks.updatePowerState(this);
7359
Kevin Rocard069c2712018-03-29 19:09:14 -07007360 updateMetadata_l();
7361
Eric Laurent5c25d562016-07-13 17:17:45 -07007362 if (allStopped) {
7363 standbyIfNotAlreadyInStandby();
7364 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007365 if (doBroadcast) {
7366 mStartStopCond.broadcast();
7367 }
7368
7369 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007370 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007371 if (sleepUs == 0) {
7372 sleepUs = kRecordThreadSleepUs;
7373 }
7374 continue;
7375 }
7376 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007377
Eric Laurent81784c32012-11-19 14:55:58 -08007378 lockEffectChains_l(effectChains);
7379 }
7380
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007381 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007382
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007383 size_t size = effectChains.size();
7384 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007385 // thread mutex is not locked, but effect chain is locked
7386 effectChains[i]->process_l();
7387 }
7388
Glenn Kasten735f45f2014-08-18 15:51:59 -07007389 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007390 if (mFastCapture != 0) {
7391 FastCaptureStateQueue *sq = mFastCapture->sq();
7392 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007393 bool didModify = false;
7394 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007395 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7396 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7397 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7398 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7399 if (old == -1) {
7400 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7401 }
7402 }
7403 state->mCommand = FastCaptureState::READ_WRITE;
7404#if 0 // FIXME
7405 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007406 FastThreadDumpState::kSamplingNforLowRamDevice :
7407 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007408#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007409 didModify = true;
7410 }
7411 audio_track_cblk_t *cblkOld = state->mCblk;
7412 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7413 if (cblkNew != cblkOld) {
7414 state->mCblk = cblkNew;
7415 // block until acked if removing a fast track
7416 if (cblkOld != NULL) {
7417 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7418 }
7419 didModify = true;
7420 }
jiabin01c8f562018-07-19 17:47:28 -07007421 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7422 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7423 if (state->mFastPatchRecordBufferProvider != abp) {
7424 state->mFastPatchRecordBufferProvider = abp;
7425 state->mFastPatchRecordFormat = fastTrack == 0 ?
7426 AUDIO_FORMAT_INVALID : fastTrack->format();
7427 didModify = true;
7428 }
Eric Laurent33403f02020-05-29 18:35:06 -07007429 if (state->mSilenceCapture != silenceFastCapture) {
7430 state->mSilenceCapture = silenceFastCapture;
7431 didModify = true;
7432 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007433 sq->end(didModify);
7434 if (didModify) {
7435 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007436#if 0
7437 if (kUseFastCapture == FastCapture_Dynamic) {
7438 mNormalSource = mPipeSource;
7439 }
7440#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007441 }
7442 }
7443
Glenn Kasten735f45f2014-08-18 15:51:59 -07007444 // now run the fast track destructor with thread mutex unlocked
7445 fastTrackToRemove.clear();
7446
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007447 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7448 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7449 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7450 // If destination is non-contiguous, first read past the nominal end of buffer, then
7451 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007452
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007453 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007454 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007455 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007456
7457 // If an NBAIO source is present, use it to read the normal capture's data
7458 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007459 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007460
7461 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7462 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7463 // we immediately retry the read() to get data and prevent another overflow.
7464 for (int retries = 0; retries <= 2; ++retries) {
7465 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7466 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7467 framesToRead);
7468 if (framesRead != OVERRUN) break;
7469 }
7470
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007471 const ssize_t availableToRead = mPipeSource->availableToRead();
7472 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007473 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007474 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7475 "more frames to read than fifo size, %zd > %zu",
7476 availableToRead, mPipeFramesP2);
7477 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7478 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7479 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7480 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007481 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7482 }
7483 if (framesRead < 0) {
7484 status_t status = (status_t) framesRead;
7485 switch (status) {
7486 case OVERRUN:
7487 ALOGW("overrun on read from pipe");
7488 framesRead = 0;
7489 break;
7490 case NEGOTIATE:
7491 ALOGE("re-negotiation is needed");
7492 framesRead = -1; // Will cause an attempt to recover.
7493 break;
7494 default:
7495 ALOGE("unknown error %d on read from pipe", status);
7496 break;
7497 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007498 }
7499 // otherwise use the HAL / AudioStreamIn directly
7500 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007501 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007502 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007503 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007504 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007505 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007506 if (result < 0) {
7507 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007508 } else {
7509 framesRead = bytesRead / mFrameSize;
7510 }
7511 }
7512
Andy Hung446f4df2019-02-21 12:26:41 -08007513 const int64_t lastIoEndNs = systemTime(); // end IO timing
7514
Andy Hung3f0c9022016-01-15 17:49:46 -08007515 // Update server timestamp with server stats
7516 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007517 if (framesRead >= 0) {
7518 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7519 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7520 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007521
7522 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007523 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007524 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007525 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007526 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7527 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7528 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007529 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007530 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7531
7532 mTimestampVerifier.add(position, time, mSampleRate);
7533
7534 // Correct timestamps
7535 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007536 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007537 id(), (long long)time, (long long)position);
7538 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7539 position = correctedTimestamp.mFrames;
7540 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007541 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007542 id(), (long long)time, (long long)position);
7543 }
7544
Andy Hung3f0c9022016-01-15 17:49:46 -08007545 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7546 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7547 // Note: In general record buffers should tend to be empty in
7548 // a properly running pipeline.
7549 //
7550 // Also, it is not advantageous to call get_presentation_position during the read
7551 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007552 } else {
7553 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007554 }
7555 }
Andy Hunge6c37112019-02-26 17:38:10 -08007556
7557 // From the timestamp, input read latency is negative output write latency.
7558 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7559 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7560 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7561 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7562 mLatencyMs.add(latencyMs);
7563 }
7564
Andy Hung3f0c9022016-01-15 17:49:46 -08007565 // Use this to track timestamp information
7566 // ALOGD("%s", mTimestamp.toString().c_str());
7567
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007568 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007569 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007570 // Force input into standby so that it tries to recover at next read attempt
7571 inputStandBy();
7572 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007573 }
7574 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007575 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007576 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007577 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007578 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007579
Andy Hung8946a282018-04-19 20:04:56 -07007580#ifdef TEE_SINK
7581 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7582#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007583 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007584 {
7585 size_t part1 = mRsmpInFramesP2 - rear;
7586 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007587 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007588 (framesRead - part1) * mFrameSize);
7589 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007590 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007591 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007592
7593 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007594
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007595 // loop over each active track
7596 for (size_t i = 0; i < size; i++) {
7597 activeTrack = activeTracks[i];
7598
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007599 // skip fast tracks, as those are handled directly by FastCapture
7600 if (activeTrack->isFastTrack()) {
7601 continue;
7602 }
7603
Andy Hung73c02e42015-03-29 01:13:58 -07007604 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007605 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7606
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007607 enum {
7608 OVERRUN_UNKNOWN,
7609 OVERRUN_TRUE,
7610 OVERRUN_FALSE
7611 } overrun = OVERRUN_UNKNOWN;
7612
7613 // loop over getNextBuffer to handle circular sink
7614 for (;;) {
7615
7616 activeTrack->mSink.frameCount = ~0;
7617 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7618 size_t framesOut = activeTrack->mSink.frameCount;
7619 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7620
Andy Hung73c02e42015-03-29 01:13:58 -07007621 // check available frames and handle overrun conditions
7622 // if the record track isn't draining fast enough.
7623 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007624 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007625 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7626 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007627 overrun = OVERRUN_TRUE;
7628 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007629 if (framesOut == 0 || framesIn == 0) {
7630 break;
7631 }
7632
Andy Hung6770c6f2015-04-07 13:43:36 -07007633 // Don't allow framesOut to be larger than what is possible with resampling
7634 // from framesIn.
7635 // This isn't strictly necessary but helps limit buffer resizing in
7636 // RecordBufferConverter. TODO: remove when no longer needed.
7637 framesOut = min(framesOut,
7638 destinationFramesPossible(
7639 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007640
7641 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007642 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007643 // straight from RecordThread buffer to RecordTrack buffer.
7644 AudioBufferProvider::Buffer buffer;
7645 buffer.frameCount = framesOut;
7646 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7647 if (status == OK && buffer.frameCount != 0) {
7648 ALOGV_IF(buffer.frameCount != framesOut,
7649 "%s() read less than expected (%zu vs %zu)",
7650 __func__, buffer.frameCount, framesOut);
7651 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007652 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007653 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7654 } else {
7655 framesOut = 0;
7656 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7657 __func__, status, buffer.frameCount);
7658 }
7659 } else {
7660 // process frames from the RecordThread buffer provider to the RecordTrack
7661 // buffer
7662 framesOut = activeTrack->mRecordBufferConverter->convert(
7663 activeTrack->mSink.raw,
7664 activeTrack->mResamplerBufferProvider,
7665 framesOut);
7666 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007667
7668 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7669 overrun = OVERRUN_FALSE;
7670 }
7671
7672 if (activeTrack->mFramesToDrop == 0) {
7673 if (framesOut > 0) {
7674 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007675 // Sanitize before releasing if the track has no access to the source data
7676 // An idle UID receives silence from non virtual devices until active
7677 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007678 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007679 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007680 activeTrack->releaseBuffer(&activeTrack->mSink);
7681 }
7682 } else {
7683 // FIXME could do a partial drop of framesOut
7684 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007685 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007686 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007687 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007688 }
7689 } else {
7690 activeTrack->mFramesToDrop += framesOut;
7691 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7692 activeTrack->mSyncStartEvent->isCancelled()) {
7693 ALOGW("Synced record %s, session %d, trigger session %d",
7694 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7695 activeTrack->sessionId(),
7696 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007697 activeTrack->mSyncStartEvent->triggerSession() :
7698 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007699 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007700 }
7701 }
7702 }
7703
7704 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007705 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007706 }
7707 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007708
7709 switch (overrun) {
7710 case OVERRUN_TRUE:
7711 // client isn't retrieving buffers fast enough
7712 if (!activeTrack->setOverflow()) {
7713 nsecs_t now = systemTime();
7714 // FIXME should lastWarning per track?
7715 if ((now - lastWarning) > kWarningThrottleNs) {
7716 ALOGW("RecordThread: buffer overflow");
7717 lastWarning = now;
7718 }
7719 }
7720 break;
7721 case OVERRUN_FALSE:
7722 activeTrack->clearOverflow();
7723 break;
7724 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007725 break;
7726 }
7727
Andy Hung3f0c9022016-01-15 17:49:46 -08007728 // update frame information and push timestamp out
7729 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007730 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007731 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7732 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007733 }
7734
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007735unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007736 // enable changes in effect chain
7737 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007738 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007739 if (audio_has_proportional_frames(mFormat)
7740 && loopCount == lastLoopCountRead + 1) {
7741 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7742 const double jitterMs =
7743 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7744 {framesRead, readPeriodNs},
7745 {0, 0} /* lastTimestamp */, mSampleRate);
7746 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7747
7748 Mutex::Autolock _l(mLock);
7749 mIoJitterMs.add(jitterMs);
7750 mProcessTimeMs.add(processMs);
7751 }
7752 // update timing info.
7753 mLastIoBeginNs = lastIoBeginNs;
7754 mLastIoEndNs = lastIoEndNs;
7755 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007756 }
7757
Glenn Kasten93e471f2013-08-19 08:40:07 -07007758 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007759
7760 {
7761 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007762 for (size_t i = 0; i < mTracks.size(); i++) {
7763 sp<RecordTrack> track = mTracks[i];
7764 track->invalidate();
7765 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007766 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007767 mStartStopCond.broadcast();
7768 }
7769
7770 releaseWakeLock();
7771
7772 ALOGV("RecordThread %p exiting", this);
7773 return false;
7774}
7775
Glenn Kasten93e471f2013-08-19 08:40:07 -07007776void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007777{
7778 if (!mStandby) {
7779 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007780 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007781 mStandby = true;
7782 }
7783}
7784
7785void AudioFlinger::RecordThread::inputStandBy()
7786{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007787 // Idle the fast capture if it's currently running
7788 if (mFastCapture != 0) {
7789 FastCaptureStateQueue *sq = mFastCapture->sq();
7790 FastCaptureState *state = sq->begin();
7791 if (!(state->mCommand & FastCaptureState::IDLE)) {
7792 state->mCommand = FastCaptureState::COLD_IDLE;
7793 state->mColdFutexAddr = &mFastCaptureFutex;
7794 state->mColdGen++;
7795 mFastCaptureFutex = 0;
7796 sq->end();
7797 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7798 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7799#if 0
7800 if (kUseFastCapture == FastCapture_Dynamic) {
7801 // FIXME
7802 }
7803#endif
7804#ifdef AUDIO_WATCHDOG
7805 // FIXME
7806#endif
7807 } else {
7808 sq->end(false /*didModify*/);
7809 }
7810 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007811 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007812 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007813
7814 // If going into standby, flush the pipe source.
7815 if (mPipeSource.get() != nullptr) {
7816 const ssize_t flushed = mPipeSource->flush();
7817 if (flushed > 0) {
7818 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7819 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7820 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7821 }
7822 }
Eric Laurent81784c32012-11-19 14:55:58 -08007823}
7824
Glenn Kasten05997e22014-03-13 15:08:33 -07007825// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007826sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007827 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007828 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007829 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007830 audio_format_t format,
7831 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007832 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007833 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007834 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007835 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00007836 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07007837 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007838 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007839 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02007840 audio_port_handle_t portId,
7841 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08007842{
Glenn Kasten74935e42013-12-19 08:56:45 -08007843 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007844 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007845 sp<RecordTrack> track;
7846 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007847 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007848 audio_input_flags_t requestedFlags = *flags;
7849 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00007850 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
7851 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007852
7853 lStatus = initCheck();
7854 if (lStatus != NO_ERROR) {
7855 ALOGE("createRecordTrack_l() audio driver not initialized");
7856 goto Exit;
7857 }
7858
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007859 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7860 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7861 lStatus = BAD_VALUE;
7862 goto Exit;
7863 }
7864
Eric Laurentec376dc2021-04-08 20:41:22 +02007865 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00007866 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02007867 lStatus = PERMISSION_DENIED;
7868 goto Exit;
7869 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007870 if (maxSharedAudioHistoryMs < 0
7871 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
7872 lStatus = BAD_VALUE;
7873 goto Exit;
7874 }
7875 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08007876 if (*pSampleRate == 0) {
7877 *pSampleRate = mSampleRate;
7878 }
7879 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007880
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007881 // special case for FAST flag considered OK if fast capture is present and access to
7882 // audio history is not required
7883 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07007884 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7885 }
7886
Eric Laurentf14db3c2017-12-08 14:20:36 -08007887 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007888 if ((*flags & inputFlags) != *flags) {
7889 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7890 " input flags (%08x)",
7891 *flags, inputFlags);
7892 *flags = (audio_input_flags_t)(*flags & inputFlags);
7893 }
Eric Laurent81784c32012-11-19 14:55:58 -08007894
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007895 // client expresses a preference for FAST and no access to audio history,
7896 // but we get the final say
7897 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007898 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007899 // we formerly checked for a callback handler (non-0 tid),
7900 // but that is no longer required for TRANSFER_OBTAIN mode
7901 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007902 // Frame count is not specified (0), or is less than or equal the pipe depth.
7903 // It is OK to provide a higher capacity than requested.
7904 // We will force it to mPipeFramesP2 below.
7905 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007906 // PCM data
7907 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007908 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007909 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007910 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007911 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007912 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007913 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007914 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007915 hasFastCapture() &&
7916 // there are sufficient fast track slots available
7917 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007918 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007919 // check compatibility with audio effects.
7920 Mutex::Autolock _l(mLock);
7921 // Do not accept FAST flag if the session has software effects
7922 sp<EffectChain> chain = getEffectChain_l(sessionId);
7923 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007924 audio_input_flags_t old = *flags;
7925 chain->checkInputFlagCompatibility(flags);
7926 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007927 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7928 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007929 }
7930 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007931 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007932 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7933 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007934 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007935 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7936 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007937 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007938 this, frameCount, mFrameCount, mPipeFramesP2,
7939 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007940 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007941 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007942 }
7943 }
7944
Eric Laurentf14db3c2017-12-08 14:20:36 -08007945 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7946 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7947 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7948 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7949 lStatus = BAD_TYPE;
7950 goto Exit;
7951 }
7952
Glenn Kasten74105912014-07-03 12:28:53 -07007953 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007954 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007955 // fast track: frame count is exactly the pipe depth
7956 frameCount = mPipeFramesP2;
7957 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007958 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007959 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007960 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7961 // or 20 ms if there is a fast capture
7962 // TODO This could be a roundupRatio inline, and const
7963 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7964 * sampleRate + mSampleRate - 1) / mSampleRate;
7965 // minimum number of notification periods is at least kMinNotifications,
7966 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7967 static const size_t kMinNotifications = 3;
7968 static const uint32_t kMinMs = 30;
7969 // TODO This could be a roundupRatio inline
7970 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7971 // TODO This could be a roundupRatio inline
7972 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7973 maxNotificationFrames;
7974 const size_t minFrameCount = maxNotificationFrames *
7975 max(kMinNotifications, minNotificationsByMs);
7976 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007977 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7978 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007979 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007980 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007981 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007982 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007983
7984 { // scope for mLock
7985 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02007986 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02007987 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00007988 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02007989 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00007990 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02007991 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02007992 }
Eric Laurent81784c32012-11-19 14:55:58 -08007993
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007994 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007995 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007996 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00007997 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
7998 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08007999
Glenn Kasten03003332013-08-06 15:40:54 -07008000 lStatus = track->initCheck();
8001 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008002 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008003 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008004 goto Exit;
8005 }
8006 mTracks.add(track);
8007
Eric Laurent05067782016-06-01 18:27:28 -07008008 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008009 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8010 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8011 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008012 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008013 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008014
8015 if (maxSharedAudioHistoryMs != 0) {
8016 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8017 }
Eric Laurent81784c32012-11-19 14:55:58 -08008018 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008019
Eric Laurent81784c32012-11-19 14:55:58 -08008020 lStatus = NO_ERROR;
8021
8022Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008023 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008024 return track;
8025}
8026
8027status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8028 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008029 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008030{
8031 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8032 sp<ThreadBase> strongMe = this;
8033 status_t status = NO_ERROR;
8034
8035 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008036 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008037 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008038 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008039 triggerSession,
8040 recordTrack->sessionId(),
8041 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008042 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008043 // Sync event can be cancelled by the trigger session if the track is not in a
8044 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008045 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008046 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008047 } else {
8048 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008049 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008050 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008051 }
8052 }
8053
8054 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008055 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008056 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008057 if (recordTrack->isInvalid()) {
8058 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008059 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8060 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008061 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008062 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8063 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008064 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8065 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008066 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008067 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008068 } else {
8069 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008070 }
8071 return status;
8072 }
8073
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008074 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8075 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8076 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008077 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008078 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008079 status_t status = NO_ERROR;
8080 if (recordTrack->isExternalTrack()) {
8081 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008082 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008083 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008084 if (recordTrack->isInvalid()) {
8085 recordTrack->clearSyncStartEvent();
8086 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8087 recordTrack->mState = TrackBase::STARTING_2;
8088 // STARTING_2 forces destroy to call stopInput.
8089 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008090 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8091 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008092 }
8093 if (recordTrack->mState != TrackBase::STARTING_1) {
8094 ALOGW("%s(%d): unsynchronized mState:%d change",
8095 __func__, recordTrack->id(), recordTrack->mState);
8096 // Someone else has changed state, let them take over,
8097 // leave mState in the new state.
8098 recordTrack->clearSyncStartEvent();
8099 return INVALID_OPERATION;
8100 }
8101 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008102 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008103 ALOGW("%s(%d): startInput failed, status %d",
8104 __func__, recordTrack->id(), status);
8105 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8106 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008107 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008108 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008109 return status;
8110 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008111 sendIoConfigEvent_l(
8112 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008113 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008114
8115 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8116
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008117 // Catch up with current buffer indices if thread is already running.
8118 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8119 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8120 // see previously buffered data before it called start(), but with greater risk of overrun.
8121
Andy Hung73c02e42015-03-29 01:13:58 -07008122 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008123 if (!recordTrack->isDirect()) {
8124 // clear any converter state as new data will be discontinuous
8125 recordTrack->mRecordBufferConverter->reset();
8126 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008127 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008128 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008129 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008130 return status;
8131 }
Eric Laurent81784c32012-11-19 14:55:58 -08008132}
8133
Eric Laurent81784c32012-11-19 14:55:58 -08008134void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8135{
8136 sp<SyncEvent> strongEvent = event.promote();
8137
8138 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008139 sp<RefBase> ptr = strongEvent->cookie().promote();
8140 if (ptr != 0) {
8141 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8142 recordTrack->handleSyncStartEvent(strongEvent);
8143 }
Eric Laurent81784c32012-11-19 14:55:58 -08008144 }
8145}
8146
Glenn Kastena8356f62013-07-25 14:37:52 -07008147bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008148 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008149 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008150 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008151 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008152 return false;
8153 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008154 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008155 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008156
Andy Hungabfab202019-03-07 19:45:54 -08008157 // NOTE: Waiting here is important to keep stop synchronous.
8158 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008159 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8160 mWaitWorkCV.broadcast(); // signal thread to stop
8161 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008162 }
Andy Hungce685402018-10-05 17:23:27 -07008163
8164 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008165 ALOGV("Record stopped OK");
8166 return true;
8167 }
Andy Hungce685402018-10-05 17:23:27 -07008168
8169 // don't handle anything - we've been invalidated or restarted and in a different state
8170 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8171 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008172 return false;
8173}
8174
Glenn Kasten0f11b512014-01-31 16:18:54 -08008175bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008176{
8177 return false;
8178}
8179
Glenn Kasten0f11b512014-01-31 16:18:54 -08008180status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008181{
8182#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8183 if (!isValidSyncEvent(event)) {
8184 return BAD_VALUE;
8185 }
8186
Glenn Kastend848eb42016-03-08 13:42:11 -08008187 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008188 status_t ret = NAME_NOT_FOUND;
8189
8190 Mutex::Autolock _l(mLock);
8191
8192 for (size_t i = 0; i < mTracks.size(); i++) {
8193 sp<RecordTrack> track = mTracks[i];
8194 if (eventSession == track->sessionId()) {
8195 (void) track->setSyncEvent(event);
8196 ret = NO_ERROR;
8197 }
8198 }
8199 return ret;
8200#else
8201 return BAD_VALUE;
8202#endif
8203}
8204
jiabin653cc0a2018-01-17 17:54:10 -08008205status_t AudioFlinger::RecordThread::getActiveMicrophones(
8206 std::vector<media::MicrophoneInfo>* activeMicrophones)
8207{
8208 ALOGV("RecordThread::getActiveMicrophones");
8209 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008210 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008211 return NO_INIT;
8212 }
jiabin9ff780e2018-03-19 18:19:52 -07008213 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8214 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008215}
8216
Paul McLean12340082019-03-19 09:35:05 -06008217status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8218 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008219{
Paul McLean12340082019-03-19 09:35:05 -06008220 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008221 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008222 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008223 return NO_INIT;
8224 }
Paul McLean12340082019-03-19 09:35:05 -06008225 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008226}
8227
Paul McLean12340082019-03-19 09:35:05 -06008228status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008229{
Paul McLean12340082019-03-19 09:35:05 -06008230 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008231 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008232 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008233 return NO_INIT;
8234 }
Paul McLean12340082019-03-19 09:35:05 -06008235 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008236}
8237
Eric Laurentec376dc2021-04-08 20:41:22 +02008238status_t AudioFlinger::RecordThread::shareAudioHistory(
8239 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8240 int64_t sharedAudioStartMs) {
8241 AutoMutex _l(mLock);
8242 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8243}
8244
8245status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8246 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8247 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008248
Eric Laurentec376dc2021-04-08 20:41:22 +02008249 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8250 return BAD_VALUE;
8251 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008252
8253 if (sharedAudioStartMs < 0
8254 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008255 return BAD_VALUE;
8256 }
8257
Eric Laurent2407ce32021-04-26 14:56:03 +02008258 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8259 // As we cannot detect more than one wraparound, only accept values up current write position
8260 // after one wraparound
8261 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8262 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008263 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008264 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8265 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008266 // Bring the start frame position within the input buffer to match the documented
8267 // "best effort" behavior of the API.
8268 if (sharedOffset < 0) {
8269 sharedAudioStartFrames = mRsmpInRear;
8270 } else if (sharedOffset > mRsmpInFrames) {
8271 sharedAudioStartFrames =
8272 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008273 }
8274
Eric Laurentec376dc2021-04-08 20:41:22 +02008275 mSharedAudioPackageName = sharedAudioPackageName;
8276 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008277 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008278 } else {
8279 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008280 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008281 }
8282 return NO_ERROR;
8283}
8284
Eric Laurent92d0a322021-07-16 15:32:33 +02008285void AudioFlinger::RecordThread::resetAudioHistory_l() {
8286 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8287 mSharedAudioStartFrames = -1;
8288 mSharedAudioPackageName = "";
8289}
8290
Kevin Rocard069c2712018-03-29 19:09:14 -07008291void AudioFlinger::RecordThread::updateMetadata_l()
8292{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008293 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8294 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008295 }
8296 StreamInHalInterface::SinkMetadata metadata;
8297 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008298 // Do not forward PatchRecord metadata to audio HAL
8299 if (track->isPatchTrack()) {
8300 continue;
8301 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008302 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008303 record_track_metadata_v7_t trackMetadata;
8304 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008305 .source = track->attributes().source,
8306 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008307 };
8308 trackMetadata.channel_mask = track->channelMask(),
8309 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8310
8311 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008312 }
8313 mInput->stream->updateSinkMetadata(metadata);
8314}
8315
Eric Laurent81784c32012-11-19 14:55:58 -08008316// destroyTrack_l() must be called with ThreadBase::mLock held
8317void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8318{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008319 track->terminate();
8320 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008321
Eric Laurent81784c32012-11-19 14:55:58 -08008322 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008323 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008324 removeTrack_l(track);
8325 }
8326}
8327
8328void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8329{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008330 String8 result;
8331 track->appendDump(result, false /* active */);
8332 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8333
Eric Laurent81784c32012-11-19 14:55:58 -08008334 mTracks.remove(track);
8335 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008336 if (track->isFastTrack()) {
8337 ALOG_ASSERT(!mFastTrackAvail);
8338 mFastTrackAvail = true;
8339 }
Eric Laurent81784c32012-11-19 14:55:58 -08008340}
8341
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008342void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008343{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008344 AudioStreamIn *input = mInput;
8345 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8346 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008347 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008348 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008349 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008350 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008351 }
Andy Hungbfa64962017-06-12 14:43:19 -07008352
8353 if (input != nullptr) {
8354 dprintf(fd, " Hal stream dump:\n");
8355 (void)input->stream->dump(fd);
8356 }
8357
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008358 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008359 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008360
Glenn Kasten2f90c512015-12-02 11:40:09 -08008361 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8362 // while we are dumping it. It may be inconsistent, but it won't mutate!
8363 // This is a large object so we place it on the heap.
8364 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008365 const std::unique_ptr<FastCaptureDumpState> copy =
8366 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008367 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008368}
8369
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008370void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008371{
Eric Laurent81784c32012-11-19 14:55:58 -08008372 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008373 size_t numtracks = mTracks.size();
8374 size_t numactive = mActiveTracks.size();
8375 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008376 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008377 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008378 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008379 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008380 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008381 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008382 for (size_t i = 0; i < numtracks ; ++i) {
8383 sp<RecordTrack> track = mTracks[i];
8384 if (track != 0) {
8385 bool active = mActiveTracks.indexOf(track) >= 0;
8386 if (active) {
8387 numactiveseen++;
8388 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008389 result.append(prefix);
8390 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008391 }
Eric Laurent81784c32012-11-19 14:55:58 -08008392 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008393 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008394 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008395 }
8396
Marco Nelissenb2208842014-02-07 14:00:50 -08008397 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008398 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008399 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008400 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008401 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008402 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008403 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008404 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008405 result.append(prefix);
8406 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008407 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008408 }
Eric Laurent81784c32012-11-19 14:55:58 -08008409
8410 }
8411 write(fd, result.string(), result.size());
8412}
8413
Eric Laurent5ada82e2019-08-29 17:53:54 -07008414void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008415{
8416 Mutex::Autolock _l(mLock);
8417 for (size_t i = 0; i < mTracks.size() ; i++) {
8418 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008419 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008420 track->setSilenced(silenced);
8421 }
8422 }
8423}
Andy Hung73c02e42015-03-29 01:13:58 -07008424
8425void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8426{
8427 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8428 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008429 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008430 const int32_t rear = recordThread->mRsmpInRear;
8431 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008432 if (mRecordTrack->startFrames() >= 0) {
8433 int32_t startFrames = mRecordTrack->startFrames();
8434 // Accept a recent wraparound of mRsmpInRear
8435 if (startFrames <= rear) {
8436 deltaFrames = rear - startFrames;
8437 } else {
8438 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008439 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008440 // start frame cannot be further in the past than start of resampling buffer
8441 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8442 deltaFrames = recordThread->mRsmpInFrames;
8443 }
8444 }
8445 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008446}
8447
8448void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8449 size_t *framesAvailable, bool *hasOverrun)
8450{
8451 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8452 RecordThread *recordThread = (RecordThread *) threadBase.get();
8453 const int32_t rear = recordThread->mRsmpInRear;
8454 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008455 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008456
8457 size_t framesIn;
8458 bool overrun = false;
8459 if (filled < 0) {
8460 // should not happen, but treat like a massive overrun and re-sync
8461 framesIn = 0;
8462 mRsmpInFront = rear;
8463 overrun = true;
8464 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8465 framesIn = (size_t) filled;
8466 } else {
8467 // client is not keeping up with server, but give it latest data
8468 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008469 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8470 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008471 overrun = true;
8472 }
8473 if (framesAvailable != NULL) {
8474 *framesAvailable = framesIn;
8475 }
8476 if (hasOverrun != NULL) {
8477 *hasOverrun = overrun;
8478 }
8479}
8480
Eric Laurent81784c32012-11-19 14:55:58 -08008481// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008482status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008483 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008484{
Andy Hung73c02e42015-03-29 01:13:58 -07008485 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008486 if (threadBase == 0) {
8487 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008488 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008489 return NOT_ENOUGH_DATA;
8490 }
8491 RecordThread *recordThread = (RecordThread *) threadBase.get();
8492 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008493 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008494 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008495 // FIXME should not be P2 (don't want to increase latency)
8496 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008497 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008498 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008499
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008500 front &= recordThread->mRsmpInFramesP2 - 1;
8501 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008502 if (part1 > (size_t) filled) {
8503 part1 = filled;
8504 }
8505 size_t ask = buffer->frameCount;
8506 ALOG_ASSERT(ask > 0);
8507 if (part1 > ask) {
8508 part1 = ask;
8509 }
8510 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008511 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008512 buffer->raw = NULL;
8513 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008514 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008515 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008516 }
8517
Andy Hung57446612015-04-19 23:56:46 -07008518 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008519 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008520 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008521 return NO_ERROR;
8522}
8523
8524// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008525void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8526 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008527{
Hongwei Wang95e37682019-04-12 11:13:36 -07008528 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008529 if (stepCount == 0) {
8530 return;
8531 }
Andy Hung73c02e42015-03-29 01:13:58 -07008532 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8533 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008534 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008535 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008536 buffer->frameCount = 0;
8537}
8538
Eric Laurentd8365c52017-07-16 15:27:05 -07008539void AudioFlinger::RecordThread::checkBtNrec()
8540{
8541 Mutex::Autolock _l(mLock);
8542 checkBtNrec_l();
8543}
8544
8545void AudioFlinger::RecordThread::checkBtNrec_l()
8546{
8547 // disable AEC and NS if the device is a BT SCO headset supporting those
8548 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008549 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008550 mAudioFlinger->btNrecIsOff();
8551 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8552 for (size_t i = 0; i < mEffectChains.size(); i++) {
8553 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8554 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8555 }
8556 }
8557}
8558
Andy Hung97a893e2015-03-29 01:03:07 -07008559
Eric Laurent10351942014-05-08 18:49:52 -07008560bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8561 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008562{
8563 bool reconfig = false;
8564
Eric Laurent10351942014-05-08 18:49:52 -07008565 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008566
Eric Laurent10351942014-05-08 18:49:52 -07008567 audio_format_t reqFormat = mFormat;
8568 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008569 // 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 -07008570 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8571
8572 AudioParameter param = AudioParameter(keyValuePair);
8573 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008574
8575 // scope for AutoPark extends to end of method
8576 AutoPark<FastCapture> park(mFastCapture);
8577
Eric Laurent10351942014-05-08 18:49:52 -07008578 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8579 // channel count change can be requested. Do we mandate the first client defines the
8580 // HAL sampling rate and channel count or do we allow changes on the fly?
8581 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8582 samplingRate = value;
8583 reconfig = true;
8584 }
8585 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008586 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008587 status = BAD_VALUE;
8588 } else {
8589 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008590 reconfig = true;
8591 }
Eric Laurent10351942014-05-08 18:49:52 -07008592 }
8593 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8594 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008595 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07008596 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07008597 status = BAD_VALUE;
8598 } else {
8599 channelMask = mask;
8600 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008601 }
Eric Laurent10351942014-05-08 18:49:52 -07008602 }
8603 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8604 // do not accept frame count changes if tracks are open as the track buffer
8605 // size depends on frame count and correct behavior would not be guaranteed
8606 // if frame count is changed after track creation
8607 if (mActiveTracks.size() > 0) {
8608 status = INVALID_OPERATION;
8609 } else {
8610 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008611 }
Eric Laurent10351942014-05-08 18:49:52 -07008612 }
8613 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008614 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008615 }
8616 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8617 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008618 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008619 }
Glenn Kastene198c362013-08-13 09:13:36 -07008620
Eric Laurent10351942014-05-08 18:49:52 -07008621 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008622 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008623 if (status == INVALID_OPERATION) {
8624 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008625 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008626 }
8627 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008628 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008629 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8630 if (mInput->stream->getAudioProperties(&config) == OK &&
8631 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8632 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07008633 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008634 status = NO_ERROR;
8635 }
Eric Laurent81784c32012-11-19 14:55:58 -08008636 }
Eric Laurent10351942014-05-08 18:49:52 -07008637 if (status == NO_ERROR) {
8638 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008639 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008640 }
8641 }
Eric Laurent81784c32012-11-19 14:55:58 -08008642 }
Eric Laurent10351942014-05-08 18:49:52 -07008643
Eric Laurent81784c32012-11-19 14:55:58 -08008644 return reconfig;
8645}
8646
8647String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8648{
Eric Laurent81784c32012-11-19 14:55:58 -08008649 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008650 if (initCheck() == NO_ERROR) {
8651 String8 out_s8;
8652 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8653 return out_s8;
8654 }
Eric Laurent81784c32012-11-19 14:55:58 -08008655 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008656 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008657}
8658
Eric Laurent09f1ed22019-04-24 17:45:17 -07008659void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8660 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008661 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8662
8663 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008664
8665 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008666 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008667 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008668 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008669 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008670 desc->mChannelMask = mChannelMask;
8671 desc->mSamplingRate = mSampleRate;
8672 desc->mFormat = mFormat;
8673 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008674 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008675 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008676 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008677 case AUDIO_CLIENT_STARTED:
8678 desc->mPatch = mPatch;
8679 desc->mPortId = portId;
8680 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008681 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008682 default:
8683 break;
8684 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008685 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008686}
8687
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008688void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008689{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008690 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8691 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008692 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008693 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8694 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07008695 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
8696 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008697 } else {
Andy Hung936845a2021-06-08 00:09:06 -07008698 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008699 ALOGI("HAL format %#x is not linear pcm", mFormat);
8700 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008701 result = mInput->stream->getFrameSize(&mFrameSize);
8702 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008703 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8704 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008705 result = mInput->stream->getBufferSize(&mBufferSize);
8706 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008707 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008708 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8709 "mBufferSize=%zu, mFrameCount=%zu",
8710 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008711
Eric Laurentec376dc2021-04-08 20:41:22 +02008712 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8713 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008714 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08008715
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008716 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8717 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008718
8719 audio_input_flags_t flags = mInput->flags;
8720 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8721 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8722 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8723 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8724 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8725 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8726 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8727 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8728 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008729}
8730
Glenn Kasten5f972c02014-01-13 09:59:31 -08008731uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008732{
8733 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008734 uint32_t result;
8735 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8736 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008737 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008738 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008739}
8740
Glenn Kastend848eb42016-03-08 13:42:11 -08008741KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008742{
Glenn Kastend848eb42016-03-08 13:42:11 -08008743 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008744 Mutex::Autolock _l(mLock);
8745 for (size_t j = 0; j < mTracks.size(); ++j) {
8746 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008747 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008748 if (ids.indexOfKey(sessionId) < 0) {
8749 ids.add(sessionId, true);
8750 }
8751 }
8752 return ids;
8753}
8754
8755AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8756{
8757 Mutex::Autolock _l(mLock);
8758 AudioStreamIn *input = mInput;
8759 mInput = NULL;
8760 return input;
8761}
8762
8763// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008764sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008765{
8766 if (mInput == NULL) {
8767 return NULL;
8768 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008769 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008770}
8771
8772status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8773{
Eric Laurent81784c32012-11-19 14:55:58 -08008774 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008775 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008776 chain->setInBuffer(NULL);
8777 chain->setOutBuffer(NULL);
8778
8779 checkSuspendOnAddEffectChain_l(chain);
8780
Eric Laurent1b928682014-10-02 19:41:47 -07008781 // make sure enabled pre processing effects state is communicated to the HAL as we
8782 // just moved them to a new input stream.
8783 chain->syncHalEffectsState();
8784
Eric Laurent81784c32012-11-19 14:55:58 -08008785 mEffectChains.add(chain);
8786
8787 return NO_ERROR;
8788}
8789
8790size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8791{
8792 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008793
8794 for (size_t i = 0; i < mEffectChains.size(); i++) {
8795 if (chain == mEffectChains[i]) {
8796 mEffectChains.removeAt(i);
8797 break;
8798 }
Eric Laurent81784c32012-11-19 14:55:58 -08008799 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008800 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008801}
8802
Eric Laurent1c333e22014-05-20 10:48:17 -07008803status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8804 audio_patch_handle_t *handle)
8805{
8806 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008807
8808 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008809 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008810 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008811 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008812 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008813 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008814 }
8815
Eric Laurentd8365c52017-07-16 15:27:05 -07008816 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008817
8818 // store new source and send to effects
8819 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8820 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008821 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008822 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008823 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008824 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008825
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008826 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008827 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8828 status = hwDevice->createAudioPatch(patch->num_sources,
8829 patch->sources,
8830 patch->num_sinks,
8831 patch->sinks,
8832 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008833 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008834 char *address;
8835 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8836 address = audio_device_address_to_parameter(
8837 patch->sources[0].ext.device.type,
8838 patch->sources[0].ext.device.address);
8839 } else {
8840 address = (char *)calloc(1, 1);
8841 }
8842 AudioParameter param = AudioParameter(String8(address));
8843 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008844 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008845 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008846 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008847 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008848 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008849 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008850 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008851
jiabinc52b1ff2019-10-31 17:20:42 -07008852 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008853 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008854 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008855 }
Eric Laurent296fb132015-05-01 11:38:42 -07008856
Andy Hungc2b11cb2020-04-22 09:04:01 -07008857 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008858 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008859 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008860 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008861 // also dispatch to active AudioRecords
8862 for (const auto &track : mActiveTracks) {
8863 track->logEndInterval();
8864 track->logBeginInterval(pathSourcesAsString);
8865 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008866 return status;
8867}
8868
8869status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8870{
8871 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008872
jiabinc52b1ff2019-10-31 17:20:42 -07008873 mPatch = audio_patch{};
8874 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008875
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008876 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008877 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8878 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008879 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008880 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008881 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008882 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008883 }
8884 return status;
8885}
8886
jiabinc52b1ff2019-10-31 17:20:42 -07008887void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8888{
wendy lin56aa82b2020-12-02 15:19:55 +08008889 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07008890 mOutDevices = outDevices;
8891 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8892 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008893 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008894 }
8895}
8896
Eric Laurentec376dc2021-04-08 20:41:22 +02008897int32_t AudioFlinger::RecordThread::getOldestFront_l()
8898{
8899 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008900 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02008901 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008902 int32_t oldestFront = mRsmpInRear;
8903 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008904 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008905 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8906 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02008907 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02008908 if (filled > maxFilled) {
8909 oldestFront = front;
8910 maxFilled = filled;
8911 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008912 }
Eric Laurent92d0a322021-07-16 15:32:33 +02008913 if (maxFilled > mRsmpInFrames) {
8914 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
8915 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008916 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02008917}
8918
8919void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
8920{
8921 if (offset == 0) {
8922 return;
8923 }
8924 for (size_t i = 0; i < mTracks.size(); i++) {
8925 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8926 front = audio_utils::safe_sub_overflow(front, offset);
8927 mTracks[i]->mResamplerBufferProvider->setFront(front);
8928 }
8929}
8930
8931void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
8932{
8933 // This is the formula for calculating the temporary buffer size.
8934 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
8935 // 1 full output buffer, regardless of the alignment of the available input.
8936 // The value is somewhat arbitrary, and could probably be even larger.
8937 // A larger value should allow more old data to be read after a track calls start(),
8938 // without increasing latency.
8939 //
8940 // Note this is independent of the maximum downsampling ratio permitted for capture.
8941 size_t minRsmpInFrames = mFrameCount * 7;
8942
8943 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
8944 // capture history available to another client using the same session ID:
8945 // dimension the resampler input buffer accordingly.
8946
8947 // Get oldest client read position: getOldestFront_l() must be called before altering
8948 // mRsmpInRear, or mRsmpInFrames
8949 int32_t previousFront = getOldestFront_l();
8950 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
8951 int32_t previousRear = mRsmpInRear;
8952 mRsmpInRear = 0;
8953
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008954 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
8955 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
8956 "resizeInputBuffer_l() called with invalid max shared history %d",
8957 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02008958 if (maxSharedAudioHistoryMs != 0) {
8959 // resizeInputBuffer_l should never be called with a non zero shared history if the
8960 // buffer was not already allocated
8961 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
8962 "resizeInputBuffer_l() called with shared history and unallocated buffer");
8963 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
8964 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02008965 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008966 return;
8967 }
8968 mRsmpInFrames = rsmpInFrames;
8969 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008970 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02008971 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
8972 // initialized
8973 if (mRsmpInFrames < minRsmpInFrames) {
8974 mRsmpInFrames = minRsmpInFrames;
8975 }
8976 mRsmpInFramesP2 = roundup(mRsmpInFrames);
8977
8978 // TODO optimize audio capture buffer sizes ...
8979 // Here we calculate the size of the sliding buffer used as a source
8980 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8981 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8982 // be better to have it derived from the pipe depth in the long term.
8983 // The current value is higher than necessary. However it should not add to latency.
8984
8985 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
8986 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8987
8988 void *rsmpInBuffer;
8989 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
8990 // if posix_memalign fails, will segv here.
8991 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
8992
8993 // Copy audio history if any from old buffer before freeing it
8994 if (previousRear != 0) {
8995 ALOG_ASSERT(mRsmpInBuffer != nullptr,
8996 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
8997
8998 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
8999 previousFront &= previousRsmpInFramesP2 - 1;
9000 size_t part1 = previousRsmpInFramesP2 - previousFront;
9001 if (part1 > (size_t) unread) {
9002 part1 = unread;
9003 }
9004 if (part1 != 0) {
9005 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9006 part1 * mFrameSize);
9007 mRsmpInRear = part1;
9008 part1 = unread - part1;
9009 if (part1 != 0) {
9010 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9011 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9012 mRsmpInRear += part1;
9013 }
9014 }
9015 // Update front for all clients according to new rear
9016 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9017 } else {
9018 mRsmpInRear = 0;
9019 }
9020 free(mRsmpInBuffer);
9021 mRsmpInBuffer = rsmpInBuffer;
9022}
9023
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009024void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009025{
9026 Mutex::Autolock _l(mLock);
9027 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009028 if (record->getSource()) {
9029 mSource = record->getSource();
9030 }
Eric Laurent83b88082014-06-20 18:31:16 -07009031}
9032
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009033void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009034{
9035 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009036 if (mSource == record->getSource()) {
9037 mSource = mInput;
9038 }
Eric Laurent83b88082014-06-20 18:31:16 -07009039 destroyTrack_l(record);
9040}
9041
Mikhail Naganovdc769682018-05-04 15:34:08 -07009042void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009043{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009044 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009045 config->role = AUDIO_PORT_ROLE_SINK;
9046 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9047 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009048 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9049 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9050 config->flags.input = mInput->flags;
9051 }
Eric Laurent83b88082014-06-20 18:31:16 -07009052}
Eric Laurent1c333e22014-05-20 10:48:17 -07009053
Eric Laurent6acd1d42017-01-04 14:23:29 -08009054// ----------------------------------------------------------------------------
9055// Mmap
9056// ----------------------------------------------------------------------------
9057
9058AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9059 : mThread(thread)
9060{
Phil Burk9fabbf82017-08-03 12:02:00 -07009061 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009062}
9063
9064AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9065{
Phil Burk9fabbf82017-08-03 12:02:00 -07009066 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009067}
9068
9069status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9070 struct audio_mmap_buffer_info *info)
9071{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009072 return mThread->createMmapBuffer(minSizeFrames, info);
9073}
9074
9075status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9076{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009077 return mThread->getMmapPosition(position);
9078}
9079
jiabinb7d8c5a2020-08-26 17:24:52 -07009080status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9081 int64_t *timeNanos) {
9082 return mThread->getExternalPosition(position, timeNanos);
9083}
9084
Eric Laurenta54f1282017-07-01 19:39:32 -07009085status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009086 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009087
9088{
jiabind1f1cb62020-03-24 11:57:57 -07009089 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009090}
9091
9092status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9093{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009094 return mThread->stop(handle);
9095}
9096
Eric Laurent18b57012017-02-13 16:23:52 -08009097status_t AudioFlinger::MmapThreadHandle::standby()
9098{
Eric Laurent18b57012017-02-13 16:23:52 -08009099 return mThread->standby();
9100}
9101
Eric Laurent6acd1d42017-01-04 14:23:29 -08009102
9103AudioFlinger::MmapThread::MmapThread(
9104 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009105 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009106 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009107 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009108 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009109 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009110 mActiveTracks(&this->mLocalLog),
9111 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9112 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009113{
Eric Laurent18b57012017-02-13 16:23:52 -08009114 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009115 readHalParameters_l();
9116}
9117
9118AudioFlinger::MmapThread::~MmapThread()
9119{
9120}
9121
9122void AudioFlinger::MmapThread::onFirstRef()
9123{
9124 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9125}
9126
9127void AudioFlinger::MmapThread::disconnect()
9128{
Eric Laurent331679c2018-04-16 17:03:16 -07009129 ActiveTracks<MmapTrack> activeTracks;
9130 {
9131 Mutex::Autolock _l(mLock);
9132 for (const sp<MmapTrack> &t : mActiveTracks) {
9133 activeTracks.add(t);
9134 }
9135 }
9136 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009137 stop(t->portId());
9138 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009139 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009140 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009141 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009142 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009143 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009144 }
9145}
9146
9147
9148void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9149 audio_stream_type_t streamType __unused,
9150 audio_session_t sessionId,
9151 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009152 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009153 audio_port_handle_t portId)
9154{
9155 mAttr = *attr;
9156 mSessionId = sessionId;
9157 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009158 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009159 mPortId = portId;
9160}
9161
9162status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9163 struct audio_mmap_buffer_info *info)
9164{
9165 if (mHalStream == 0) {
9166 return NO_INIT;
9167 }
Eric Laurent18b57012017-02-13 16:23:52 -08009168 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009169 return mHalStream->createMmapBuffer(minSizeFrames, info);
9170}
9171
9172status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9173{
9174 if (mHalStream == 0) {
9175 return NO_INIT;
9176 }
9177 return mHalStream->getMmapPosition(position);
9178}
9179
Eric Laurent331679c2018-04-16 17:03:16 -07009180status_t AudioFlinger::MmapThread::exitStandby()
9181{
9182 status_t ret = mHalStream->start();
9183 if (ret != NO_ERROR) {
9184 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9185 return ret;
9186 }
Andy Hungcf10d742020-04-28 15:38:24 -07009187 if (mStandby) {
9188 mThreadMetrics.logBeginInterval();
9189 mStandby = false;
9190 }
Eric Laurent331679c2018-04-16 17:03:16 -07009191 return NO_ERROR;
9192}
9193
Eric Laurenta54f1282017-07-01 19:39:32 -07009194status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009195 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009196 audio_port_handle_t *handle)
9197{
Eric Laurenta54f1282017-07-01 19:39:32 -07009198 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009199 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009200 if (mHalStream == 0) {
9201 return NO_INIT;
9202 }
9203
9204 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009205
Eric Laurenta54f1282017-07-01 19:39:32 -07009206 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009207 // For the first track, reuse portId and session allocated when the stream was opened.
9208 ret = exitStandby();
9209 if (ret == NO_ERROR) {
9210 acquireWakeLock();
9211 }
9212 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009213 }
9214
9215 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9216
9217 audio_io_handle_t io = mId;
9218 if (isOutput()) {
9219 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9220 config.sample_rate = mSampleRate;
9221 config.channel_mask = mChannelMask;
9222 config.format = mFormat;
9223 audio_stream_type_t stream = streamType();
9224 audio_output_flags_t flags =
9225 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009226 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009227 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009228 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9229 mSessionId,
9230 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009231 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009232 &config,
9233 flags,
9234 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009235 &portId,
9236 &secondaryOutputs);
9237 ALOGD_IF(!secondaryOutputs.empty(),
9238 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009239 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009240 audio_config_base_t config;
9241 config.sample_rate = mSampleRate;
9242 config.channel_mask = mChannelMask;
9243 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009244 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009245 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009246 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009247 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009248 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009249 &config,
9250 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9251 &deviceId,
9252 &portId);
9253 }
9254 // APM should not chose a different input or output stream for the same set of attributes
9255 // and audo configuration
9256 if (ret != NO_ERROR || io != mId) {
9257 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9258 __FUNCTION__, ret, io, mId);
9259 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009260 }
9261
9262 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009263 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009264 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009265 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009266 }
9267
Eric Laurent331679c2018-04-16 17:03:16 -07009268 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009269 // abort if start is rejected by audio policy manager
9270 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009271 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009272 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009273 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009274 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009275 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009276 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009277 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009278 }
Eric Laurent331679c2018-04-16 17:03:16 -07009279 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009280 } else {
9281 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009282 }
9283 return PERMISSION_DENIED;
9284 }
9285
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009286 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009287 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009288 mChannelMask, mSessionId, isOutput(),
9289 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009290 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009291
Eric Laurent4eb58f12018-12-07 16:41:02 -08009292 if (isOutput()) {
9293 // force volume update when a new track is added
9294 mHalVolFloat = -1.0f;
9295 } else if (!track->isSilenced_l()) {
9296 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009297 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009298 t->invalidate();
9299 }
9300 }
9301
9302
Eric Laurent6acd1d42017-01-04 14:23:29 -08009303 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009304 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009305 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009306 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009307 chain->incTrackCnt();
9308 chain->incActiveTrackCnt();
9309 }
9310
Andy Hungc2b11cb2020-04-22 09:04:01 -07009311 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009312 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009313 broadcast_l();
9314
Eric Laurenta54f1282017-07-01 19:39:32 -07009315 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009316
9317 return NO_ERROR;
9318}
9319
9320status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9321{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009322 ALOGV("%s handle %d", __FUNCTION__, handle);
9323
9324 if (mHalStream == 0) {
9325 return NO_INIT;
9326 }
9327
Eric Laurenta54f1282017-07-01 19:39:32 -07009328 if (handle == mPortId) {
9329 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009330 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009331 return NO_ERROR;
9332 }
9333
Eric Laurent331679c2018-04-16 17:03:16 -07009334 Mutex::Autolock _l(mLock);
9335
Eric Laurent6acd1d42017-01-04 14:23:29 -08009336 sp<MmapTrack> track;
9337 for (const sp<MmapTrack> &t : mActiveTracks) {
9338 if (handle == t->portId()) {
9339 track = t;
9340 break;
9341 }
9342 }
9343 if (track == 0) {
9344 return BAD_VALUE;
9345 }
9346
9347 mActiveTracks.remove(track);
9348
Eric Laurent331679c2018-04-16 17:03:16 -07009349 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009350 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009351 AudioSystem::stopOutput(track->portId());
9352 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009353 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009354 AudioSystem::stopInput(track->portId());
9355 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009356 }
Eric Laurent331679c2018-04-16 17:03:16 -07009357 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009358
9359 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9360 if (chain != 0) {
9361 chain->decActiveTrackCnt();
9362 chain->decTrackCnt();
9363 }
9364
9365 broadcast_l();
9366
Eric Laurent6acd1d42017-01-04 14:23:29 -08009367 return NO_ERROR;
9368}
9369
Eric Laurent18b57012017-02-13 16:23:52 -08009370status_t AudioFlinger::MmapThread::standby()
9371{
9372 ALOGV("%s", __FUNCTION__);
9373
9374 if (mHalStream == 0) {
9375 return NO_INIT;
9376 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009377 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009378 return INVALID_OPERATION;
9379 }
9380 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009381 if (!mStandby) {
9382 mThreadMetrics.logEndInterval();
9383 mStandby = true;
9384 }
Eric Laurent18b57012017-02-13 16:23:52 -08009385 releaseWakeLock();
9386 return NO_ERROR;
9387}
9388
Eric Laurent6acd1d42017-01-04 14:23:29 -08009389
9390void AudioFlinger::MmapThread::readHalParameters_l()
9391{
9392 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9393 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9394 mFormat = mHALFormat;
9395 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9396 result = mHalStream->getFrameSize(&mFrameSize);
9397 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009398 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9399 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009400 result = mHalStream->getBufferSize(&mBufferSize);
9401 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9402 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009403
Andy Hungcf10d742020-04-28 15:38:24 -07009404 // TODO: make a readHalParameters call?
9405 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009406 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9407 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9408 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9409 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9410 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9411 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9412 /*
9413 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9414 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9415 (int32_t)mHapticChannelMask)
9416 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9417 (int32_t)mHapticChannelCount)
9418 */
9419 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9420 formatToString(mHALFormat).c_str())
9421 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9422 (int32_t)mFrameCount) // sic - added HAL
9423 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009424}
9425
9426bool AudioFlinger::MmapThread::threadLoop()
9427{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009428 checkSilentMode_l();
9429
9430 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9431
9432 while (!exitPending())
9433 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009434 Vector< sp<EffectChain> > effectChains;
9435
Andy Hung13850be2019-03-14 11:33:09 -07009436 { // under Thread lock
9437 Mutex::Autolock _l(mLock);
9438
Eric Laurent6acd1d42017-01-04 14:23:29 -08009439 if (mSignalPending) {
9440 // A signal was raised while we were unlocked
9441 mSignalPending = false;
9442 } else {
9443 if (mConfigEvents.isEmpty()) {
9444 // we're about to wait, flush the binder command buffer
9445 IPCThreadState::self()->flushCommands();
9446
9447 if (exitPending()) {
9448 break;
9449 }
9450
Eric Laurent6acd1d42017-01-04 14:23:29 -08009451 // wait until we have something to do...
9452 ALOGV("%s going to sleep", myName.string());
9453 mWaitWorkCV.wait(mLock);
9454 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009455
9456 checkSilentMode_l();
9457
9458 continue;
9459 }
9460 }
9461
9462 processConfigEvents_l();
9463
9464 processVolume_l();
9465
9466 checkInvalidTracks_l();
9467
9468 mActiveTracks.updatePowerState(this);
9469
Kevin Rocard069c2712018-03-29 19:09:14 -07009470 updateMetadata_l();
9471
Eric Laurent6acd1d42017-01-04 14:23:29 -08009472 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009473 } // release Thread lock
9474
Eric Laurent6acd1d42017-01-04 14:23:29 -08009475 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009476 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009477 }
Andy Hung13850be2019-03-14 11:33:09 -07009478
9479 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009480 unlockEffectChains(effectChains);
9481 // Effect chains will be actually deleted here if they were removed from
9482 // mEffectChains list during mixing or effects processing
9483 }
9484
9485 threadLoop_exit();
9486
9487 if (!mStandby) {
9488 threadLoop_standby();
9489 mStandby = true;
9490 }
9491
Eric Laurent6acd1d42017-01-04 14:23:29 -08009492 ALOGV("Thread %p type %d exiting", this, mType);
9493 return false;
9494}
9495
9496// checkForNewParameter_l() must be called with ThreadBase::mLock held
9497bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9498 status_t& status)
9499{
9500 AudioParameter param = AudioParameter(keyValuePair);
9501 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009502 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009503 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009504 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009505 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009506 if (sendToHal) {
9507 status = mHalStream->setParameters(keyValuePair);
9508 } else {
9509 status = NO_ERROR;
9510 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009511
9512 return false;
9513}
9514
9515String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9516{
9517 Mutex::Autolock _l(mLock);
9518 String8 out_s8;
9519 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9520 return out_s8;
9521 }
9522 return String8();
9523}
9524
Eric Laurent09f1ed22019-04-24 17:45:17 -07009525void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9526 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009527 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9528
9529 desc->mIoHandle = mId;
9530
9531 switch (event) {
9532 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009533 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009534 case AUDIO_INPUT_CONFIG_CHANGED:
9535 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009536 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009537 case AUDIO_OUTPUT_CONFIG_CHANGED:
9538 desc->mPatch = mPatch;
9539 desc->mChannelMask = mChannelMask;
9540 desc->mSamplingRate = mSampleRate;
9541 desc->mFormat = mFormat;
9542 desc->mFrameCount = mFrameCount;
9543 desc->mFrameCountHAL = mFrameCount;
9544 desc->mLatency = 0;
9545 break;
9546
9547 case AUDIO_INPUT_CLOSED:
9548 case AUDIO_OUTPUT_CLOSED:
9549 default:
9550 break;
9551 }
9552 mAudioFlinger->ioConfigChanged(event, desc, pid);
9553}
9554
9555status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9556 audio_patch_handle_t *handle)
9557{
9558 status_t status = NO_ERROR;
9559
9560 // store new device and send to effects
9561 audio_devices_t type = AUDIO_DEVICE_NONE;
9562 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009563 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9564 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9565 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009566 if (isOutput()) {
9567 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009568 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9569 && !mAudioHwDev->supportsAudioPatches(),
9570 "Enumerated device type(%#x) must not be used "
9571 "as it does not support audio patches",
9572 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009573 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009574 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9575 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009576 }
9577 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009578 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009579 } else {
9580 type = patch->sources[0].ext.device.type;
9581 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009582 numDevices = mPatch.num_sources;
9583 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009584 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009585 }
9586
9587 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009588 if (isOutput()) {
9589 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9590 } else {
9591 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9592 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009593 }
9594
jiabinc52b1ff2019-10-31 17:20:42 -07009595 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009596 // store new source and send to effects
9597 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9598 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9599 for (size_t i = 0; i < mEffectChains.size(); i++) {
9600 mEffectChains[i]->setAudioSource_l(mAudioSource);
9601 }
9602 }
9603 }
9604
9605 if (mAudioHwDev->supportsAudioPatches()) {
9606 status = mHalDevice->createAudioPatch(patch->num_sources,
9607 patch->sources,
9608 patch->num_sinks,
9609 patch->sinks,
9610 handle);
9611 } else {
9612 char *address;
9613 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9614 //FIXME: we only support address on first sink with HAL version < 3.0
9615 address = audio_device_address_to_parameter(
9616 patch->sinks[0].ext.device.type,
9617 patch->sinks[0].ext.device.address);
9618 } else {
9619 address = (char *)calloc(1, 1);
9620 }
9621 AudioParameter param = AudioParameter(String8(address));
9622 free(address);
9623 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9624 if (!isOutput()) {
9625 param.addInt(String8(AudioParameter::keyInputSource),
9626 (int)patch->sinks[0].ext.mix.usecase.source);
9627 }
9628 status = mHalStream->setParameters(param.toString());
9629 *handle = AUDIO_PATCH_HANDLE_NONE;
9630 }
9631
jiabinc52b1ff2019-10-31 17:20:42 -07009632 if (numDevices == 0 || mDeviceId != deviceId) {
9633 if (isOutput()) {
9634 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9635 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009636 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009637 } else {
9638 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9639 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9640 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009641 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009642 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009643 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009644 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009645 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009646 }
jiabinc52b1ff2019-10-31 17:20:42 -07009647 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009648 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009649 }
9650 return status;
9651}
9652
9653status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9654{
9655 status_t status = NO_ERROR;
9656
jiabinc52b1ff2019-10-31 17:20:42 -07009657 mPatch = audio_patch{};
9658 mOutDeviceTypeAddrs.clear();
9659 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009660
9661 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9662 supportsAudioPatches : false;
9663
9664 if (supportsAudioPatches) {
9665 status = mHalDevice->releaseAudioPatch(handle);
9666 } else {
9667 AudioParameter param;
9668 param.addInt(String8(AudioParameter::keyRouting), 0);
9669 status = mHalStream->setParameters(param.toString());
9670 }
9671 return status;
9672}
9673
Mikhail Naganovdc769682018-05-04 15:34:08 -07009674void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009675{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009676 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009677 if (isOutput()) {
9678 config->role = AUDIO_PORT_ROLE_SOURCE;
9679 config->ext.mix.hw_module = mAudioHwDev->handle();
9680 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9681 } else {
9682 config->role = AUDIO_PORT_ROLE_SINK;
9683 config->ext.mix.hw_module = mAudioHwDev->handle();
9684 config->ext.mix.usecase.source = mAudioSource;
9685 }
9686}
9687
9688status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9689{
9690 audio_session_t session = chain->sessionId();
9691
9692 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9693 // Attach all tracks with same session ID to this chain.
9694 // indicate all active tracks in the chain
9695 for (const sp<MmapTrack> &track : mActiveTracks) {
9696 if (session == track->sessionId()) {
9697 chain->incTrackCnt();
9698 chain->incActiveTrackCnt();
9699 }
9700 }
9701
9702 chain->setThread(this);
9703 chain->setInBuffer(nullptr);
9704 chain->setOutBuffer(nullptr);
9705 chain->syncHalEffectsState();
9706
9707 mEffectChains.add(chain);
9708 checkSuspendOnAddEffectChain_l(chain);
9709 return NO_ERROR;
9710}
9711
9712size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9713{
9714 audio_session_t session = chain->sessionId();
9715
9716 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9717
9718 for (size_t i = 0; i < mEffectChains.size(); i++) {
9719 if (chain == mEffectChains[i]) {
9720 mEffectChains.removeAt(i);
9721 // detach all active tracks from the chain
9722 // detach all tracks with same session ID from this chain
9723 for (const sp<MmapTrack> &track : mActiveTracks) {
9724 if (session == track->sessionId()) {
9725 chain->decActiveTrackCnt();
9726 chain->decTrackCnt();
9727 }
9728 }
9729 break;
9730 }
9731 }
9732 return mEffectChains.size();
9733}
9734
Eric Laurent6acd1d42017-01-04 14:23:29 -08009735void AudioFlinger::MmapThread::threadLoop_standby()
9736{
9737 mHalStream->standby();
9738}
9739
9740void AudioFlinger::MmapThread::threadLoop_exit()
9741{
Phil Burk7dce7282017-09-27 13:51:41 -07009742 // Do not call callback->onTearDown() because it is redundant for thread exit
9743 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009744}
9745
9746status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9747{
9748 return BAD_VALUE;
9749}
9750
9751bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9752{
9753 return false;
9754}
9755
9756status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9757 const effect_descriptor_t *desc, audio_session_t sessionId)
9758{
9759 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009760 if (audio_is_global_session(sessionId)) {
9761 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009762 desc->name, mThreadName);
9763 return BAD_VALUE;
9764 }
9765
9766 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9767 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9768 desc->name);
9769 return BAD_VALUE;
9770 }
9771 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009772 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9773 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009774 return BAD_VALUE;
9775 }
9776
9777 // Only allow effects without processing load or latency
9778 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9779 return BAD_VALUE;
9780 }
9781
jiabineb3bda02020-06-30 14:07:03 -07009782 if (EffectModule::isHapticGenerator(&desc->type)) {
9783 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9784 return BAD_VALUE;
9785 }
9786
Eric Laurent6acd1d42017-01-04 14:23:29 -08009787 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009788}
9789
9790void AudioFlinger::MmapThread::checkInvalidTracks_l()
9791{
9792 for (const sp<MmapTrack> &track : mActiveTracks) {
9793 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009794 sp<MmapStreamCallback> callback = mCallback.promote();
9795 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009796 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009797 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009798 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009799 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9800 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9801 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009802 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009803 }
9804 }
9805}
9806
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009807void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009808{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009809 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9810 mAttr.content_type, mAttr.usage, mAttr.source);
9811 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009812 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009813 dprintf(fd, " No active clients\n");
9814 }
9815}
9816
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009817void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009818{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009819 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009820 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009821 dprintf(fd, " %zu Tracks\n", numtracks);
9822 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009823 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009824 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009825 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009826 for (size_t i = 0; i < numtracks ; ++i) {
9827 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009828 result.append(prefix);
9829 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009830 }
9831 } else {
9832 dprintf(fd, "\n");
9833 }
9834 write(fd, result.string(), result.size());
9835}
9836
9837AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9838 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009839 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009840 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009841 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009842 mStreamVolume(1.0),
9843 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009844 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009845{
9846 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9847 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9848 mMasterVolume = audioFlinger->masterVolume_l();
9849 mMasterMute = audioFlinger->masterMute_l();
9850 if (mAudioHwDev) {
9851 if (mAudioHwDev->canSetMasterVolume()) {
9852 mMasterVolume = 1.0;
9853 }
9854
9855 if (mAudioHwDev->canSetMasterMute()) {
9856 mMasterMute = false;
9857 }
9858 }
9859}
9860
9861void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9862 audio_stream_type_t streamType,
9863 audio_session_t sessionId,
9864 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009865 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009866 audio_port_handle_t portId)
9867{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009868 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009869 mStreamType = streamType;
9870}
9871
9872AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9873{
9874 Mutex::Autolock _l(mLock);
9875 AudioStreamOut *output = mOutput;
9876 mOutput = NULL;
9877 return output;
9878}
9879
9880void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9881{
9882 Mutex::Autolock _l(mLock);
9883 // Don't apply master volume in SW if our HAL can do it for us.
9884 if (mAudioHwDev &&
9885 mAudioHwDev->canSetMasterVolume()) {
9886 mMasterVolume = 1.0;
9887 } else {
9888 mMasterVolume = value;
9889 }
9890}
9891
9892void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9893{
9894 Mutex::Autolock _l(mLock);
9895 // Don't apply master mute in SW if our HAL can do it for us.
9896 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9897 mMasterMute = false;
9898 } else {
9899 mMasterMute = muted;
9900 }
9901}
9902
9903void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9904{
9905 Mutex::Autolock _l(mLock);
9906 if (stream == mStreamType) {
9907 mStreamVolume = value;
9908 broadcast_l();
9909 }
9910}
9911
9912float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9913{
9914 Mutex::Autolock _l(mLock);
9915 if (stream == mStreamType) {
9916 return mStreamVolume;
9917 }
9918 return 0.0f;
9919}
9920
9921void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9922{
9923 Mutex::Autolock _l(mLock);
9924 if (stream == mStreamType) {
9925 mStreamMute= muted;
9926 broadcast_l();
9927 }
9928}
9929
9930void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9931{
9932 Mutex::Autolock _l(mLock);
9933 if (streamType == mStreamType) {
9934 for (const sp<MmapTrack> &track : mActiveTracks) {
9935 track->invalidate();
9936 }
9937 broadcast_l();
9938 }
9939}
9940
9941void AudioFlinger::MmapPlaybackThread::processVolume_l()
9942{
9943 float volume;
9944
9945 if (mMasterMute || mStreamMute) {
9946 volume = 0;
9947 } else {
9948 volume = mMasterVolume * mStreamVolume;
9949 }
9950
9951 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009952
9953 // Convert volumes from float to 8.24
9954 uint32_t vol = (uint32_t)(volume * (1 << 24));
9955
9956 // Delegate volume control to effect in track effect chain if needed
9957 // only one effect chain can be present on DirectOutputThread, so if
9958 // there is one, the track is connected to it
9959 if (!mEffectChains.isEmpty()) {
9960 mEffectChains[0]->setVolume_l(&vol, &vol);
9961 volume = (float)vol / (1 << 24);
9962 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009963 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009964 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9965 mHalVolFloat = volume; // HW volume control worked, so update value.
9966 mNoCallbackWarningCount = 0;
9967 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009968 sp<MmapStreamCallback> callback = mCallback.promote();
9969 if (callback != 0) {
9970 int channelCount;
9971 if (isOutput()) {
9972 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9973 } else {
9974 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9975 }
9976 Vector<float> values;
9977 for (int i = 0; i < channelCount; i++) {
9978 values.add(volume);
9979 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009980 mHalVolFloat = volume; // SW volume control worked, so update value.
9981 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009982 mLock.unlock();
9983 callback->onVolumeChanged(mChannelMask, values);
9984 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009985 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009986 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9987 ALOGW("Could not set MMAP stream volume: no volume callback!");
9988 mNoCallbackWarningCount++;
9989 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009990 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009991 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009992 for (const sp<MmapTrack> &track : mActiveTracks) {
9993 track->setMetadataHasChanged();
9994 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009995 }
9996}
9997
Kevin Rocard069c2712018-03-29 19:09:14 -07009998void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9999{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010000 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10001 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010002 }
10003 StreamOutHalInterface::SourceMetadata metadata;
10004 for (const sp<MmapTrack> &track : mActiveTracks) {
10005 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010006 playback_track_metadata_v7_t trackMetadata;
10007 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010008 .usage = track->attributes().usage,
10009 .content_type = track->attributes().content_type,
10010 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010011 };
10012 trackMetadata.channel_mask = track->channelMask(),
10013 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10014 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010015 }
10016 mOutput->stream->updateSourceMetadata(metadata);
10017}
10018
Eric Laurent6acd1d42017-01-04 14:23:29 -080010019void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10020{
10021 if (!mMasterMute) {
10022 char value[PROPERTY_VALUE_MAX];
10023 if (property_get("ro.audio.silent", value, "0") > 0) {
10024 char *endptr;
10025 unsigned long ul = strtoul(value, &endptr, 0);
10026 if (*endptr == '\0' && ul != 0) {
10027 ALOGD("Silence is golden");
10028 // The setprop command will not allow a property to be changed after
10029 // the first time it is set, so we don't have to worry about un-muting.
10030 setMasterMute_l(true);
10031 }
10032 }
10033 }
10034}
10035
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010036void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10037{
10038 MmapThread::toAudioPortConfig(config);
10039 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10040 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10041 config->flags.output = mOutput->flags;
10042 }
10043}
10044
jiabinb7d8c5a2020-08-26 17:24:52 -070010045status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10046 int64_t *timeNanos)
10047{
10048 if (mOutput == nullptr) {
10049 return NO_INIT;
10050 }
10051 struct timespec timestamp;
10052 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10053 if (status == NO_ERROR) {
10054 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10055 }
10056 return status;
10057}
10058
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010059void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010060{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010061 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010062
Glenn Kastend3bb6452016-12-05 18:14:37 -080010063 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10064 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010065 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10066}
10067
10068AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10069 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010070 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010071 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010072 mInput(input)
10073{
10074 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10075 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10076}
10077
Eric Laurent331679c2018-04-16 17:03:16 -070010078status_t AudioFlinger::MmapCaptureThread::exitStandby()
10079{
Phil Burkf054fc32018-12-06 09:45:59 -080010080 {
10081 // mInput might have been cleared by clearInput()
10082 Mutex::Autolock _l(mLock);
10083 if (mInput != nullptr && mInput->stream != nullptr) {
10084 mInput->stream->setGain(1.0f);
10085 }
10086 }
Eric Laurent331679c2018-04-16 17:03:16 -070010087 return MmapThread::exitStandby();
10088}
10089
Eric Laurent6acd1d42017-01-04 14:23:29 -080010090AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10091{
10092 Mutex::Autolock _l(mLock);
10093 AudioStreamIn *input = mInput;
10094 mInput = NULL;
10095 return input;
10096}
Kevin Rocard069c2712018-03-29 19:09:14 -070010097
Eric Laurent331679c2018-04-16 17:03:16 -070010098
10099void AudioFlinger::MmapCaptureThread::processVolume_l()
10100{
10101 bool changed = false;
10102 bool silenced = false;
10103
10104 sp<MmapStreamCallback> callback = mCallback.promote();
10105 if (callback == 0) {
10106 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10107 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10108 mNoCallbackWarningCount++;
10109 }
10110 }
10111
10112 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10113 // track is silenced and unmute otherwise
10114 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10115 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10116 changed = true;
10117 silenced = mActiveTracks[i]->isSilenced_l();
10118 }
10119 }
10120
10121 if (changed) {
10122 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10123 }
10124}
10125
Kevin Rocard069c2712018-03-29 19:09:14 -070010126void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10127{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010128 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10129 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010130 }
10131 StreamInHalInterface::SinkMetadata metadata;
10132 for (const sp<MmapTrack> &track : mActiveTracks) {
10133 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010134 record_track_metadata_v7_t trackMetadata;
10135 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010136 .source = track->attributes().source,
10137 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010138 };
10139 trackMetadata.channel_mask = track->channelMask(),
10140 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10141 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010142 }
10143 mInput->stream->updateSinkMetadata(metadata);
10144}
10145
Eric Laurent5ada82e2019-08-29 17:53:54 -070010146void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010147{
10148 Mutex::Autolock _l(mLock);
10149 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010150 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010151 mActiveTracks[i]->setSilenced_l(silenced);
10152 broadcast_l();
10153 }
10154 }
10155}
10156
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010157void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10158{
10159 MmapThread::toAudioPortConfig(config);
10160 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10161 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10162 config->flags.input = mInput->flags;
10163 }
10164}
10165
jiabinb7d8c5a2020-08-26 17:24:52 -070010166status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10167 uint64_t *position, int64_t *timeNanos)
10168{
10169 if (mInput == nullptr) {
10170 return NO_INIT;
10171 }
10172 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10173}
10174
Glenn Kasten63238ef2015-03-02 15:50:29 -080010175} // namespace android