blob: 88c9ba563bb1c3ea654a4d1e1a63fd520adc1f7d [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>
jiabin10d86fd2019-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))
Andy Hung6770c6f2015-04-07 13:43:36 -0700111template <typename T>
112static inline T min(const T& a, const T& b)
113{
114 return a < b ? a : b;
115}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700116
Eric Laurent81784c32012-11-19 14:55:58 -0800117namespace android {
118
119// retry counts for buffer fill timeout
120// 50 * ~20msecs = 1 second
121static const int8_t kMaxTrackRetries = 50;
122static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung0765c9a2021-04-27 17:46:12 -0700123
Eric Laurent81784c32012-11-19 14:55:58 -0800124// allow less retry attempts on direct output thread.
125// direct outputs can be a scarce resource in audio hardware and should
126// be released as quickly as possible.
Andy Hung0765c9a2021-04-27 17:46:12 -0700127// Notes:
128// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
129// in case the data write is bursty for the AudioTrack. The application
130// should endeavor to write at least once every kMaxTrackRetriesDirectMs
131// to prevent an underrun situation. If the data is bursty, then
132// the application can also throttle the data sent to be even.
133// 2) For compressed audio data, any data present in the AudioTrack buffer
134// will be sent and reset the retry count. This delivers data as
135// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
136// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
137// of data to be available, then any remaining data is delivered.
138// This is required to ensure the last bit of data is delivered before underrun.
139//
140// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
141// or the size of the HAL period for proportional / linear PCM tracks.
142static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800143
144// don't warn about blocked writes or record buffer overflows more often than this
145static const nsecs_t kWarningThrottleNs = seconds(5);
146
147// RecordThread loop sleep time upon application overrun or audio HAL read error
148static const int kRecordThreadSleepUs = 5000;
149
Eric Laurent10351942014-05-08 18:49:52 -0700150// maximum time to wait in sendConfigEvent_l() for a status to be received
151static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800152
153// minimum sleep time for the mixer thread loop when tracks are active but in underrun
154static const uint32_t kMinThreadSleepTimeUs = 5000;
155// maximum divider applied to the active sleep time in the mixer thread loop
156static const uint32_t kMaxThreadSleepTimeShift = 2;
157
Andy Hung09a50072014-02-27 14:30:47 -0800158// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700159// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800160static const uint32_t kMinNormalSinkBufferSizeMs = 20;
161// maximum normal sink buffer size
162static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700164// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
165// FIXME This should be based on experimentally observed scheduling jitter
166static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
167
Eric Laurent972a1732013-09-04 09:42:59 -0700168// Offloaded output thread standby delay: allows track transition without going to standby
169static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
170
Eric Laurent51716182016-02-29 18:00:56 -0800171// Direct output thread minimum sleep time in idle or active(underrun) state
172static const nsecs_t kDirectMinSleepTimeUs = 10000;
173
Glenn Kasten1b291842016-07-18 14:55:21 -0700174// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
175// balance between power consumption and latency, and allows threads to be scheduled reliably
176// by the CFS scheduler.
177// FIXME Express other hardcoded references to 20ms with references to this constant and move
178// it appropriately.
179#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800180
Eric Laurent81784c32012-11-19 14:55:58 -0800181// Whether to use fast mixer
182static const enum {
183 FastMixer_Never, // never initialize or use: for debugging only
184 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
185 // normal mixer multiplier is 1
186 FastMixer_Static, // initialize if needed, then use all the time if initialized,
187 // multiplier is calculated based on min & max normal mixer buffer size
188 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
189 // multiplier is calculated based on min & max normal mixer buffer size
190 // FIXME for FastMixer_Dynamic:
191 // Supporting this option will require fixing HALs that can't handle large writes.
192 // For example, one HAL implementation returns an error from a large write,
193 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
194 // We could either fix the HAL implementations, or provide a wrapper that breaks
195 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
196} kUseFastMixer = FastMixer_Static;
197
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700198// Whether to use fast capture
199static const enum {
200 FastCapture_Never, // never initialize or use: for debugging only
201 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
202 FastCapture_Static, // initialize if needed, then use all the time if initialized
203} kUseFastCapture = FastCapture_Static;
204
Eric Laurent81784c32012-11-19 14:55:58 -0800205// Priorities for requestPriority
206static const int kPriorityAudioApp = 2;
207static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700208static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800209
Glenn Kastenea38ee72016-04-18 11:08:01 -0700210// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
211// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
212// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700213
214// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800215static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800216
Glenn Kasten03490092014-05-27 12:30:54 -0700217// The minimum and maximum allowed values
218static const int kFastTrackMultiplierMin = 1;
219static const int kFastTrackMultiplierMax = 2;
220
221// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
222static int sFastTrackMultiplier = kFastTrackMultiplier;
223
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700224// See Thread::readOnlyHeap().
225// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
226// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
227// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700228static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700229
Eric Laurent81784c32012-11-19 14:55:58 -0800230// ----------------------------------------------------------------------------
231
Andy Hungb68f5eb2019-12-03 16:49:17 -0800232// TODO: move all toString helpers to audio.h
233// under #ifdef __cplusplus #endif
234static std::string patchSinksToString(const struct audio_patch *patch)
235{
236 std::stringstream ss;
237 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700238 if (i > 0) {
239 ss << "|";
240 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800241 ss << "(" << toString(patch->sinks[i].ext.device.type)
242 << ", " << patch->sinks[i].ext.device.address << ")";
243 }
244 return ss.str();
245}
246
247static std::string patchSourcesToString(const struct audio_patch *patch)
248{
249 std::stringstream ss;
250 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700251 if (i > 0) {
252 ss << "|";
253 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800254 ss << "(" << toString(patch->sources[i].ext.device.type)
255 << ", " << patch->sources[i].ext.device.address << ")";
256 }
257 return ss.str();
258}
259
Glenn Kasten03490092014-05-27 12:30:54 -0700260static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
261
262static void sFastTrackMultiplierInit()
263{
264 char value[PROPERTY_VALUE_MAX];
265 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
266 char *endptr;
267 unsigned long ul = strtoul(value, &endptr, 0);
268 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
269 sFastTrackMultiplier = (int) ul;
270 }
271 }
272}
273
274// ----------------------------------------------------------------------------
275
Eric Laurent81784c32012-11-19 14:55:58 -0800276#ifdef ADD_BATTERY_DATA
277// To collect the amplifier usage
278static void addBatteryData(uint32_t params) {
279 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
280 if (service == NULL) {
281 // it already logged
282 return;
283 }
284
285 service->addBatteryData(params);
286}
287#endif
288
Andy Hung3f0c9022016-01-15 17:49:46 -0800289// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
290struct {
291 // call when you acquire a partial wakelock
292 void acquire(const sp<IBinder> &wakeLockToken) {
293 pthread_mutex_lock(&mLock);
294 if (wakeLockToken.get() == nullptr) {
295 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
296 } else {
297 if (mCount == 0) {
298 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
299 }
300 ++mCount;
301 }
302 pthread_mutex_unlock(&mLock);
303 }
304
305 // call when you release a partial wakelock.
306 void release(const sp<IBinder> &wakeLockToken) {
307 if (wakeLockToken.get() == nullptr) {
308 return;
309 }
310 pthread_mutex_lock(&mLock);
311 if (--mCount < 0) {
312 ALOGE("negative wakelock count");
313 mCount = 0;
314 }
315 pthread_mutex_unlock(&mLock);
316 }
317
318 // retrieves the boottime timebase offset from monotonic.
319 int64_t getBoottimeOffset() {
320 pthread_mutex_lock(&mLock);
321 int64_t boottimeOffset = mBoottimeOffset;
322 pthread_mutex_unlock(&mLock);
323 return boottimeOffset;
324 }
325
326 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
327 // and the selected timebase.
328 // Currently only TIMEBASE_BOOTTIME is allowed.
329 //
330 // This only needs to be called upon acquiring the first partial wakelock
331 // after all other partial wakelocks are released.
332 //
333 // We do an empirical measurement of the offset rather than parsing
334 // /proc/timer_list since the latter is not a formal kernel ABI.
335 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
336 int clockbase;
337 switch (timebase) {
338 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
339 clockbase = SYSTEM_TIME_BOOTTIME;
340 break;
341 default:
342 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
343 break;
344 }
345 // try three times to get the clock offset, choose the one
346 // with the minimum gap in measurements.
347 const int tries = 3;
348 nsecs_t bestGap, measured;
349 for (int i = 0; i < tries; ++i) {
350 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
351 const nsecs_t tbase = systemTime(clockbase);
352 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
353 const nsecs_t gap = tmono2 - tmono;
354 if (i == 0 || gap < bestGap) {
355 bestGap = gap;
356 measured = tbase - ((tmono + tmono2) >> 1);
357 }
358 }
359
360 // to avoid micro-adjusting, we don't change the timebase
361 // unless it is significantly different.
362 //
363 // Assumption: It probably takes more than toleranceNs to
364 // suspend and resume the device.
365 static int64_t toleranceNs = 10000; // 10 us
366 if (llabs(*offset - measured) > toleranceNs) {
367 ALOGV("Adjusting timebase offset old: %lld new: %lld",
368 (long long)*offset, (long long)measured);
369 *offset = measured;
370 }
371 }
372
373 pthread_mutex_t mLock;
374 int32_t mCount;
375 int64_t mBoottimeOffset;
376} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800377
378// ----------------------------------------------------------------------------
379// CPU Stats
380// ----------------------------------------------------------------------------
381
382class CpuStats {
383public:
384 CpuStats();
385 void sample(const String8 &title);
386#ifdef DEBUG_CPU_USAGE
387private:
388 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700389 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800390
Andy Hung16698b82018-08-01 10:48:38 -0700391 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800392
393 int mCpuNum; // thread's current CPU number
394 int mCpukHz; // frequency of thread's current CPU in kHz
395#endif
396};
397
398CpuStats::CpuStats()
399#ifdef DEBUG_CPU_USAGE
400 : mCpuNum(-1), mCpukHz(-1)
401#endif
402{
403}
404
Glenn Kasten0f11b512014-01-31 16:18:54 -0800405void CpuStats::sample(const String8 &title
406#ifndef DEBUG_CPU_USAGE
407 __unused
408#endif
409 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800410#ifdef DEBUG_CPU_USAGE
411 // get current thread's delta CPU time in wall clock ns
412 double wcNs;
413 bool valid = mCpuUsage.sampleAndEnable(wcNs);
414
415 // record sample for wall clock statistics
416 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700417 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800418 }
419
420 // get the current CPU number
421 int cpuNum = sched_getcpu();
422
423 // get the current CPU frequency in kHz
424 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
425
426 // check if either CPU number or frequency changed
427 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
428 mCpuNum = cpuNum;
429 mCpukHz = cpukHz;
430 // ignore sample for purposes of cycles
431 valid = false;
432 }
433
434 // if no change in CPU number or frequency, then record sample for cycle statistics
435 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700436 const double cycles = wcNs * cpukHz * 0.000001;
437 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800438 }
439
Eric Tan5b13ff82018-07-27 11:20:17 -0700440 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800441 // mCpuUsage.elapsed() is expensive, so don't call it every loop
442 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700443 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800444 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700445 const double perLoop = elapsed / (double) n;
446 const double perLoop100 = perLoop * 0.01;
447 const double perLoop1k = perLoop * 0.001;
448 const double mean = mWcStats.getMean();
449 const double stddev = mWcStats.getStdDev();
450 const double minimum = mWcStats.getMin();
451 const double maximum = mWcStats.getMax();
452 const double meanCycles = mHzStats.getMean();
453 const double stddevCycles = mHzStats.getStdDev();
454 const double minCycles = mHzStats.getMin();
455 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800456 mCpuUsage.resetElapsed();
457 mWcStats.reset();
458 mHzStats.reset();
459 ALOGD("CPU usage for %s over past %.1f secs\n"
460 " (%u mixer loops at %.1f mean ms per loop):\n"
461 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
462 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
463 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
464 title.string(),
465 elapsed * .000000001, n, perLoop * .000001,
466 mean * .001,
467 stddev * .001,
468 minimum * .001,
469 maximum * .001,
470 mean / perLoop100,
471 stddev / perLoop100,
472 minimum / perLoop100,
473 maximum / perLoop100,
474 meanCycles / perLoop1k,
475 stddevCycles / perLoop1k,
476 minCycles / perLoop1k,
477 maxCycles / perLoop1k);
478
479 }
480 }
481#endif
482};
483
484// ----------------------------------------------------------------------------
485// ThreadBase
486// ----------------------------------------------------------------------------
487
Glenn Kasten97b7b752014-09-28 13:04:24 -0700488// static
489const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
490{
491 switch (type) {
492 case MIXER:
493 return "MIXER";
494 case DIRECT:
495 return "DIRECT";
496 case DUPLICATING:
497 return "DUPLICATING";
498 case RECORD:
499 return "RECORD";
500 case OFFLOAD:
501 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700502 case MMAP_PLAYBACK:
503 return "MMAP_PLAYBACK";
504 case MMAP_CAPTURE:
505 return "MMAP_CAPTURE";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700506 default:
507 return "unknown";
508 }
509}
510
Eric Laurent81784c32012-11-19 14:55:58 -0800511AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700512 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800513 : Thread(false /*canCallJava*/),
514 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700515 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700516 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
517 isOut),
518 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700519 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800520 // are set by PlaybackThread::readOutputParameters_l() or
521 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700522 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabin10d86fd2019-10-31 17:20:42 -0700523 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700524 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800525 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700526 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800527 mSystemReady(systemReady),
528 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800529{
Andy Hungcf10d742020-04-28 15:38:24 -0700530 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700531 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800532}
533
534AudioFlinger::ThreadBase::~ThreadBase()
535{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700536 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700537 mConfigEvents.clear();
538
Eric Laurent81784c32012-11-19 14:55:58 -0800539 // do not lock the mutex in destructor
540 releaseWakeLock_l();
541 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800542 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800543 binder->unlinkToDeath(mDeathRecipient);
544 }
Andy Hungd0979812019-02-21 15:51:44 -0800545
546 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800547}
548
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700549status_t AudioFlinger::ThreadBase::readyToRun()
550{
551 status_t status = initCheck();
552 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800553 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700554 } else {
555 ALOGE("No working audio driver found.");
556 }
557 return status;
558}
559
Eric Laurent81784c32012-11-19 14:55:58 -0800560void AudioFlinger::ThreadBase::exit()
561{
562 ALOGV("ThreadBase::exit");
563 // do any cleanup required for exit to succeed
564 preExit();
565 {
566 // This lock prevents the following race in thread (uniprocessor for illustration):
567 // if (!exitPending()) {
568 // // context switch from here to exit()
569 // // exit() calls requestExit(), what exitPending() observes
570 // // exit() calls signal(), which is dropped since no waiters
571 // // context switch back from exit() to here
572 // mWaitWorkCV.wait(...);
573 // // now thread is hung
574 // }
575 AutoMutex lock(mLock);
576 requestExit();
577 mWaitWorkCV.broadcast();
578 }
579 // When Thread::requestExitAndWait is made virtual and this method is renamed to
580 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
581 requestExitAndWait();
582}
583
584status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
585{
Eric Laurent81784c32012-11-19 14:55:58 -0800586 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
587 Mutex::Autolock _l(mLock);
588
Eric Laurent10351942014-05-08 18:49:52 -0700589 return sendSetParameterConfigEvent_l(keyValuePairs);
590}
591
592// sendConfigEvent_l() must be called with ThreadBase::mLock held
593// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
594status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
595{
596 status_t status = NO_ERROR;
597
Eric Laurent72e3f392015-05-20 14:43:50 -0700598 if (event->mRequiresSystemReady && !mSystemReady) {
599 event->mWaitStatus = false;
600 mPendingConfigEvents.add(event);
601 return status;
602 }
Eric Laurent10351942014-05-08 18:49:52 -0700603 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700604 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800605 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700606 mLock.unlock();
607 {
608 Mutex::Autolock _l(event->mLock);
609 while (event->mWaitStatus) {
610 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
611 event->mStatus = TIMED_OUT;
612 event->mWaitStatus = false;
613 }
614 }
615 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800616 }
Eric Laurent10351942014-05-08 18:49:52 -0700617 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800618 return status;
619}
620
Eric Laurent09f1ed22019-04-24 17:45:17 -0700621void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
622 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800623{
624 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700625 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800626}
627
628// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700629void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
630 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
Andy Hungd0979812019-02-21 15:51:44 -0800632 // The audio statistics history is exponentially weighted to forget events
633 // about five or more seconds in the past. In order to have
634 // crisper statistics for mediametrics, we reset the statistics on
635 // an IoConfigEvent, to reflect different properties for a new device.
636 mIoJitterMs.reset();
637 mLatencyMs.reset();
638 mProcessTimeMs.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100639 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800640
Eric Laurent09f1ed22019-04-24 17:45:17 -0700641 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700642 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800643}
644
Mikhail Naganov83f04272017-02-07 10:45:09 -0800645void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700646{
647 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800648 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700649}
650
Eric Laurent81784c32012-11-19 14:55:58 -0800651// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800652void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
653 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800654{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800655 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700656 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800657}
658
Eric Laurent10351942014-05-08 18:49:52 -0700659// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
660status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800661{
Andy Hung2ddee192015-12-18 17:34:44 -0800662 sp<ConfigEvent> configEvent;
663 AudioParameter param(keyValuePair);
664 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700665 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800666 setMasterMono_l(value != 0);
667 if (param.size() == 1) {
668 return NO_ERROR; // should be a solo parameter - we don't pass down
669 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700670 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800671 configEvent = new SetParameterConfigEvent(param.toString());
672 } else {
673 configEvent = new SetParameterConfigEvent(keyValuePair);
674 }
Eric Laurent10351942014-05-08 18:49:52 -0700675 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700676}
677
Eric Laurent1c333e22014-05-20 10:48:17 -0700678status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
679 const struct audio_patch *patch,
680 audio_patch_handle_t *handle)
681{
682 Mutex::Autolock _l(mLock);
683 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
684 status_t status = sendConfigEvent_l(configEvent);
685 if (status == NO_ERROR) {
686 CreateAudioPatchConfigEventData *data =
687 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
688 *handle = data->mHandle;
689 }
690 return status;
691}
692
693status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
694 const audio_patch_handle_t handle)
695{
696 Mutex::Autolock _l(mLock);
697 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
698 return sendConfigEvent_l(configEvent);
699}
700
jiabin10d86fd2019-10-31 17:20:42 -0700701status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
702 const DeviceDescriptorBaseVector& outDevices)
703{
704 if (type() != RECORD) {
705 // The update out device operation is only for record thread.
706 return INVALID_OPERATION;
707 }
708 Mutex::Autolock _l(mLock);
709 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
710 return sendConfigEvent_l(configEvent);
711}
712
Eric Laurent1c333e22014-05-20 10:48:17 -0700713
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700714// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700715void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700716{
Eric Laurent10351942014-05-08 18:49:52 -0700717 bool configChanged = false;
718
Eric Laurent81784c32012-11-19 14:55:58 -0800719 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700720 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700721 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800722 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700723 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700724 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700725 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
726 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800727 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700728 true /*asynchronous*/);
729 if (err != 0) {
730 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700731 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700732 }
733 } break;
734 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700735 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700736 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700737 } break;
738 case CFG_EVENT_SET_PARAMETER: {
739 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
740 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
741 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700742 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
743 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700744 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700745 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700746 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabin10d86fd2019-10-31 17:20:42 -0700747 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700748 CreateAudioPatchConfigEventData *data =
749 (CreateAudioPatchConfigEventData *)event->mData.get();
750 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabin10d86fd2019-10-31 17:20:42 -0700751 const DeviceTypeSet newDevices = getDeviceTypes();
752 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
753 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
754 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700755 } break;
756 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabin10d86fd2019-10-31 17:20:42 -0700757 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700758 ReleaseAudioPatchConfigEventData *data =
759 (ReleaseAudioPatchConfigEventData *)event->mData.get();
760 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabin10d86fd2019-10-31 17:20:42 -0700761 const DeviceTypeSet newDevices = getDeviceTypes();
762 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
763 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
764 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
765 } break;
766 case CFG_EVENT_UPDATE_OUT_DEVICE: {
767 UpdateOutDevicesConfigEventData *data =
768 (UpdateOutDevicesConfigEventData *)event->mData.get();
769 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700770 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700771 default:
Eric Laurent10351942014-05-08 18:49:52 -0700772 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700773 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800774 }
Eric Laurent10351942014-05-08 18:49:52 -0700775 {
776 Mutex::Autolock _l(event->mLock);
777 if (event->mWaitStatus) {
778 event->mWaitStatus = false;
779 event->mCond.signal();
780 }
781 }
782 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
783 }
784
785 if (configChanged) {
786 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800787 }
Eric Laurent81784c32012-11-19 14:55:58 -0800788}
789
Marco Nelissenb2208842014-02-07 14:00:50 -0800790String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
791 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700792 const audio_channel_representation_t representation =
793 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794
795 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800796 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700797 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
798 if (output) {
799 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
800 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
801 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
802 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
803 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
804 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
805 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
806 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
807 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
808 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
809 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
810 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
811 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
812 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
813 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
814 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700815 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
816 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
817 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
818 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
819 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
820 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
821 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
822 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low_frequency_2, ");
823 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
824 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700825 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
826 } else {
827 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
828 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
829 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
830 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
831 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
832 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
833 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
834 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
835 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
836 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
837 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
838 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700839 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
840 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
841 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
842 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700843 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
844 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700845 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
846 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
847 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
848 }
849 const int len = s.length();
850 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700851 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700852 s.unlockBuffer(len - 2); // remove trailing ", "
853 }
854 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800855 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700856 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
857 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
858 return s;
859 default:
860 s.appendFormat("unknown mask, representation:%d bits:%#x",
861 representation, audio_channel_mask_get_bits(mask));
862 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800863 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800864}
865
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700866void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800867{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800868 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
869 this, mThreadName, getTid(), type(), threadTypeToString(type()));
870
Eric Laurent81784c32012-11-19 14:55:58 -0800871 bool locked = AudioFlinger::dumpTryLock(mLock);
872 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800873 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800874 }
875
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700876 dumpBase_l(fd, args);
877 dumpInternals_l(fd, args);
878 dumpTracks_l(fd, args);
879 dumpEffectChains_l(fd, args);
880
881 if (locked) {
882 mLock.unlock();
883 }
884
885 dprintf(fd, " Local log:\n");
886 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
887}
888
889void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
890{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700891 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700892 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700893 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700894 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700895 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700896 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700897 dprintf(fd, " Channel count: %u\n", mChannelCount);
898 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800899 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700900 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700901 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700902 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800903 size_t numConfig = mConfigEvents.size();
904 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700905 const size_t SIZE = 256;
906 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800907 for (size_t i = 0; i < numConfig; i++) {
908 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700909 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800910 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700911 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800912 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700913 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800914 }
Andy Hung293558a2017-03-21 12:19:20 -0700915 // Note: output device may be used by capture threads for effects such as AEC.
jiabin10d86fd2019-10-31 17:20:42 -0700916 dprintf(fd, " Output devices: %s (%s)\n",
917 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
918 dprintf(fd, " Input device: %#x (%s)\n",
919 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800920 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800921
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700922 // Dump timestamp statistics for the Thread types that support it.
923 if (mType == RECORD
924 || mType == MIXER
925 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700926 || mType == DIRECT
927 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700928 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700929 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700930 }
931
Andy Hung446f4df2019-02-21 12:26:41 -0800932 if (mLastIoBeginNs > 0) { // MMAP may not set this
933 dprintf(fd, " Last %s occurred (msecs): %lld\n",
934 isOutput() ? "write" : "read",
935 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
936 }
937
938 if (mProcessTimeMs.getN() > 0) {
939 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
940 }
941
942 if (mIoJitterMs.getN() > 0) {
943 dprintf(fd, " Hal %s jitter ms stats: %s\n",
944 isOutput() ? "write" : "read",
945 mIoJitterMs.toString().c_str());
946 }
947
Andy Hunge6c37112019-02-26 17:38:10 -0800948 if (mLatencyMs.getN() > 0) {
949 dprintf(fd, " Threadloop %s latency stats: %s\n",
950 isOutput() ? "write" : "read",
951 mLatencyMs.toString().c_str());
952 }
Eric Laurent81784c32012-11-19 14:55:58 -0800953}
954
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700955void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800956{
957 const size_t SIZE = 256;
958 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800959
Marco Nelissenb2208842014-02-07 14:00:50 -0800960 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000961 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800962 write(fd, buffer, strlen(buffer));
963
Marco Nelissenb2208842014-02-07 14:00:50 -0800964 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800965 sp<EffectChain> chain = mEffectChains[i];
966 if (chain != 0) {
967 chain->dump(fd, args);
968 }
969 }
970}
971
Andy Hungdae27702016-10-31 14:01:16 -0700972void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800973{
974 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700975 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800976}
977
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100978String16 AudioFlinger::ThreadBase::getWakeLockTag()
979{
980 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800981 case MIXER:
982 return String16("AudioMix");
983 case DIRECT:
984 return String16("AudioDirectOut");
985 case DUPLICATING:
986 return String16("AudioDup");
987 case RECORD:
988 return String16("AudioIn");
989 case OFFLOAD:
990 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -0700991 case MMAP_PLAYBACK:
992 return String16("MmapPlayback");
993 case MMAP_CAPTURE:
994 return String16("MmapCapture");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800995 default:
996 ALOG_ASSERT(false);
997 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100998 }
999}
1000
Andy Hungdae27702016-10-31 14:01:16 -07001001void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001002{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001003 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001004 if (mPowerManager != 0) {
1005 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001006 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
1007 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001008 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001009 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001010 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001011 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001012 if (status == NO_ERROR) {
1013 mWakeLockToken = binder;
1014 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001015 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001016 }
Wei Jia3f273d12015-11-24 09:06:49 -08001017
Andy Hung3f0c9022016-01-15 17:49:46 -08001018 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001019 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1020 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001021}
1022
1023void AudioFlinger::ThreadBase::releaseWakeLock()
1024{
1025 Mutex::Autolock _l(mLock);
1026 releaseWakeLock_l();
1027}
1028
1029void AudioFlinger::ThreadBase::releaseWakeLock_l()
1030{
Andy Hung3f0c9022016-01-15 17:49:46 -08001031 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001032 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001033 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001034 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001035 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1036 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001037 }
1038 mWakeLockToken.clear();
1039 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001040}
1041
1042void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001043 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001044 // use checkService() to avoid blocking if power service is not up yet
1045 sp<IBinder> binder =
1046 defaultServiceManager()->checkService(String16("power"));
1047 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001048 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001049 } else {
1050 mPowerManager = interface_cast<IPowerManager>(binder);
1051 binder->linkToDeath(mDeathRecipient);
1052 }
1053 }
1054}
1055
Andy Hungd01b0f12016-11-07 16:10:30 -08001056void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001057 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001058
1059#if !LOG_NDEBUG
1060 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001061 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001062 s << uid << " ";
1063 }
1064 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1065#endif
1066
Andy Hung438e7572015-12-14 15:51:17 -08001067 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1068 if (mSystemReady) {
1069 ALOGE("no wake lock to update, but system ready!");
1070 } else {
1071 ALOGW("no wake lock to update, system not ready yet");
1072 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001073 return;
1074 }
1075 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001076 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
1077 status_t status = mPowerManager->updateWakeLockUids(
1078 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
1079 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001080 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001081 }
1082}
1083
Eric Laurent81784c32012-11-19 14:55:58 -08001084void AudioFlinger::ThreadBase::clearPowerManager()
1085{
1086 Mutex::Autolock _l(mLock);
1087 releaseWakeLock_l();
1088 mPowerManager.clear();
1089}
1090
jiabin10d86fd2019-10-31 17:20:42 -07001091void AudioFlinger::ThreadBase::updateOutDevices(
1092 const DeviceDescriptorBaseVector& outDevices __unused)
1093{
1094 ALOGE("%s should only be called in RecordThread", __func__);
1095}
1096
Glenn Kasten0f11b512014-01-31 16:18:54 -08001097void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001098{
1099 sp<ThreadBase> thread = mThread.promote();
1100 if (thread != 0) {
1101 thread->clearPowerManager();
1102 }
1103 ALOGW("power manager service died !!!");
1104}
1105
Eric Laurent81784c32012-11-19 14:55:58 -08001106void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001107 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001108{
1109 sp<EffectChain> chain = getEffectChain_l(sessionId);
1110 if (chain != 0) {
1111 if (type != NULL) {
1112 chain->setEffectSuspended_l(type, suspend);
1113 } else {
1114 chain->setEffectSuspendedAll_l(suspend);
1115 }
1116 }
1117
1118 updateSuspendedSessions_l(type, suspend, sessionId);
1119}
1120
1121void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1122{
1123 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1124 if (index < 0) {
1125 return;
1126 }
1127
1128 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1129 mSuspendedSessions.valueAt(index);
1130
1131 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001132 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001133 for (int j = 0; j < desc->mRefCount; j++) {
1134 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1135 chain->setEffectSuspendedAll_l(true);
1136 } else {
1137 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1138 desc->mType.timeLow);
1139 chain->setEffectSuspended_l(&desc->mType, true);
1140 }
1141 }
1142 }
1143}
1144
1145void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1146 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001147 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001148{
1149 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1150
1151 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1152
1153 if (suspend) {
1154 if (index >= 0) {
1155 sessionEffects = mSuspendedSessions.valueAt(index);
1156 } else {
1157 mSuspendedSessions.add(sessionId, sessionEffects);
1158 }
1159 } else {
1160 if (index < 0) {
1161 return;
1162 }
1163 sessionEffects = mSuspendedSessions.valueAt(index);
1164 }
1165
1166
1167 int key = EffectChain::kKeyForSuspendAll;
1168 if (type != NULL) {
1169 key = type->timeLow;
1170 }
1171 index = sessionEffects.indexOfKey(key);
1172
1173 sp<SuspendedSessionDesc> desc;
1174 if (suspend) {
1175 if (index >= 0) {
1176 desc = sessionEffects.valueAt(index);
1177 } else {
1178 desc = new SuspendedSessionDesc();
1179 if (type != NULL) {
1180 desc->mType = *type;
1181 }
1182 sessionEffects.add(key, desc);
1183 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1184 }
1185 desc->mRefCount++;
1186 } else {
1187 if (index < 0) {
1188 return;
1189 }
1190 desc = sessionEffects.valueAt(index);
1191 if (--desc->mRefCount == 0) {
1192 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1193 sessionEffects.removeItemsAt(index);
1194 if (sessionEffects.isEmpty()) {
1195 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1196 sessionId);
1197 mSuspendedSessions.removeItem(sessionId);
1198 }
1199 }
1200 }
1201 if (!sessionEffects.isEmpty()) {
1202 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1203 }
1204}
1205
Eric Laurent5d885392019-12-13 10:56:31 -08001206void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1207 audio_session_t sessionId,
1208 bool threadLocked) {
1209 if (!threadLocked) {
1210 mLock.lock();
1211 }
Eric Laurent81784c32012-11-19 14:55:58 -08001212
Eric Laurent81784c32012-11-19 14:55:58 -08001213 if (mType != RECORD) {
1214 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1215 // another session. This gives the priority to well behaved effect control panels
1216 // and applications not using global effects.
1217 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1218 // global effects
Eric Laurenta20c4e92019-11-12 15:55:51 -08001219 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001220 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1221 }
1222 }
1223
Eric Laurent5d885392019-12-13 10:56:31 -08001224 if (!threadLocked) {
1225 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001226 }
1227}
1228
Eric Laurent4c415062016-06-17 16:14:16 -07001229// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1230status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1231 const effect_descriptor_t *desc, audio_session_t sessionId)
1232{
Eric Laurenta20c4e92019-11-12 15:55:51 -08001233 // No global output effect sessions on record threads
1234 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1235 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001236 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1237 desc->name, mThreadName);
1238 return BAD_VALUE;
1239 }
1240 // only pre processing effects on record thread
1241 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1242 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1243 desc->name, mThreadName);
1244 return BAD_VALUE;
1245 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001246
1247 // always allow effects without processing load or latency
1248 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1249 return NO_ERROR;
1250 }
1251
Eric Laurent4c415062016-06-17 16:14:16 -07001252 audio_input_flags_t flags = mInput->flags;
1253 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1254 if (flags & AUDIO_INPUT_FLAG_RAW) {
1255 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1256 desc->name, mThreadName);
1257 return BAD_VALUE;
1258 }
1259 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1260 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1261 desc->name, mThreadName);
1262 return BAD_VALUE;
1263 }
1264 }
1265 return NO_ERROR;
1266}
1267
1268// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1269status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1270 const effect_descriptor_t *desc, audio_session_t sessionId)
1271{
1272 // no preprocessing on playback threads
1273 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1274 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1275 " thread %s", desc->name, mThreadName);
1276 return BAD_VALUE;
1277 }
1278
Eric Laurent3e4de772017-07-16 16:55:08 -07001279 // always allow effects without processing load or latency
1280 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1281 return NO_ERROR;
1282 }
1283
Eric Laurent4c415062016-06-17 16:14:16 -07001284 switch (mType) {
1285 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001286#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001287 // Reject any effect on mixer multichannel sinks.
1288 // TODO: fix both format and multichannel issues with effects.
1289 if (mChannelCount != FCC_2) {
1290 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1291 " thread %s", desc->name, mChannelCount, mThreadName);
1292 return BAD_VALUE;
1293 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001294#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001295 audio_output_flags_t flags = mOutput->flags;
1296 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1297 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1298 // global effects are applied only to non fast tracks if they are SW
1299 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1300 break;
1301 }
1302 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1303 // only post processing on output stage session
1304 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1305 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1306 " on output stage session", desc->name);
1307 return BAD_VALUE;
1308 }
Eric Laurenta20c4e92019-11-12 15:55:51 -08001309 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1310 // only post processing on output stage session
1311 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1312 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1313 " on device session", desc->name);
1314 return BAD_VALUE;
1315 }
Eric Laurent4c415062016-06-17 16:14:16 -07001316 } else {
1317 // no restriction on effects applied on non fast tracks
1318 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1319 break;
1320 }
1321 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001322
Eric Laurent4c415062016-06-17 16:14:16 -07001323 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1324 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1325 desc->name);
1326 return BAD_VALUE;
1327 }
1328 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1329 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1330 " in fast mode", desc->name);
1331 return BAD_VALUE;
1332 }
1333 }
1334 } break;
1335 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001336 // nothing actionable on offload threads, if the effect:
1337 // - is offloadable: the effect can be created
1338 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1339 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001340 break;
1341 case DIRECT:
1342 // Reject any effect on Direct output threads for now, since the format of
1343 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1344 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1345 desc->name, mThreadName);
1346 return BAD_VALUE;
1347 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001348#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001349 // Reject any effect on mixer multichannel sinks.
1350 // TODO: fix both format and multichannel issues with effects.
1351 if (mChannelCount != FCC_2) {
1352 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1353 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1354 return BAD_VALUE;
1355 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001356#endif
Eric Laurenta20c4e92019-11-12 15:55:51 -08001357 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001358 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1359 " thread %s", desc->name, mThreadName);
1360 return BAD_VALUE;
1361 }
1362 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1363 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1364 " DUPLICATING thread %s", desc->name, mThreadName);
1365 return BAD_VALUE;
1366 }
1367 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1368 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1369 " DUPLICATING thread %s", desc->name, mThreadName);
1370 return BAD_VALUE;
1371 }
1372 break;
1373 default:
1374 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1375 }
1376
1377 return NO_ERROR;
1378}
1379
Eric Laurent81784c32012-11-19 14:55:58 -08001380// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1381sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1382 const sp<AudioFlinger::Client>& client,
1383 const sp<IEffectClient>& effectClient,
1384 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001385 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001386 effect_descriptor_t *desc,
1387 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001388 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001389 bool pinned,
1390 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001391{
1392 sp<EffectModule> effect;
1393 sp<EffectHandle> handle;
1394 status_t lStatus;
1395 sp<EffectChain> chain;
1396 bool chainCreated = false;
1397 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001398 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001399
1400 lStatus = initCheck();
1401 if (lStatus != NO_ERROR) {
1402 ALOGW("createEffect_l() Audio driver not initialized.");
1403 goto Exit;
1404 }
1405
Eric Laurent81784c32012-11-19 14:55:58 -08001406 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1407
1408 { // scope for mLock
1409 Mutex::Autolock _l(mLock);
1410
Eric Laurent4c415062016-06-17 16:14:16 -07001411 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001412 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001413 goto Exit;
1414 }
1415
Eric Laurent81784c32012-11-19 14:55:58 -08001416 // check for existing effect chain with the requested audio session
1417 chain = getEffectChain_l(sessionId);
1418 if (chain == 0) {
1419 // create a new chain for this session
1420 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1421 chain = new EffectChain(this, sessionId);
1422 addEffectChain_l(chain);
1423 chain->setStrategy(getStrategyForSession_l(sessionId));
1424 chainCreated = true;
1425 } else {
1426 effect = chain->getEffectFromDesc_l(desc);
1427 }
1428
1429 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1430
1431 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001432 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001433 // create a new effect module if none present in the chain
Eric Laurent5d885392019-12-13 10:56:31 -08001434 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001435 if (lStatus != NO_ERROR) {
1436 goto Exit;
1437 }
1438 effectCreated = true;
1439
jiabin10d86fd2019-10-31 17:20:42 -07001440 // FIXME: use vector of device and address when effect interface is ready.
jiabinb8269fd2019-11-11 12:16:27 -08001441 effect->setDevices(outDeviceTypeAddrs());
1442 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001443 effect->setMode(mAudioFlinger->getMode());
1444 effect->setAudioSource(mAudioSource);
1445 }
1446 // create effect handle and connect it to effect module
1447 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001448 lStatus = handle->initCheck();
1449 if (lStatus == OK) {
1450 lStatus = effect->addHandle(handle.get());
1451 }
Eric Laurent81784c32012-11-19 14:55:58 -08001452 if (enabled != NULL) {
1453 *enabled = (int)effect->isEnabled();
1454 }
1455 }
1456
1457Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001458 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001459 Mutex::Autolock _l(mLock);
1460 if (effectCreated) {
1461 chain->removeEffect_l(effect);
1462 }
Eric Laurent81784c32012-11-19 14:55:58 -08001463 if (chainCreated) {
1464 removeEffectChain_l(chain);
1465 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001466 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001467 }
1468
Glenn Kasten9156ef32013-08-06 15:39:08 -07001469 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001470 return handle;
1471}
1472
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001473void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1474 bool unpinIfLast)
1475{
1476 bool remove = false;
1477 sp<EffectModule> effect;
1478 {
1479 Mutex::Autolock _l(mLock);
Eric Laurente0b9a362019-12-16 19:34:05 -08001480 sp<EffectBase> effectBase = handle->effect().promote();
1481 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001482 return;
1483 }
Eric Laurent9b2064c2019-11-22 17:25:04 -08001484 effect = effectBase->asEffectModule();
1485 if (effect == nullptr) {
1486 return;
1487 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001488 // restore suspended effects if the disconnected handle was enabled and the last one.
1489 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1490 if (remove) {
1491 removeEffect_l(effect, true);
1492 }
1493 }
1494 if (remove) {
1495 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001496 if (handle->enabled()) {
Eric Laurent5d885392019-12-13 10:56:31 -08001497 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001498 }
1499 }
1500}
1501
Eric Laurent5d885392019-12-13 10:56:31 -08001502void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001503 if (isOffloadOrMmap()) {
Eric Laurent5d885392019-12-13 10:56:31 -08001504 Mutex::Autolock _l(mLock);
1505 broadcast_l();
1506 }
1507 if (!effect->isOffloadable()) {
1508 if (mType == ThreadBase::OFFLOAD) {
1509 PlaybackThread *t = (PlaybackThread *)this;
1510 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1511 }
1512 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1513 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1514 }
1515 }
1516}
1517
1518void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001519 if (isOffloadOrMmap()) {
Eric Laurent5d885392019-12-13 10:56:31 -08001520 Mutex::Autolock _l(mLock);
1521 broadcast_l();
1522 }
1523}
1524
Glenn Kastend848eb42016-03-08 13:42:11 -08001525sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1526 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001527{
1528 Mutex::Autolock _l(mLock);
1529 return getEffect_l(sessionId, effectId);
1530}
1531
Glenn Kastend848eb42016-03-08 13:42:11 -08001532sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1533 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001534{
1535 sp<EffectChain> chain = getEffectChain_l(sessionId);
1536 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1537}
1538
Eric Laurent6c796322019-04-09 14:13:17 -07001539std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1540{
1541 sp<EffectChain> chain = getEffectChain_l(sessionId);
1542 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1543}
1544
Eric Laurent81784c32012-11-19 14:55:58 -08001545// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1546// PlaybackThread::mLock held
1547status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1548{
1549 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001550 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001551 sp<EffectChain> chain = getEffectChain_l(sessionId);
1552 bool chainCreated = false;
1553
Eric Laurent5baf2af2013-09-12 17:37:00 -07001554 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001555 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001556 this, effect->desc().name, effect->desc().flags);
1557
Eric Laurent81784c32012-11-19 14:55:58 -08001558 if (chain == 0) {
1559 // create a new chain for this session
1560 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1561 chain = new EffectChain(this, sessionId);
1562 addEffectChain_l(chain);
1563 chain->setStrategy(getStrategyForSession_l(sessionId));
1564 chainCreated = true;
1565 }
1566 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1567
1568 if (chain->getEffectFromId_l(effect->id()) != 0) {
1569 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1570 this, effect->desc().name, chain.get());
1571 return BAD_VALUE;
1572 }
1573
Eric Laurent5baf2af2013-09-12 17:37:00 -07001574 effect->setOffloaded(mType == OFFLOAD, mId);
1575
Eric Laurent81784c32012-11-19 14:55:58 -08001576 status_t status = chain->addEffect_l(effect);
1577 if (status != NO_ERROR) {
1578 if (chainCreated) {
1579 removeEffectChain_l(chain);
1580 }
1581 return status;
1582 }
1583
jiabinb8269fd2019-11-11 12:16:27 -08001584 effect->setDevices(outDeviceTypeAddrs());
1585 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001586 effect->setMode(mAudioFlinger->getMode());
1587 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001588
Eric Laurent81784c32012-11-19 14:55:58 -08001589 return NO_ERROR;
1590}
1591
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001592void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001593
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001594 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001595 effect_descriptor_t desc = effect->desc();
1596 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1597 detachAuxEffect_l(effect->id());
1598 }
1599
Eric Laurent5d885392019-12-13 10:56:31 -08001600 sp<EffectChain> chain = effect->callback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001601 if (chain != 0) {
1602 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001603 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001604 removeEffectChain_l(chain);
1605 }
1606 } else {
1607 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1608 }
1609}
1610
1611void AudioFlinger::ThreadBase::lockEffectChains_l(
1612 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1613{
1614 effectChains = mEffectChains;
1615 for (size_t i = 0; i < mEffectChains.size(); i++) {
1616 mEffectChains[i]->lock();
1617 }
1618}
1619
1620void AudioFlinger::ThreadBase::unlockEffectChains(
1621 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1622{
1623 for (size_t i = 0; i < effectChains.size(); i++) {
1624 effectChains[i]->unlock();
1625 }
1626}
1627
Glenn Kastend848eb42016-03-08 13:42:11 -08001628sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001629{
1630 Mutex::Autolock _l(mLock);
1631 return getEffectChain_l(sessionId);
1632}
1633
Glenn Kastend848eb42016-03-08 13:42:11 -08001634sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1635 const
Eric Laurent81784c32012-11-19 14:55:58 -08001636{
1637 size_t size = mEffectChains.size();
1638 for (size_t i = 0; i < size; i++) {
1639 if (mEffectChains[i]->sessionId() == sessionId) {
1640 return mEffectChains[i];
1641 }
1642 }
1643 return 0;
1644}
1645
1646void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1647{
1648 Mutex::Autolock _l(mLock);
1649 size_t size = mEffectChains.size();
1650 for (size_t i = 0; i < size; i++) {
1651 mEffectChains[i]->setMode_l(mode);
1652 }
1653}
1654
Mikhail Naganovdc769682018-05-04 15:34:08 -07001655void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001656{
1657 config->type = AUDIO_PORT_TYPE_MIX;
1658 config->ext.mix.handle = mId;
1659 config->sample_rate = mSampleRate;
1660 config->format = mFormat;
1661 config->channel_mask = mChannelMask;
1662 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1663 AUDIO_PORT_CONFIG_FORMAT;
1664}
1665
Eric Laurent72e3f392015-05-20 14:43:50 -07001666void AudioFlinger::ThreadBase::systemReady()
1667{
1668 Mutex::Autolock _l(mLock);
1669 if (mSystemReady) {
1670 return;
1671 }
1672 mSystemReady = true;
1673
1674 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1675 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1676 }
1677 mPendingConfigEvents.clear();
1678}
1679
Andy Hungdae27702016-10-31 14:01:16 -07001680template <typename T>
1681ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1682 ssize_t index = mActiveTracks.indexOf(track);
1683 if (index >= 0) {
1684 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1685 return index;
1686 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001687 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001688 mActiveTracksGeneration++;
1689 mLatestActiveTrack = track;
1690 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001691 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001692 return mActiveTracks.add(track);
1693}
1694
1695template <typename T>
1696ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1697 ssize_t index = mActiveTracks.remove(track);
1698 if (index < 0) {
1699 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1700 return index;
1701 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001702 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001703 mActiveTracksGeneration++;
1704 --mBatteryCounter[track->uid()].second;
1705 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001706 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001707#ifdef TEE_SINK
1708 track->dumpTee(-1 /* fd */, "_REMOVE");
1709#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001710 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001711 return index;
1712}
1713
1714template <typename T>
1715void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1716 for (const sp<T> &track : mActiveTracks) {
1717 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001718 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001719 }
1720 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001721 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001722 mActiveTracks.clear();
1723 mLatestActiveTrack.clear();
1724 mBatteryCounter.clear();
1725}
1726
1727template <typename T>
1728void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1729 sp<ThreadBase> thread, bool force) {
1730 // Updates ActiveTracks client uids to the thread wakelock.
1731 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1732 thread->updateWakeLockUids_l(getWakeLockUids());
1733 mLastActiveTracksGeneration = mActiveTracksGeneration;
1734 }
1735
1736 // Updates BatteryNotifier uids
1737 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1738 const uid_t uid = it->first;
1739 ssize_t &previous = it->second.first;
1740 ssize_t &current = it->second.second;
1741 if (current > 0) {
1742 if (previous == 0) {
1743 BatteryNotifier::getInstance().noteStartAudio(uid);
1744 }
1745 previous = current;
1746 ++it;
1747 } else if (current == 0) {
1748 if (previous > 0) {
1749 BatteryNotifier::getInstance().noteStopAudio(uid);
1750 }
1751 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1752 } else /* (current < 0) */ {
1753 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1754 }
1755 }
1756}
Eric Laurent83b88082014-06-20 18:31:16 -07001757
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001758template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001759bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1760 const bool hasChanged = mHasChanged;
1761 mHasChanged = false;
1762 return hasChanged;
1763}
1764
1765template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001766void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1767 const char *funcName, const sp<T> &track) const {
1768 if (mLocalLog != nullptr) {
1769 String8 result;
1770 track->appendDump(result, false /* active */);
1771 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1772 }
1773}
1774
Eric Laurent6acd1d42017-01-04 14:23:29 -08001775void AudioFlinger::ThreadBase::broadcast_l()
1776{
1777 // Thread could be blocked waiting for async
1778 // so signal it to handle state changes immediately
1779 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1780 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1781 mSignalPending = true;
1782 mWaitWorkCV.broadcast();
1783}
1784
Andy Hungd0979812019-02-21 15:51:44 -08001785// Call only from threadLoop() or when it is idle.
1786// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1787void AudioFlinger::ThreadBase::sendStatistics(bool force)
1788{
1789 // Do not log if we have no stats.
1790 // We choose the timestamp verifier because it is the most likely item to be present.
1791 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1792 if (nstats == 0) {
1793 return;
1794 }
1795
1796 // Don't log more frequently than once per 12 hours.
1797 // We use BOOTTIME to include suspend time.
1798 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1799 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1800 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1801 return;
1802 }
1803
1804 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1805 mLastRecordedTimeNs = timeNs;
1806
Ray Essickf27e9872019-12-07 06:28:46 -08001807 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001808
1809#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1810
1811 // thread configuration
1812 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1813 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1814 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1815 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1816 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1817 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1818 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabin10d86fd2019-10-31 17:20:42 -07001819 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1820 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001821
1822 // thread statistics
1823 if (mIoJitterMs.getN() > 0) {
1824 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1825 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1826 }
1827 if (mProcessTimeMs.getN() > 0) {
1828 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1829 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1830 }
1831 const auto tsjitter = mTimestampVerifier.getJitterMs();
1832 if (tsjitter.getN() > 0) {
1833 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1834 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1835 }
1836 if (mLatencyMs.getN() > 0) {
1837 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1838 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1839 }
1840
1841 item->selfrecord();
1842}
1843
Eric Laurent81784c32012-11-19 14:55:58 -08001844// ----------------------------------------------------------------------------
1845// Playback
1846// ----------------------------------------------------------------------------
1847
1848AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1849 AudioStreamOut* output,
1850 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001851 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001852 bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07001853 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001854 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001855 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001856 mMixerBuffer(NULL),
1857 mMixerBufferSize(0),
1858 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1859 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001860 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001861 mEffectBuffer(NULL),
1862 mEffectBufferSize(0),
1863 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1864 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001865 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001866 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001867 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001868 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001869 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001870 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001871 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001872 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001873 mMixerStatus(MIXER_IDLE),
1874 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001875 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001876 mBytesRemaining(0),
1877 mCurrentWriteLength(0),
1878 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001879 mWriteAckSequence(0),
1880 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001881 mScreenState(AudioFlinger::mScreenState),
1882 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001883 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001884 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent029e33e2020-12-23 18:19:44 +01001885 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1886 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001887{
Glenn Kastend7dca052015-03-05 16:05:54 -08001888 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1889 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001890
1891 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1892 // it would be safer to explicitly pass initial masterVolume/masterMute as
1893 // parameter.
1894 //
1895 // If the HAL we are using has support for master volume or master mute,
1896 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1897 // and the mute set to false).
1898 mMasterVolume = audioFlinger->masterVolume_l();
1899 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001900 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001901 if (mOutput->audioHwDev->canSetMasterVolume()) {
1902 mMasterVolume = 1.0;
1903 }
1904
1905 if (mOutput->audioHwDev->canSetMasterMute()) {
1906 mMasterMute = false;
1907 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001908 mIsMsdDevice = strcmp(
1909 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001910 }
1911
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001912 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001913
Andy Hungc8fddf32018-08-08 18:32:37 -07001914 // TODO: We may also match on address as well as device type for
1915 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001916 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabin10d86fd2019-10-31 17:20:42 -07001917 // TODO: This property should be ensure that only contains one single device type.
1918 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1919 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001920 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1921 : AUDIO_DEVICE_NONE));
1922 }
1923
Mikhail Naganovdc6be0d2020-09-25 23:03:05 +00001924 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1925 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08001926 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001927 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1928 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001929 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001930 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1931 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001932 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1933 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001934}
1935
1936AudioFlinger::PlaybackThread::~PlaybackThread()
1937{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001938 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001939 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001940 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001941 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001942}
1943
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001944// Thread virtuals
1945
1946void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001947{
jiabinf6eb4c32020-02-25 14:06:25 -08001948 if (mOutput == nullptr || mOutput->stream == nullptr) {
1949 ALOGE("The stream is not open yet"); // This should not happen.
1950 } else {
1951 // setEventCallback will need a strong pointer as a parameter. Calling it
1952 // here instead of constructor of PlaybackThread so that the onFirstRef
1953 // callback would not be made on an incompletely constructed object.
1954 if (mOutput->stream->setEventCallback(this) != OK) {
1955 ALOGE("Failed to add event callback");
1956 }
1957 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001958 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001959}
1960
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001961// ThreadBase virtuals
1962void AudioFlinger::PlaybackThread::preExit()
1963{
1964 ALOGV(" preExit()");
1965 // FIXME this is using hard-coded strings but in the future, this functionality will be
1966 // converted to use audio HAL extensions required to support tunneling
1967 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1968 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1969}
1970
1971void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001972{
Eric Laurent81784c32012-11-19 14:55:58 -08001973 String8 result;
1974
Marco Nelissenb2208842014-02-07 14:00:50 -08001975 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001976 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1977 const stream_type_t *st = &mStreamTypes[i];
1978 if (i > 0) {
1979 result.appendFormat(", ");
1980 }
1981 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1982 if (st->mute) {
1983 result.append("M");
1984 }
1985 }
1986 result.append("\n");
1987 write(fd, result.string(), result.length());
1988 result.clear();
1989
Eric Laurent81784c32012-11-19 14:55:58 -08001990 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1991 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001992 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001993 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001994
1995 size_t numtracks = mTracks.size();
1996 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001997 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001998 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001999 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002000 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002001 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002002 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002003 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002004 for (size_t i = 0; i < numtracks; ++i) {
2005 sp<Track> track = mTracks[i];
2006 if (track != 0) {
2007 bool active = mActiveTracks.indexOf(track) >= 0;
2008 if (active) {
2009 numactiveseen++;
2010 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002011 result.append(prefix);
2012 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002013 }
2014 }
2015 } else {
2016 result.append("\n");
2017 }
2018 if (numactiveseen != numactive) {
2019 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002020 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002021 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002022 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002023 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002024 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002025 sp<Track> track = mActiveTracks[i];
2026 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002027 result.append(prefix);
2028 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002029 }
2030 }
2031 }
2032
2033 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002034}
2035
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002036void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002037{
Andy Hung04cb8f72020-03-20 13:44:33 -07002038 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002039 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002040 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2041 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2042 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2043 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002044 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002045 dprintf(fd, " Total writes: %d\n", mNumWrites);
2046 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2047 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2048 dprintf(fd, " Suspend count: %d\n", mSuspended);
2049 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2050 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2051 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2052 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002053 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002054 AudioStreamOut *output = mOutput;
2055 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002056 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002057 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002058 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2059 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2060 if (mPipeSink.get() != nullptr) {
2061 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2062 }
2063 if (output != nullptr) {
2064 dprintf(fd, " Hal stream dump:\n");
2065 (void)output->stream->dump(fd);
2066 }
Eric Laurent81784c32012-11-19 14:55:58 -08002067}
2068
Eric Laurent81784c32012-11-19 14:55:58 -08002069// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2070sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2071 const sp<AudioFlinger::Client>& client,
2072 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002073 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002074 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002075 audio_format_t format,
2076 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002077 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002078 size_t *pNotificationFrameCount,
2079 uint32_t notificationsPerBuffer,
2080 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002081 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002082 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002083 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002084 pid_t creatorPid,
Eric Laurent81784c32012-11-19 14:55:58 -08002085 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08002086 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002087 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002088 audio_port_handle_t portId,
jiabin375283d2020-08-21 18:14:43 -07002089 const sp<media::IAudioTrackCallback>& callback,
2090 const std::string& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08002091{
Glenn Kasten74935e42013-12-19 08:56:45 -08002092 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002093 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002094 sp<Track> track;
2095 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002096 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002097 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002098 uint32_t sampleRate;
2099
2100 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2101 lStatus = BAD_VALUE;
2102 goto Exit;
2103 }
Eric Laurent21da6472017-11-09 16:29:26 -08002104
2105 if (*pSampleRate == 0) {
2106 *pSampleRate = mSampleRate;
2107 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002108 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002109
2110 // special case for FAST flag considered OK if fast mixer is present
2111 if (hasFastMixer()) {
2112 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2113 }
2114
2115 // Check if requested flags are compatible with output stream flags
2116 if ((*flags & outputFlags) != *flags) {
2117 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2118 *flags, outputFlags);
2119 *flags = (audio_output_flags_t)(*flags & outputFlags);
2120 }
Eric Laurent81784c32012-11-19 14:55:58 -08002121
Eric Laurent81784c32012-11-19 14:55:58 -08002122 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002123 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002124 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002125 // PCM data
2126 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002127 // TODO: extract as a data library function that checks that a computationally
2128 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002129 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002130 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2131 (channelMask == AUDIO_CHANNEL_OUT_MONO
2132 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002133 // hardware sample rate
2134 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002135 // normal mixer has an associated fast mixer
2136 hasFastMixer() &&
2137 // there are sufficient fast track slots available
2138 (mFastTrackAvailMask != 0)
2139 // FIXME test that MixerThread for this fast track has a capable output HAL
2140 // FIXME add a permission test also?
2141 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002142 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2143 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002144 // read the fast track multiplier property the first time it is needed
2145 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2146 if (ok != 0) {
2147 ALOGE("%s pthread_once failed: %d", __func__, ok);
2148 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002149 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002150 }
Eric Laurent4c415062016-06-17 16:14:16 -07002151
2152 // check compatibility with audio effects.
2153 { // scope for mLock
2154 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002155 for (audio_session_t session : {
Eric Laurenta20c4e92019-11-12 15:55:51 -08002156 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002157 AUDIO_SESSION_OUTPUT_STAGE,
2158 AUDIO_SESSION_OUTPUT_MIX,
2159 sessionId,
2160 }) {
2161 sp<EffectChain> chain = getEffectChain_l(session);
2162 if (chain.get() != nullptr) {
2163 audio_output_flags_t old = *flags;
2164 chain->checkOutputFlagCompatibility(flags);
2165 if (old != *flags) {
2166 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2167 (int)session, (int)old, (int)*flags);
2168 }
Eric Laurent4c415062016-06-17 16:14:16 -07002169 }
2170 }
2171 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002172 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002173 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2174 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002175 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002176 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2177 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002178 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002179 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002180 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002181 audio_is_linear_pcm(format),
2182 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002183 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002184 }
2185 }
Eric Laurent21da6472017-11-09 16:29:26 -08002186
2187 if (!audio_has_proportional_frames(format)) {
2188 if (sharedBuffer != 0) {
2189 // Same comment as below about ignoring frameCount parameter for set()
2190 frameCount = sharedBuffer->size();
2191 } else if (frameCount == 0) {
2192 frameCount = mNormalFrameCount;
2193 }
2194 if (notificationFrameCount != frameCount) {
2195 notificationFrameCount = frameCount;
2196 }
2197 } else if (sharedBuffer != 0) {
2198 // FIXME: Ensure client side memory buffers need
2199 // not have additional alignment beyond sample
2200 // (e.g. 16 bit stereo accessed as 32 bit frame).
2201 size_t alignment = audio_bytes_per_sample(format);
2202 if (alignment & 1) {
2203 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2204 alignment = 1;
2205 }
2206 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2207 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2208 if (channelCount > 1) {
2209 // More than 2 channels does not require stronger alignment than stereo
2210 alignment <<= 1;
2211 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002212 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002213 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002214 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002215 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002216 goto Exit;
2217 }
Eric Laurent21da6472017-11-09 16:29:26 -08002218
2219 // When initializing a shared buffer AudioTrack via constructors,
2220 // there's no frameCount parameter.
2221 // But when initializing a shared buffer AudioTrack via set(),
2222 // there _is_ a frameCount parameter. We silently ignore it.
2223 frameCount = sharedBuffer->size() / frameSize;
2224 } else {
2225 size_t minFrameCount = 0;
2226 // For fast tracks we try to respect the application's request for notifications per buffer.
2227 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2228 if (notificationsPerBuffer > 0) {
2229 // Avoid possible arithmetic overflow during multiplication.
2230 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2231 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2232 notificationsPerBuffer, mFrameCount);
2233 } else {
2234 minFrameCount = mFrameCount * notificationsPerBuffer;
2235 }
2236 }
2237 } else {
2238 // For normal PCM streaming tracks, update minimum frame count.
2239 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2240 // cover audio hardware latency.
2241 // This is probably too conservative, but legacy application code may depend on it.
2242 // If you change this calculation, also review the start threshold which is related.
2243 uint32_t latencyMs = latency_l();
2244 if (latencyMs == 0) {
2245 ALOGE("Error when retrieving output stream latency");
2246 lStatus = UNKNOWN_ERROR;
2247 goto Exit;
2248 }
2249
2250 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2251 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2252
Eric Laurent81784c32012-11-19 14:55:58 -08002253 }
Eric Laurent21da6472017-11-09 16:29:26 -08002254 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002255 frameCount = minFrameCount;
2256 }
Eric Laurent81784c32012-11-19 14:55:58 -08002257 }
Eric Laurent21da6472017-11-09 16:29:26 -08002258
2259 // Make sure that application is notified with sufficient margin before underrun.
2260 // The client can divide the AudioTrack buffer into sub-buffers,
2261 // and expresses its desire to server as the notification frame count.
2262 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2263 size_t maxNotificationFrames;
2264 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2265 // notify every HAL buffer, regardless of the size of the track buffer
2266 maxNotificationFrames = mFrameCount;
2267 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002268 // Triple buffer the notification period for a triple buffered mixer period;
2269 // otherwise, double buffering for the notification period is fine.
2270 //
2271 // TODO: This should be moved to AudioTrack to modify the notification period
2272 // on AudioTrack::setBufferSizeInFrames() changes.
2273 const int nBuffering =
2274 (uint64_t{frameCount} * mSampleRate)
2275 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2276
Eric Laurent21da6472017-11-09 16:29:26 -08002277 maxNotificationFrames = frameCount / nBuffering;
2278 // If client requested a fast track but this was denied, then use the smaller maximum.
2279 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2280 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2281 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2282 maxNotificationFrames = maxNotificationFramesFastDenied;
2283 }
2284 }
2285 }
2286 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2287 if (notificationFrameCount == 0) {
2288 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2289 maxNotificationFrames, frameCount);
2290 } else {
2291 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2292 notificationFrameCount, maxNotificationFrames, frameCount);
2293 }
2294 notificationFrameCount = maxNotificationFrames;
2295 }
2296 }
2297
Glenn Kasten74935e42013-12-19 08:56:45 -08002298 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002299 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002300
Glenn Kastenc3df8382014-03-13 15:05:25 -07002301 switch (mType) {
2302
2303 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002304 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002305 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002306 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2307 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002308 sampleRate, format, channelMask, mOutput, mFormat);
2309 lStatus = BAD_VALUE;
2310 goto Exit;
2311 }
2312 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002313 break;
2314
2315 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002316 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002317 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2318 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002319 sampleRate, format, channelMask, mOutput, mFormat);
2320 lStatus = BAD_VALUE;
2321 goto Exit;
2322 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002323 break;
2324
2325 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002326 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002327 ALOGE("createTrack_l() Bad parameter: format %#x \""
2328 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002329 format, mOutput, mFormat);
2330 lStatus = BAD_VALUE;
2331 goto Exit;
2332 }
Andy Hungcd044842014-08-07 11:04:34 -07002333 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002334 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2335 lStatus = BAD_VALUE;
2336 goto Exit;
2337 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002338 break;
2339
Eric Laurent81784c32012-11-19 14:55:58 -08002340 }
2341
2342 lStatus = initCheck();
2343 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002344 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002345 goto Exit;
2346 }
2347
2348 { // scope for mLock
2349 Mutex::Autolock _l(mLock);
2350
2351 // all tracks in same audio session must share the same routing strategy otherwise
2352 // conflicts will happen when tracks are moved from one output to another by audio policy
2353 // manager
2354 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2355 for (size_t i = 0; i < mTracks.size(); ++i) {
2356 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002357 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002358 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2359 if (sessionId == t->sessionId() && strategy != actual) {
2360 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2361 strategy, actual);
2362 lStatus = BAD_VALUE;
2363 goto Exit;
2364 }
2365 }
2366 }
2367
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002368 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002369 channelMask, frameCount,
2370 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
jiabin375283d2020-08-21 18:14:43 -07002371 sessionId, creatorPid, uid, *flags, TrackBase::TYPE_DEFAULT, portId,
2372 SIZE_MAX /*frameCountToBeReady*/, opPackageName);
Glenn Kasten03003332013-08-06 15:40:54 -07002373
Glenn Kasten03003332013-08-06 15:40:54 -07002374 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2375 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002376 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002377 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002378 goto Exit;
2379 }
2380 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002381 {
2382 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2383 if (callback.get() != nullptr) {
jiabinb56e7432020-09-17 11:40:42 -07002384 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002385 }
2386 }
Eric Laurent81784c32012-11-19 14:55:58 -08002387
2388 sp<EffectChain> chain = getEffectChain_l(sessionId);
2389 if (chain != 0) {
2390 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2391 track->setMainBuffer(chain->inBuffer());
2392 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2393 chain->incTrackCnt();
2394 }
2395
Eric Laurent05067782016-06-01 18:27:28 -07002396 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002397 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2398 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2399 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002400 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002401 }
2402 }
2403
2404 lStatus = NO_ERROR;
2405
2406Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002407 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002408 return track;
2409}
2410
Andy Hung1bc088a2018-02-09 15:57:31 -08002411template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002412ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2413{
Andy Hungc0691382018-09-12 18:01:57 -07002414 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002415 const ssize_t index = mTracks.remove(track);
2416 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002417 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002418 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002419 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002420 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002421 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002422 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002423 }
2424 return index;
2425}
2426
Eric Laurent81784c32012-11-19 14:55:58 -08002427uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2428{
2429 return latency;
2430}
2431
2432uint32_t AudioFlinger::PlaybackThread::latency() const
2433{
2434 Mutex::Autolock _l(mLock);
2435 return latency_l();
2436}
2437uint32_t AudioFlinger::PlaybackThread::latency_l() const
2438{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002439 uint32_t latency;
2440 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2441 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002442 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002443 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002444}
2445
2446void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2447{
2448 Mutex::Autolock _l(mLock);
2449 // Don't apply master volume in SW if our HAL can do it for us.
2450 if (mOutput && mOutput->audioHwDev &&
2451 mOutput->audioHwDev->canSetMasterVolume()) {
2452 mMasterVolume = 1.0;
2453 } else {
2454 mMasterVolume = value;
2455 }
2456}
2457
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002458void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2459{
2460 mMasterBalance.store(balance);
2461}
2462
Eric Laurent81784c32012-11-19 14:55:58 -08002463void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2464{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002465 if (isDuplicating()) {
2466 return;
2467 }
Eric Laurent81784c32012-11-19 14:55:58 -08002468 Mutex::Autolock _l(mLock);
2469 // Don't apply master mute in SW if our HAL can do it for us.
2470 if (mOutput && mOutput->audioHwDev &&
2471 mOutput->audioHwDev->canSetMasterMute()) {
2472 mMasterMute = false;
2473 } else {
2474 mMasterMute = muted;
2475 }
2476}
2477
2478void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2479{
2480 Mutex::Autolock _l(mLock);
2481 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002482 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002483}
2484
2485void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2486{
2487 Mutex::Autolock _l(mLock);
2488 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002489 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002490}
2491
2492float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2493{
2494 Mutex::Autolock _l(mLock);
2495 return mStreamTypes[stream].volume;
2496}
2497
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002498void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2499{
2500 mOutput->stream->setVolume(left, right);
2501}
2502
Eric Laurent81784c32012-11-19 14:55:58 -08002503// addTrack_l() must be called with ThreadBase::mLock held
2504status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2505{
2506 status_t status = ALREADY_EXISTS;
2507
Eric Laurent81784c32012-11-19 14:55:58 -08002508 if (mActiveTracks.indexOf(track) < 0) {
2509 // the track is newly added, make sure it fills up all its
2510 // buffers before playing. This is to ensure the client will
2511 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002512 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002513 TrackBase::track_state state = track->mState;
2514 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002515 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002516 mLock.lock();
2517 // abort track was stopped/paused while we released the lock
2518 if (state != track->mState) {
2519 if (status == NO_ERROR) {
2520 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002521 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002522 mLock.lock();
2523 }
2524 return INVALID_OPERATION;
2525 }
2526 // abort if start is rejected by audio policy manager
2527 if (status != NO_ERROR) {
2528 return PERMISSION_DENIED;
2529 }
2530#ifdef ADD_BATTERY_DATA
2531 // to track the speaker usage
2532 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2533#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002534 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002535 }
2536
Eric Laurent51716182016-02-29 18:00:56 -08002537 // set retry count for buffer fill
2538 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002539 if (track->isStopping_1()) {
2540 track->mRetryCount = kMaxTrackStopRetriesOffload;
2541 } else {
2542 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2543 }
2544 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002545 } else {
2546 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002547 track->mFillingUpStatus =
2548 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002549 }
2550
jiabin245cdd92018-12-07 17:55:15 -08002551 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2552 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002553 // Unlock due to VibratorService will lock for this call and will
2554 // call Tracks.mute/unmute which also require thread's lock.
2555 mLock.unlock();
2556 const int intensity = AudioFlinger::onExternalVibrationStart(
2557 track->getExternalVibration());
2558 mLock.lock();
jiabinbf6b0ec2019-02-12 12:30:12 -08002559 track->setHapticIntensity(static_cast<AudioMixer::haptic_intensity_t>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002560 // Haptic playback should be enabled by vibrator service.
2561 if (track->getHapticPlaybackEnabled()) {
2562 // Disable haptic playback of all active track to ensure only
2563 // one track playing haptic if current track should play haptic.
2564 for (const auto &t : mActiveTracks) {
2565 t->setHapticPlaybackEnabled(false);
2566 }
jiabin245cdd92018-12-07 17:55:15 -08002567 }
jiabin245cdd92018-12-07 17:55:15 -08002568 }
2569
Eric Laurent81784c32012-11-19 14:55:58 -08002570 track->mResetDone = false;
2571 track->mPresentationCompleteFrames = 0;
2572 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002573 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2574 if (chain != 0) {
2575 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2576 track->sessionId());
2577 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002578 }
2579
Andy Hungc2b11cb2020-04-22 09:04:01 -07002580 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002581 status = NO_ERROR;
2582 }
2583
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002584 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002585 return status;
2586}
2587
Eric Laurentbfb1b832013-01-07 09:53:42 -08002588bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002589{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002591 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002592 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2593 track->mState = TrackBase::STOPPED;
2594 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002595 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002596 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002598 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599
2600 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002601}
2602
2603void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2604{
2605 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002606
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002607 String8 result;
2608 track->appendDump(result, false /* active */);
2609 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002610
Eric Laurent81784c32012-11-19 14:55:58 -08002611 mTracks.remove(track);
jiabinb56e7432020-09-17 11:40:42 -07002612 {
2613 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2614 mAudioTrackCallbacks.erase(track);
2615 }
Eric Laurent81784c32012-11-19 14:55:58 -08002616 if (track->isFastTrack()) {
2617 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002618 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002619 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2620 mFastTrackAvailMask |= 1 << index;
2621 // redundant as track is about to be destroyed, for dumpsys only
2622 track->mFastIndex = -1;
2623 }
2624 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2625 if (chain != 0) {
2626 chain->decTrackCnt();
2627 }
2628}
2629
2630String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2631{
Eric Laurent81784c32012-11-19 14:55:58 -08002632 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002633 String8 out_s8;
2634 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2635 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002636 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002637 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002638}
2639
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002640status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2641 Mutex::Autolock _l(mLock);
2642 if (mOutput == nullptr || mOutput->stream == nullptr) {
2643 return NO_INIT;
2644 }
2645 return mOutput->stream->selectPresentation(presentationId, programId);
2646}
2647
Eric Laurent09f1ed22019-04-24 17:45:17 -07002648void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2649 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002650 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2651 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002652
Eric Laurent73e26b62015-04-27 16:55:58 -07002653 desc->mIoHandle = mId;
Eric Laurent029e33e2020-12-23 18:19:44 +01002654 struct audio_patch patch = mPatch;
2655 if (isMsdDevice()) {
2656 patch = mDownStreamPatch;
2657 }
Eric Laurent81784c32012-11-19 14:55:58 -08002658
2659 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002660 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002661 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002662 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent029e33e2020-12-23 18:19:44 +01002663 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002664 desc->mChannelMask = mChannelMask;
2665 desc->mSamplingRate = mSampleRate;
2666 desc->mFormat = mFormat;
2667 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002668 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002669 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002670 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002671 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002672 case AUDIO_CLIENT_STARTED:
Eric Laurent029e33e2020-12-23 18:19:44 +01002673 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002674 desc->mPortId = portId;
2675 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002676 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002677 default:
2678 break;
2679 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002680 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002681}
2682
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002683void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002684{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002685 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686}
2687
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002688void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002689{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002690 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002691}
2692
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002693void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002694{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002695 mCallbackThread->setAsyncError();
2696}
2697
jiabinf6eb4c32020-02-25 14:06:25 -08002698void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2699 const std::basic_string<uint8_t>& metadataBs)
2700{
2701 std::thread([this, metadataBs]() {
2702 audio_utils::metadata::Data metadata =
2703 audio_utils::metadata::dataFromByteString(metadataBs);
2704 if (metadata.empty()) {
2705 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2706 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2707 (int)metadataBs.size());
2708 return;
2709 }
2710
2711 audio_utils::metadata::ByteString metaDataStr =
2712 audio_utils::metadata::byteStringFromData(metadata);
2713 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2714 Mutex::Autolock _l(mAudioTrackCbLock);
jiabinb56e7432020-09-17 11:40:42 -07002715 for (const auto& callbackPair : mAudioTrackCallbacks) {
2716 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002717 }
2718 }).detach();
2719}
2720
Eric Laurent3b4529e2013-09-05 18:09:19 -07002721void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002722{
2723 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002724 // reject out of sequence requests
2725 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2726 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727 mWaitWorkCV.signal();
2728 }
2729}
2730
Eric Laurent3b4529e2013-09-05 18:09:19 -07002731void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002732{
2733 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002734 // reject out of sequence requests
2735 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002736 // Register discontinuity when HW drain is completed because that can cause
2737 // the timestamp frame position to reset to 0 for direct and offload threads.
2738 // (Out of sequence requests are ignored, since the discontinuity would be handled
2739 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002740 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002741 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002742 mWaitWorkCV.signal();
2743 }
2744}
2745
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002746void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002747{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002748 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002749 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2750 mSampleRate = audioConfig.sample_rate;
2751 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002752 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002753 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002754 }
Andy Hung9a592762014-07-21 21:56:01 -07002755 if ((mType == MIXER || mType == DUPLICATING)
2756 && !isValidPcmSinkChannelMask(mChannelMask)) {
2757 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2758 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002759 }
Andy Hunge5412692014-05-16 11:25:07 -07002760 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002761 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002762
2763 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002764 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002765 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002766 // Get format from the shim, which will be different than the HAL format
2767 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002768 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002769 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002770 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002771 }
Andy Hung6146c082014-03-18 11:56:15 -07002772 if ((mType == MIXER || mType == DUPLICATING)
2773 && !isValidPcmSinkFormat(mFormat)) {
2774 LOG_FATAL("HAL format %#x not supported for mixed output",
2775 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002776 }
Phil Burk062e67a2015-02-11 13:40:50 -08002777 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002778 result = mOutput->stream->getBufferSize(&mBufferSize);
2779 LOG_ALWAYS_FATAL_IF(result != OK,
2780 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002781 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002782 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002783 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002784 mFrameCount);
2785 }
2786
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002787 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2788 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002789 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002790 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002791 }
2792 }
2793
Eric Laurentd1f69b02014-12-15 14:33:13 -08002794 mHwSupportsPause = false;
2795 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002796 bool supportsPause = false, supportsResume = false;
2797 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2798 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002799 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002800 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002801 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002802 } else if (supportsResume) {
2803 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002804 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002805 }
2806 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002807 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2808 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2809 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002810
Andy Hungfbfc3952015-01-15 13:33:51 -08002811 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2812 // For best precision, we use float instead of the associated output
2813 // device format (typically PCM 16 bit).
2814
2815 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2816 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2817 mBufferSize = mFrameSize * mFrameCount;
2818
2819 // TODO: We currently use the associated output device channel mask and sample rate.
2820 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2821 // (if a valid mask) to avoid premature downmix.
2822 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2823 // instead of the output device sample rate to avoid loss of high frequency information.
2824 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2825 }
2826
Andy Hung09a50072014-02-27 14:30:47 -08002827 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002828 double multiplier = 1.0;
2829 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2830 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002831 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2832 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002833
Eric Laurent81784c32012-11-19 14:55:58 -08002834 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2835 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2836 maxNormalFrameCount = maxNormalFrameCount & ~15;
2837 if (maxNormalFrameCount < minNormalFrameCount) {
2838 maxNormalFrameCount = minNormalFrameCount;
2839 }
2840 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2841 if (multiplier <= 1.0) {
2842 multiplier = 1.0;
2843 } else if (multiplier <= 2.0) {
2844 if (2 * mFrameCount <= maxNormalFrameCount) {
2845 multiplier = 2.0;
2846 } else {
2847 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2848 }
2849 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002850 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002851 }
2852 }
2853 mNormalFrameCount = multiplier * mFrameCount;
2854 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002855 if (mType == MIXER || mType == DUPLICATING) {
2856 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2857 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002858 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002859 mNormalFrameCount);
2860
Andy Hung08fb1742015-05-31 23:22:10 -07002861 // Check if we want to throttle the processing to no more than 2x normal rate
2862 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002863 mThreadThrottleTimeMs = 0;
2864 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002865 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2866
Andy Hung010a1a12014-03-13 13:57:33 -07002867 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2868 // Originally this was int16_t[] array, need to remove legacy implications.
2869 free(mSinkBuffer);
2870 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002871 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2872 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2873 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002874 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002875
Andy Hung69aed5f2014-02-25 17:24:40 -08002876 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2877 // drives the output.
2878 free(mMixerBuffer);
2879 mMixerBuffer = NULL;
2880 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002881 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002882 mMixerBufferSize = mNormalFrameCount * mChannelCount
2883 * audio_bytes_per_sample(mMixerBufferFormat);
2884 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2885 }
Andy Hung98ef9782014-03-04 14:46:50 -08002886 free(mEffectBuffer);
2887 mEffectBuffer = NULL;
2888 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002889 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002890 mEffectBufferSize = mNormalFrameCount * mChannelCount
2891 * audio_bytes_per_sample(mEffectBufferFormat);
2892 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2893 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002894
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07002895 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2896 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002897 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2898 mChannelCount -= mHapticChannelCount;
2899
Eric Laurent81784c32012-11-19 14:55:58 -08002900 // force reconfiguration of effect chains and engines to take new buffer size and audio
2901 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002902 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002903 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2904 // matter.
2905 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2906 Vector< sp<EffectChain> > effectChains = mEffectChains;
2907 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002908 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2909 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002910 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002911
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002912 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002913 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002914 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2915 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2916 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2917 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2918 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2919 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2920 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2921 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2922 (int32_t)mHapticChannelMask)
2923 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2924 (int32_t)mHapticChannelCount)
2925 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2926 formatToString(mHALFormat).c_str())
2927 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2928 (int32_t)mFrameCount) // sic - added HAL
2929 ;
2930 uint32_t latencyMs;
2931 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2932 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2933 }
2934 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08002935}
2936
Kevin Rocard069c2712018-03-29 19:09:14 -07002937void AudioFlinger::PlaybackThread::updateMetadata_l()
2938{
Kevin Rocard12381092018-04-11 09:19:59 -07002939 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2940 return; // That should not happen
2941 }
2942 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2943 for (const sp<Track> &track : mActiveTracks) {
2944 // Do not short-circuit as all hasChanged states must be reset
2945 // as all the metadata are going to be sent
2946 hasChanged |= track->readAndClearHasChanged();
2947 }
2948 if (!hasChanged) {
2949 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002950 }
2951 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002952 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002953 for (const sp<Track> &track : mActiveTracks) {
2954 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002955 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002956 }
Kevin Rocard12381092018-04-11 09:19:59 -07002957 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002958}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002959
Kevin Rocard12381092018-04-11 09:19:59 -07002960void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2961 const StreamOutHalInterface::SourceMetadata& metadata)
2962{
2963 mOutput->stream->updateSourceMetadata(metadata);
2964};
2965
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002966status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002967{
2968 if (halFrames == NULL || dspFrames == NULL) {
2969 return BAD_VALUE;
2970 }
2971 Mutex::Autolock _l(mLock);
2972 if (initCheck() != NO_ERROR) {
2973 return INVALID_OPERATION;
2974 }
Andy Hung818e7a32016-02-16 18:08:07 -08002975 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002976 *halFrames = framesWritten;
2977
2978 if (isSuspended()) {
2979 // return an estimation of rendered frames when the output is suspended
2980 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002981 *dspFrames = (uint32_t)
2982 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002983 return NO_ERROR;
2984 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002985 status_t status;
2986 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002987 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002988 *dspFrames = (size_t)frames;
2989 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002990 }
2991}
2992
Glenn Kastend848eb42016-03-08 13:42:11 -08002993uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002994{
2995 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2996 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2997 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2998 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2999 }
3000 for (size_t i = 0; i < mTracks.size(); i++) {
3001 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003002 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003003 return AudioSystem::getStrategyForStream(track->streamType());
3004 }
3005 }
3006 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3007}
3008
3009
Phil Burk062e67a2015-02-11 13:40:50 -08003010AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003011{
3012 Mutex::Autolock _l(mLock);
3013 return mOutput;
3014}
3015
Phil Burk062e67a2015-02-11 13:40:50 -08003016AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003017{
3018 Mutex::Autolock _l(mLock);
3019 AudioStreamOut *output = mOutput;
3020 mOutput = NULL;
3021 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3022 // must push a NULL and wait for ack
3023 mOutputSink.clear();
3024 mPipeSink.clear();
3025 mNormalSink.clear();
3026 return output;
3027}
3028
3029// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003030sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003031{
3032 if (mOutput == NULL) {
3033 return NULL;
3034 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003035 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003036}
3037
3038uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3039{
3040 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3041}
3042
3043status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3044{
3045 if (!isValidSyncEvent(event)) {
3046 return BAD_VALUE;
3047 }
3048
3049 Mutex::Autolock _l(mLock);
3050
3051 for (size_t i = 0; i < mTracks.size(); ++i) {
3052 sp<Track> track = mTracks[i];
3053 if (event->triggerSession() == track->sessionId()) {
3054 (void) track->setSyncEvent(event);
3055 return NO_ERROR;
3056 }
3057 }
3058
3059 return NAME_NOT_FOUND;
3060}
3061
3062bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3063{
3064 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3065}
3066
3067void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3068 const Vector< sp<Track> >& tracksToRemove)
3069{
Andy Hungfe726a62018-09-27 15:17:25 -07003070 // Miscellaneous track cleanup when removed from the active list,
3071 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003072#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003073 for (const auto& track : tracksToRemove) {
3074 if (track->isExternalTrack()) {
3075 // to track the speaker usage
3076 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003077 }
3078 }
Andy Hungfe726a62018-09-27 15:17:25 -07003079#else
3080 (void)tracksToRemove; // suppress unused warning
3081#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003082}
3083
3084void AudioFlinger::PlaybackThread::checkSilentMode_l()
3085{
3086 if (!mMasterMute) {
3087 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003088 if (mOutDeviceTypeAddrs.empty()) {
3089 ALOGD("ro.audio.silent is ignored since no output device is set");
3090 return;
3091 }
jiabin10d86fd2019-10-31 17:20:42 -07003092 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003093 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3094 return;
3095 }
Eric Laurent81784c32012-11-19 14:55:58 -08003096 if (property_get("ro.audio.silent", value, "0") > 0) {
3097 char *endptr;
3098 unsigned long ul = strtoul(value, &endptr, 0);
3099 if (*endptr == '\0' && ul != 0) {
3100 ALOGD("Silence is golden");
3101 // The setprop command will not allow a property to be changed after
3102 // the first time it is set, so we don't have to worry about un-muting.
3103 setMasterMute_l(true);
3104 }
3105 }
3106 }
3107}
3108
3109// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003110ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003111{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003112 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003113 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003114 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003115 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003116
3117 // If an NBAIO sink is present, use it to write the normal mixer's submix
3118 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003119
Andy Hung010a1a12014-03-13 13:57:33 -07003120 const size_t count = mBytesRemaining / mFrameSize;
3121
Simon Wilson2d590962012-11-29 15:18:50 -08003122 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003123 // update the setpoint when AudioFlinger::mScreenState changes
3124 uint32_t screenState = AudioFlinger::mScreenState;
3125 if (screenState != mScreenState) {
3126 mScreenState = screenState;
3127 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3128 if (pipe != NULL) {
3129 pipe->setAvgFrames((mScreenState & 1) ?
3130 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3131 }
3132 }
Andy Hung010a1a12014-03-13 13:57:33 -07003133 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003134 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003135 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003136 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003137#ifdef TEE_SINK
3138 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3139#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003140 } else {
3141 bytesWritten = framesWritten;
3142 }
3143 // otherwise use the HAL / AudioStreamOut directly
3144 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003145 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003146
Eric Laurentbfb1b832013-01-07 09:53:42 -08003147 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003148 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3149 mWriteAckSequence += 2;
3150 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003151 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003152 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003153 }
Mikhail Naganov76e89c32019-08-15 20:18:47 -07003154 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003155 // FIXME We should have an implementation of timestamps for direct output threads.
3156 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003157 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganov76e89c32019-08-15 20:18:47 -07003158 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003159
Eric Laurentbfb1b832013-01-07 09:53:42 -08003160 if (mUseAsyncWrite &&
3161 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3162 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003163 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003165 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003166 }
Eric Laurent81784c32012-11-19 14:55:58 -08003167 }
3168
Eric Laurent81784c32012-11-19 14:55:58 -08003169 mNumWrites++;
3170 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003171 if (mStandby) {
3172 mThreadMetrics.logBeginInterval();
3173 mStandby = false;
3174 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003175 return bytesWritten;
3176}
3177
3178void AudioFlinger::PlaybackThread::threadLoop_drain()
3179{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003180 bool supportsDrain = false;
3181 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003182 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3183 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003184 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3185 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003186 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003187 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003188 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003189 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003190 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003191 }
3192}
3193
3194void AudioFlinger::PlaybackThread::threadLoop_exit()
3195{
Eric Laurent275e8e92014-11-30 15:14:47 -08003196 {
3197 Mutex::Autolock _l(mLock);
3198 for (size_t i = 0; i < mTracks.size(); i++) {
3199 sp<Track> track = mTracks[i];
3200 track->invalidate();
3201 }
Andy Hungdae27702016-10-31 14:01:16 -07003202 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3203 // After we exit there are no more track changes sent to BatteryNotifier
3204 // because that requires an active threadLoop.
3205 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3206 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003207 }
Eric Laurent81784c32012-11-19 14:55:58 -08003208}
3209
3210/*
3211The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003212 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003213 - mActiveSleepTimeUs from activeSleepTimeUs()
3214 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003215 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3216 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003217 - maxPeriod from frame count and sample rate (MIXER only)
3218
3219The parameters that affect these derived values are:
3220 - frame count
3221 - frame size
3222 - sample rate
3223 - device type: A2DP or not
3224 - device latency
3225 - format: PCM or not
3226 - active sleep time
3227 - idle sleep time
3228*/
3229
3230void AudioFlinger::PlaybackThread::cacheParameters_l()
3231{
Andy Hung25c2dac2014-02-27 14:56:00 -08003232 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003233 mActiveSleepTimeUs = activeSleepTimeUs();
3234 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003235
3236 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3237 // truncating audio when going to standby.
3238 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabin10d86fd2019-10-31 17:20:42 -07003239 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003240 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3241 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3242 }
3243 }
Eric Laurent81784c32012-11-19 14:55:58 -08003244}
3245
Eric Laurent13084622016-05-17 10:51:49 -07003246bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003247{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003248 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003249 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003250 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003251 size_t size = mTracks.size();
3252 for (size_t i = 0; i < size; i++) {
3253 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003254 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003255 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003256 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003257 }
3258 }
Eric Laurent13084622016-05-17 10:51:49 -07003259 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003260}
3261
Haynes Mathew George05317d22016-05-03 16:34:26 -07003262void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3263{
3264 Mutex::Autolock _l(mLock);
3265 invalidateTracks_l(streamType);
3266}
3267
Eric Laurent81784c32012-11-19 14:55:58 -08003268status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3269{
Glenn Kastend848eb42016-03-08 13:42:11 -08003270 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003271 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003272 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003273 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3274 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3275 &halInBuffer);
3276 if (result != OK) return result;
3277 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003278 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003279 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurenta20c4e92019-11-12 15:55:51 -08003280 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003281 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003282 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003283 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003284 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003285 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003286 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003287 &halInBuffer);
3288 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003289#ifdef FLOAT_EFFECT_CHAIN
3290 buffer = halInBuffer->audioBuffer()->f32;
3291#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003292 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003293#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003294 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3295 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003296 }
3297
3298 // Attach all tracks with same session ID to this chain.
3299 for (size_t i = 0; i < mTracks.size(); ++i) {
3300 sp<Track> track = mTracks[i];
3301 if (session == track->sessionId()) {
3302 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3303 buffer);
3304 track->setMainBuffer(buffer);
3305 chain->incTrackCnt();
3306 }
3307 }
3308
3309 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003310 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003311 if (session == track->sessionId()) {
3312 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3313 chain->incActiveTrackCnt();
3314 }
3315 }
3316 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003317 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003318 chain->setInBuffer(halInBuffer);
3319 chain->setOutBuffer(halOutBuffer);
Eric Laurenta20c4e92019-11-12 15:55:51 -08003320 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3321 // chains list in order to be processed last as it contains output device effects.
3322 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3323 // processing effects specific to an output stream before effects applied to all streams
3324 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003325 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3326 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003327 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003328 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003329 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003330 // Effect chain for other sessions are inserted at beginning of effect
3331 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003332 // sessions is not important.
3333 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurenta20c4e92019-11-12 15:55:51 -08003334 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3335 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003336 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003337 size_t size = mEffectChains.size();
3338 size_t i = 0;
3339 for (i = 0; i < size; i++) {
3340 if (mEffectChains[i]->sessionId() < session) {
3341 break;
3342 }
3343 }
3344 mEffectChains.insertAt(chain, i);
3345 checkSuspendOnAddEffectChain_l(chain);
3346
3347 return NO_ERROR;
3348}
3349
3350size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3351{
Glenn Kastend848eb42016-03-08 13:42:11 -08003352 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003353
3354 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3355
3356 for (size_t i = 0; i < mEffectChains.size(); i++) {
3357 if (chain == mEffectChains[i]) {
3358 mEffectChains.removeAt(i);
3359 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003360 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003361 if (session == track->sessionId()) {
3362 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3363 chain.get(), session);
3364 chain->decActiveTrackCnt();
3365 }
3366 }
3367
3368 // detach all tracks with same session ID from this chain
3369 for (size_t i = 0; i < mTracks.size(); ++i) {
3370 sp<Track> track = mTracks[i];
3371 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003372 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003373 chain->decTrackCnt();
3374 }
3375 }
3376 break;
3377 }
3378 }
3379 return mEffectChains.size();
3380}
3381
3382status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003383 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003384{
3385 Mutex::Autolock _l(mLock);
3386 return attachAuxEffect_l(track, EffectId);
3387}
3388
3389status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003390 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003391{
3392 status_t status = NO_ERROR;
3393
3394 if (EffectId == 0) {
3395 track->setAuxBuffer(0, NULL);
3396 } else {
3397 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3398 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3399 if (effect != 0) {
3400 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3401 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3402 } else {
3403 status = INVALID_OPERATION;
3404 }
3405 } else {
3406 status = BAD_VALUE;
3407 }
3408 }
3409 return status;
3410}
3411
3412void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3413{
3414 for (size_t i = 0; i < mTracks.size(); ++i) {
3415 sp<Track> track = mTracks[i];
3416 if (track->auxEffectId() == effectId) {
3417 attachAuxEffect_l(track, 0);
3418 }
3419 }
3420}
3421
3422bool AudioFlinger::PlaybackThread::threadLoop()
3423{
Glenn Kasten388d5712017-04-07 14:38:41 -07003424 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003425
Eric Laurent81784c32012-11-19 14:55:58 -08003426 Vector< sp<Track> > tracksToRemove;
3427
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003428 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003429 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003430
3431 // MIXER
3432 nsecs_t lastWarning = 0;
3433
3434 // DUPLICATING
3435 // FIXME could this be made local to while loop?
3436 writeFrames = 0;
3437
3438 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003439 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003440
3441 if (mType == MIXER) {
3442 sleepTimeShift = 0;
3443 }
3444
3445 CpuStats cpuStats;
3446 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3447
3448 acquireWakeLock();
3449
Glenn Kasteneef598c2017-04-03 14:41:13 -07003450 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3451 // thread associated with this PlaybackThread.
3452 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3453 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003454 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3455 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003456 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003457 const char *logString = NULL;
3458
rago1bb90822017-05-02 18:31:48 -07003459 // Estimated time for next buffer to be written to hal. This is used only on
3460 // suspended mode (for now) to help schedule the wait time until next iteration.
3461 nsecs_t timeLoopNextNs = 0;
3462
Eric Laurent664539d2013-09-23 18:24:31 -07003463 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003464
Andy Hung2dbffc22018-08-08 18:50:41 -07003465 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003466
Andy Hung446f4df2019-02-21 12:26:41 -08003467 // loopCount is used for statistics and diagnostics.
3468 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003469 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003470 // Log merge requests are performed during AudioFlinger binder transactions, but
3471 // that does not cover audio playback. It's requested here for that reason.
3472 mAudioFlinger->requestLogMerge();
3473
Eric Laurent81784c32012-11-19 14:55:58 -08003474 cpuStats.sample(myName);
3475
3476 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003477 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003478 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003479
Andy Hung2dbffc22018-08-08 18:50:41 -07003480 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3481 //
jiabin10d86fd2019-10-31 17:20:42 -07003482 // Note: we access outDeviceTypes() outside of mLock.
3483 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003484 // Here, we try for the AF lock, but do not block on it as the latency
3485 // is more informational.
3486 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3487 std::vector<PatchPanel::SoftwarePatch> swPatches;
3488 double latencyMs;
3489 status_t status = INVALID_OPERATION;
3490 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3491 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3492 && swPatches.size() > 0) {
3493 status = swPatches[0].getLatencyMs_l(&latencyMs);
3494 downstreamPatchHandle = swPatches[0].getPatchHandle();
3495 }
3496 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003497 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003498 lastDownstreamPatchHandle = downstreamPatchHandle;
3499 }
3500 if (status == OK) {
3501 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003502 // latency of 5 seconds).
3503 const double minLatency = 0., maxLatency = 5000.;
3504 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003505 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003506 } else {
3507 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003508 if (latencyMs < minLatency) latencyMs = minLatency;
3509 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003510 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003511 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003512 }
3513 mAudioFlinger->mLock.unlock();
3514 }
3515 } else {
3516 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3517 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003518 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003519 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3520 }
3521 }
3522
Eric Laurent81784c32012-11-19 14:55:58 -08003523 { // scope for mLock
3524
3525 Mutex::Autolock _l(mLock);
3526
Eric Laurent021cf962014-05-13 10:18:14 -07003527 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003528
Glenn Kasteneef598c2017-04-03 14:41:13 -07003529 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003530 if (logString != NULL) {
3531 mNBLogWriter->logTimestamp();
3532 mNBLogWriter->log(logString);
3533 logString = NULL;
3534 }
3535
Dean Wheatley12473e92021-03-18 23:00:55 +11003536 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003537
Eric Laurent81784c32012-11-19 14:55:58 -08003538 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003539 if (mSignalPending) {
3540 // A signal was raised while we were unlocked
3541 mSignalPending = false;
3542 } else if (waitingAsyncCallback_l()) {
3543 if (exitPending()) {
3544 break;
3545 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003546 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003547 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003548 releaseWakeLock_l();
3549 released = true;
3550 }
Andy Hung10cbff12017-02-21 17:30:14 -08003551
3552 const int64_t waitNs = computeWaitTimeNs_l();
3553 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3554 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3555 if (status == TIMED_OUT) {
3556 mSignalPending = true; // if timeout recheck everything
3557 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003558 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003559 if (released) {
3560 acquireWakeLock_l();
3561 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003562 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3563 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003564
3565 continue;
3566 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003567 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003568 isSuspended()) {
3569 // put audio hardware into standby after short delay
3570 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003571
3572 threadLoop_standby();
3573
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003574 // This is where we go into standby
3575 if (!mStandby) {
3576 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003577 mThreadMetrics.logEndInterval();
3578 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003579 }
Andy Hungd0979812019-02-21 15:51:44 -08003580 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003581 }
3582
Eric Tan39ec8d62018-07-24 09:49:29 -07003583 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003584 // we're about to wait, flush the binder command buffer
3585 IPCThreadState::self()->flushCommands();
3586
3587 clearOutputTracks();
3588
3589 if (exitPending()) {
3590 break;
3591 }
3592
3593 releaseWakeLock_l();
3594 // wait until we have something to do...
3595 ALOGV("%s going to sleep", myName.string());
3596 mWaitWorkCV.wait(mLock);
3597 ALOGV("%s waking up", myName.string());
3598 acquireWakeLock_l();
3599
3600 mMixerStatus = MIXER_IDLE;
3601 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3602 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003603 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003604 checkSilentMode_l();
3605
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003606 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3607 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003608 if (mType == MIXER) {
3609 sleepTimeShift = 0;
3610 }
3611
3612 continue;
3613 }
3614 }
Eric Laurent81784c32012-11-19 14:55:58 -08003615 // mMixerStatusIgnoringFastTracks is also updated internally
3616 mMixerStatus = prepareTracks_l(&tracksToRemove);
3617
Andy Hungdae27702016-10-31 14:01:16 -07003618 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003619
Kevin Rocard069c2712018-03-29 19:09:14 -07003620 updateMetadata_l();
3621
Eric Laurent81784c32012-11-19 14:55:58 -08003622 // prevent any changes in effect chain list and in each effect chain
3623 // during mixing and effect process as the audio buffers could be deleted
3624 // or modified if an effect is created or deleted
3625 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003626
3627 // Determine which session to pick up haptic data.
3628 // This must be done under the same lock as prepareTracks_l().
3629 // TODO: Write haptic data directly to sink buffer when mixing.
3630 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3631 for (const auto& track : mActiveTracks) {
3632 if (track->getHapticPlaybackEnabled()) {
3633 activeHapticSessionId = track->sessionId();
3634 break;
3635 }
3636 }
3637 }
3638
Andy Hungc1646382019-04-30 16:12:10 -07003639 // Acquire a local copy of active tracks with lock (release w/o lock).
3640 //
3641 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3642 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3643 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3644 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003645 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003646
Eric Laurentbfb1b832013-01-07 09:53:42 -08003647 if (mBytesRemaining == 0) {
3648 mCurrentWriteLength = 0;
3649 if (mMixerStatus == MIXER_TRACKS_READY) {
3650 // threadLoop_mix() sets mCurrentWriteLength
3651 threadLoop_mix();
3652 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3653 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003654 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003655 // must be written to HAL
3656 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003657 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003658 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003659
3660 // Tally underrun frames as we are inserting 0s here.
3661 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003662 if (track->mFillingUpStatus == Track::FS_ACTIVE
3663 && !track->isStopped()
3664 && !track->isPaused()
3665 && !track->isTerminated()) {
3666 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3667 __func__, track->id(), track->getTrackStateAsString(),
3668 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003669 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3670 }
3671 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003672 }
3673 }
Andy Hung98ef9782014-03-04 14:46:50 -08003674 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003675 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003676 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3677 // or mSinkBuffer (if there are no effects).
3678 //
3679 // This is done pre-effects computation; if effects change to
3680 // support higher precision, this needs to move.
3681 //
3682 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003683 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003684 if (mMixerBufferValid) {
3685 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3686 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3687
Andy Hung2ddee192015-12-18 17:34:44 -08003688 // mono blend occurs for mixer threads only (not direct or offloaded)
3689 // and is handled here if we're going directly to the sink.
3690 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003691 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3692 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003693 }
3694
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003695 if (!hasFastMixer()) {
3696 // Balance must take effect after mono conversion.
3697 // We do it here if there is no FastMixer.
3698 // mBalance detects zero balance within the class for speed (not needed here).
3699 mBalance.setBalance(mMasterBalance.load());
3700 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3701 }
3702
Andy Hung98ef9782014-03-04 14:46:50 -08003703 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003704 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3705
3706 // If we're going directly to the sink and there are haptic channels,
3707 // we should adjust channels as the sample data is partially interleaved
3708 // in this case.
3709 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3710 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3711 mChannelCount + mHapticChannelCount,
3712 audio_bytes_per_sample(format),
3713 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3714 }
Andy Hung98ef9782014-03-04 14:46:50 -08003715 }
3716
Eric Laurentbfb1b832013-01-07 09:53:42 -08003717 mBytesRemaining = mCurrentWriteLength;
3718 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003719 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3720 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3721 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3722 mBytesWritten += mBytesRemaining;
3723 mFramesWritten += framesRemaining;
3724 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003725 mBytesRemaining = 0;
3726 }
Eric Laurent81784c32012-11-19 14:55:58 -08003727
Eric Laurentbfb1b832013-01-07 09:53:42 -08003728 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003729 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003730 for (size_t i = 0; i < effectChains.size(); i ++) {
3731 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003732 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003733 if (activeHapticSessionId != AUDIO_SESSION_NONE
3734 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003735 // Haptic data is active in this case, copy it directly from
3736 // in buffer to out buffer.
3737 const size_t audioBufferSize = mNormalFrameCount
3738 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3739 memcpy_by_audio_format(
3740 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3741 EFFECT_BUFFER_FORMAT,
3742 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3743 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3744 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003745 }
Eric Laurent81784c32012-11-19 14:55:58 -08003746 }
3747 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003748 // Process effect chains for offloaded thread even if no audio
3749 // was read from audio track: process only updates effect state
3750 // and thus does have to be synchronized with audio writes but may have
3751 // to be called while waiting for async write callback
3752 if (mType == OFFLOAD) {
3753 for (size_t i = 0; i < effectChains.size(); i ++) {
3754 effectChains[i]->process_l();
3755 }
3756 }
Eric Laurent81784c32012-11-19 14:55:58 -08003757
Andy Hung98ef9782014-03-04 14:46:50 -08003758 // Only if the Effects buffer is enabled and there is data in the
3759 // Effects buffer (buffer valid), we need to
3760 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003761 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003762 if (mEffectBufferValid) {
3763 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003764
3765 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003766 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3767 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003768 }
3769
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003770 if (!hasFastMixer()) {
3771 // Balance must take effect after mono conversion.
3772 // We do it here if there is no FastMixer.
3773 // mBalance detects zero balance within the class for speed (not needed here).
3774 mBalance.setBalance(mMasterBalance.load());
3775 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3776 }
3777
Andy Hung98ef9782014-03-04 14:46:50 -08003778 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003779 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3780 // The sample data is partially interleaved when haptic channels exist,
3781 // we need to adjust channels here.
3782 if (mHapticChannelCount > 0) {
3783 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3784 mChannelCount + mHapticChannelCount,
3785 audio_bytes_per_sample(mFormat),
3786 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3787 }
Andy Hung98ef9782014-03-04 14:46:50 -08003788 }
3789
Eric Laurent81784c32012-11-19 14:55:58 -08003790 // enable changes in effect chain
3791 unlockEffectChains(effectChains);
3792
Eric Laurentbfb1b832013-01-07 09:53:42 -08003793 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003794 // mSleepTimeUs == 0 means we must write to audio hardware
3795 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003796 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003797 // writePeriodNs is updated >= 0 when ret > 0.
3798 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003799 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003800 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003801 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003802 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003803 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003804 if (ret < 0) {
3805 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003806 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003807 mBytesWritten += ret;
3808 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003809 const int64_t frames = ret / mFrameSize;
3810 mFramesWritten += frames;
3811
3812 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3813 // process information relating to write time.
3814 if (audio_has_proportional_frames(mFormat)) {
3815 // we are in a continuous mixing cycle
3816 if (mMixerStatus == MIXER_TRACKS_READY &&
3817 loopCount == lastLoopCountWritten + 1) {
3818
3819 const double jitterMs =
3820 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3821 {frames, writePeriodNs},
3822 {0, 0} /* lastTimestamp */, mSampleRate);
3823 const double processMs =
3824 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3825
3826 Mutex::Autolock _l(mLock);
3827 mIoJitterMs.add(jitterMs);
3828 mProcessTimeMs.add(processMs);
3829 }
3830
3831 // write blocked detection
3832 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3833 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3834 mNumDelayedWrites++;
3835 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3836 ATRACE_NAME("underrun");
3837 ALOGW("write blocked for %lld msecs, "
3838 "%d delayed writes, thread %d",
3839 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3840 mNumDelayedWrites, mId);
3841 lastWarning = lastIoEndNs;
3842 }
3843 }
3844 }
3845 // update timing info.
3846 mLastIoBeginNs = lastIoBeginNs;
3847 mLastIoEndNs = lastIoEndNs;
3848 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003849 }
3850 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3851 (mMixerStatus == MIXER_DRAIN_ALL)) {
3852 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003853 }
Andy Hung08fb1742015-05-31 23:22:10 -07003854 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003855
3856 if (mThreadThrottle
3857 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003858 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003859 // Limit MixerThread data processing to no more than twice the
3860 // expected processing rate.
3861 //
3862 // This helps prevent underruns with NuPlayer and other applications
3863 // which may set up buffers that are close to the minimum size, or use
3864 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3865 //
3866 // The throttle smooths out sudden large data drains from the device,
3867 // e.g. when it comes out of standby, which often causes problems with
3868 // (1) mixer threads without a fast mixer (which has its own warm-up)
3869 // (2) minimum buffer sized tracks (even if the track is full,
3870 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003871 //
3872 // Total time spent in last processing cycle equals time spent in
3873 // 1. threadLoop_write, as well as time spent in
3874 // 2. threadLoop_mix (significant for heavy mixing, especially
3875 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003876
Andy Hung446f4df2019-02-21 12:26:41 -08003877 // it's OK if deltaMs is an overestimate.
3878
3879 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003880
Ivan Lozanoea04d392017-11-07 14:37:07 -08003881 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003882 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07003883 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08003884
Andy Hung08fb1742015-05-31 23:22:10 -07003885 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003886 // notify of throttle start on verbose log
3887 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3888 "mixer(%p) throttle begin:"
3889 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003890 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003891 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003892 // Throttle must be attributed to the previous mixer loop's write time
3893 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003894 // This also ensures proper timing statistics.
3895 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003896 } else {
3897 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3898 if (diff > 0) {
3899 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003900 // but prevent spamming for bluetooth
jiabin10d86fd2019-10-31 17:20:42 -07003901 ALOGD_IF(!isSingleDeviceType(
3902 outDeviceTypes(), audio_is_a2dp_out_device) &&
3903 !isSingleDeviceType(
3904 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003905 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003906 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3907 }
Andy Hung08fb1742015-05-31 23:22:10 -07003908 }
3909 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003910 }
Eric Laurent81784c32012-11-19 14:55:58 -08003911
Eric Laurentbfb1b832013-01-07 09:53:42 -08003912 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003913 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003914 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003915 // suspended requires accurate metering of sleep time.
3916 if (isSuspended()) {
3917 // advance by expected sleepTime
3918 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3919 const nsecs_t nowNs = systemTime();
3920
3921 // compute expected next time vs current time.
3922 // (negative deltas are treated as delays).
3923 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3924 if (deltaNs < -kMaxNextBufferDelayNs) {
3925 // Delays longer than the max allowed trigger a reset.
3926 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3927 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3928 timeLoopNextNs = nowNs + deltaNs;
3929 } else if (deltaNs < 0) {
3930 // Delays within the max delay allowed: zero the delta/sleepTime
3931 // to help the system catch up in the next iteration(s)
3932 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3933 deltaNs = 0;
3934 }
3935 // update sleep time (which is >= 0)
3936 mSleepTimeUs = deltaNs / 1000;
3937 }
Eric Laurente93cc032016-05-05 10:15:10 -07003938 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3939 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003940 }
Glenn Kastene7754022014-10-31 12:11:26 -07003941 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003942 }
Eric Laurent81784c32012-11-19 14:55:58 -08003943 }
3944
3945 // Finally let go of removed track(s), without the lock held
3946 // since we can't guarantee the destructors won't acquire that
3947 // same lock. This will also mutate and push a new fast mixer state.
3948 threadLoop_removeTracks(tracksToRemove);
3949 tracksToRemove.clear();
3950
3951 // FIXME I don't understand the need for this here;
3952 // it was in the original code but maybe the
3953 // assignment in saveOutputTracks() makes this unnecessary?
3954 clearOutputTracks();
3955
3956 // Effect chains will be actually deleted here if they were removed from
3957 // mEffectChains list during mixing or effects processing
3958 effectChains.clear();
3959
3960 // FIXME Note that the above .clear() is no longer necessary since effectChains
3961 // is now local to this block, but will keep it for now (at least until merge done).
3962 }
3963
Eric Laurentbfb1b832013-01-07 09:53:42 -08003964 threadLoop_exit();
3965
Eric Laurentcf817a22014-08-04 20:36:31 -07003966 if (!mStandby) {
3967 threadLoop_standby();
3968 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003969 }
3970
3971 releaseWakeLock();
3972
3973 ALOGV("Thread %p type %d exiting", this, mType);
3974 return false;
3975}
3976
Dean Wheatley12473e92021-03-18 23:00:55 +11003977void AudioFlinger::PlaybackThread::collectTimestamps_l()
3978{
3979 // Collect timestamp statistics for the Playback Thread types that support it.
3980 if (mType != MIXER
3981 && mType != DUPLICATING
3982 && mType != DIRECT
3983 && mType != OFFLOAD) {
3984 return;
3985 }
3986 if (mStandby) {
3987 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
3988 return;
3989 } else if (mHwPaused) {
3990 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
3991 return;
3992 }
3993
3994 // Gather the framesReleased counters for all active tracks,
3995 // and associate with the sink frames written out. We need
3996 // this to convert the sink timestamp to the track timestamp.
3997 bool kernelLocationUpdate = false;
3998 ExtendedTimestamp timestamp; // use private copy to fetch
3999
4000 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4001 // HAL may be draining some small duration buffered data for fade out.
4002 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4003 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4004 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4005 mSampleRate);
4006
4007 if (isTimestampCorrectionEnabled()) {
4008 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4009 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4010 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4011 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4012 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4013 = correctedTimestamp.mFrames;
4014 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4015 = correctedTimestamp.mTimeNs;
4016 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4017 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4018 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4019
4020 // Note: Downstream latency only added if timestamp correction enabled.
4021 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4022 const int64_t newPosition =
4023 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4024 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4025 // prevent retrograde
4026 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4027 newPosition,
4028 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4029 - mSuspendedFrames));
4030 }
4031 }
4032
4033 // We always fetch the timestamp here because often the downstream
4034 // sink will block while writing.
4035
4036 // We keep track of the last valid kernel position in case we are in underrun
4037 // and the normal mixer period is the same as the fast mixer period, or there
4038 // is some error from the HAL.
4039 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4040 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4041 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4042 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4043 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4044
4045 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4046 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4047 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4048 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4049 }
4050
4051 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4052 kernelLocationUpdate = true;
4053 } else {
4054 ALOGVV("getTimestamp error - no valid kernel position");
4055 }
4056
4057 // copy over kernel info
4058 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4059 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4060 + mSuspendedFrames; // add frames discarded when suspended
4061 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4062 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4063 } else {
4064 mTimestampVerifier.error();
4065 }
4066
4067 // mFramesWritten for non-offloaded tracks are contiguous
4068 // even after standby() is called. This is useful for the track frame
4069 // to sink frame mapping.
4070 bool serverLocationUpdate = false;
4071 if (mFramesWritten != mLastFramesWritten) {
4072 serverLocationUpdate = true;
4073 mLastFramesWritten = mFramesWritten;
4074 }
4075 // Only update timestamps if there is a meaningful change.
4076 // Either the kernel timestamp must be valid or we have written something.
4077 if (kernelLocationUpdate || serverLocationUpdate) {
4078 if (serverLocationUpdate) {
4079 // use the time before we called the HAL write - it is a bit more accurate
4080 // to when the server last read data than the current time here.
4081 //
4082 // If we haven't written anything, mLastIoBeginNs will be -1
4083 // and we use systemTime().
4084 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4085 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4086 ? systemTime() : mLastIoBeginNs;
4087 }
4088
4089 for (const sp<Track> &t : mActiveTracks) {
4090 if (!t->isFastTrack()) {
4091 t->updateTrackFrameInfo(
4092 t->mAudioTrackServerProxy->framesReleased(),
4093 mFramesWritten,
4094 mSampleRate,
4095 mTimestamp);
4096 }
4097 }
4098 }
4099
4100 if (audio_has_proportional_frames(mFormat)) {
4101 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4102 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4103 mLatencyMs.add(latencyMs);
4104 }
4105 }
4106#if 0
4107 // logFormat example
4108 if (z % 100 == 0) {
4109 timespec ts;
4110 clock_gettime(CLOCK_MONOTONIC, &ts);
4111 LOGT("This is an integer %d, this is a float %f, this is my "
4112 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4113 LOGT("A deceptive null-terminated string %\0");
4114 }
4115 ++z;
4116#endif
4117}
4118
Eric Laurentbfb1b832013-01-07 09:53:42 -08004119// removeTracks_l() must be called with ThreadBase::mLock held
4120void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4121{
Andy Hungfe726a62018-09-27 15:17:25 -07004122 for (const auto& track : tracksToRemove) {
4123 mActiveTracks.remove(track);
4124 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4125 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4126 if (chain != 0) {
4127 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4128 __func__, track->id(), chain.get(), track->sessionId());
4129 chain->decActiveTrackCnt();
4130 }
4131 // If an external client track, inform APM we're no longer active, and remove if needed.
4132 // We do this under lock so that the state is consistent if the Track is destroyed.
4133 if (track->isExternalTrack()) {
4134 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004135 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004136 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004137 }
4138 }
Andy Hungfe726a62018-09-27 15:17:25 -07004139 if (track->isTerminated()) {
4140 // remove from our tracks vector
4141 removeTrack_l(track);
4142 }
jiabin57303cc2018-12-18 15:45:57 -08004143 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4144 && mHapticChannelCount > 0) {
4145 mLock.unlock();
4146 // Unlock due to VibratorService will lock for this call and will
4147 // call Tracks.mute/unmute which also require thread's lock.
4148 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4149 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08004150 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004151 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004152}
Eric Laurent81784c32012-11-19 14:55:58 -08004153
Eric Laurentaccc1472013-09-20 09:36:34 -07004154status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4155{
4156 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004157 ExtendedTimestamp ets;
4158 status_t status = mNormalSink->getTimestamp(ets);
4159 if (status == NO_ERROR) {
4160 status = ets.getBestTimestamp(&timestamp);
4161 }
4162 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004163 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004164 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004165 collectTimestamps_l();
4166 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4167 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004168 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004169 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4170 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4171 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4172 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4173 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004174 }
4175 return INVALID_OPERATION;
4176}
Eric Laurent1c333e22014-05-20 10:48:17 -07004177
Eric Laurenteab90452019-06-24 15:17:46 -07004178// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4179// still applied by the mixer.
4180// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4181// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4182// if more than one track are active
4183status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4184{
4185 status_t result = NO_ERROR;
4186 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4187 if (*volume != mLeftVolFloat) {
4188 result = mOutput->stream->setVolume(*volume, *volume);
4189 ALOGE_IF(result != OK,
4190 "Error when setting output stream volume: %d", result);
4191 if (result == NO_ERROR) {
4192 mLeftVolFloat = *volume;
4193 }
4194 }
4195 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4196 // remove stream volume contribution from software volume.
4197 if (mLeftVolFloat == *volume) {
4198 *volume = 1.0f;
4199 }
4200 }
4201 return result;
4202}
4203
Eric Laurent054d9d32015-04-24 08:48:48 -07004204status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4205 audio_patch_handle_t *handle)
4206{
Andy Hungf60abce2016-08-26 11:37:54 -07004207 status_t status;
4208 if (property_get_bool("af.patch_park", false /* default_value */)) {
4209 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4210 // or if HAL does not properly lock against access.
4211 AutoPark<FastMixer> park(mFastMixer);
4212 status = PlaybackThread::createAudioPatch_l(patch, handle);
4213 } else {
4214 status = PlaybackThread::createAudioPatch_l(patch, handle);
4215 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004216 return status;
4217}
4218
Eric Laurent1c333e22014-05-20 10:48:17 -07004219status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4220 audio_patch_handle_t *handle)
4221{
4222 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004223
4224 // store new device and send to effects
4225 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabin10d86fd2019-10-31 17:20:42 -07004226 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004227 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabin10d86fd2019-10-31 17:20:42 -07004228 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4229 && !mOutput->audioHwDev->supportsAudioPatches(),
4230 "Enumerated device type(%#x) must not be used "
4231 "as it does not support audio patches",
4232 patch->sinks[i].ext.device.type);
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07004233 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabin10d86fd2019-10-31 17:20:42 -07004234 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4235 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004236 }
4237
François Gaffie0c280aa2018-07-25 10:02:15 +02004238 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004239#ifdef ADD_BATTERY_DATA
4240 // when changing the audio output device, call addBatteryData to notify
4241 // the change
jiabin10d86fd2019-10-31 17:20:42 -07004242 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004243 uint32_t params = 0;
4244 // check whether speaker is on
jiabin10d86fd2019-10-31 17:20:42 -07004245 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004246 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004247 }
4248
Eric Laurent054d9d32015-04-24 08:48:48 -07004249 // check if any other device (except speaker) is on
jiabin10d86fd2019-10-31 17:20:42 -07004250 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004251 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4252 }
4253
4254 if (params != 0) {
4255 addBatteryData(params);
4256 }
4257 }
4258#endif
4259
4260 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08004261 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004262 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004263
jiabin10d86fd2019-10-31 17:20:42 -07004264 // mPatch.num_sinks is not set when the thread is created so that
4265 // the first patch creation triggers an ioConfigChanged callback
4266 bool configChanged = (mPatch.num_sinks == 0) ||
4267 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004268 mPatch = *patch;
jiabin10d86fd2019-10-31 17:20:42 -07004269 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004270 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004271
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004272 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004273 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4274 status = hwDevice->createAudioPatch(patch->num_sources,
4275 patch->sources,
4276 patch->num_sinks,
4277 patch->sinks,
4278 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004279 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004280 char *address;
4281 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4282 //FIXME: we only support address on first sink with HAL version < 3.0
4283 address = audio_device_address_to_parameter(
4284 patch->sinks[0].ext.device.type,
4285 patch->sinks[0].ext.device.address);
4286 } else {
4287 address = (char *)calloc(1, 1);
4288 }
4289 AudioParameter param = AudioParameter(String8(address));
4290 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004291 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004292 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004293 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004294 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004295 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004296
4297 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004298 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004299 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004300 // also dispatch to active AudioTracks for MediaMetrics
4301 for (const auto &track : mActiveTracks) {
4302 track->logEndInterval();
4303 track->logBeginInterval(patchSinksAsString);
4304 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004305
Eric Laurente8726fe2015-06-26 09:39:24 -07004306 if (configChanged) {
4307 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4308 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004309 return status;
4310}
4311
Eric Laurent054d9d32015-04-24 08:48:48 -07004312status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4313{
Andy Hungf60abce2016-08-26 11:37:54 -07004314 status_t status;
4315 if (property_get_bool("af.patch_park", false /* default_value */)) {
4316 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4317 // or if HAL does not properly lock against access.
4318 AutoPark<FastMixer> park(mFastMixer);
4319 status = PlaybackThread::releaseAudioPatch_l(handle);
4320 } else {
4321 status = PlaybackThread::releaseAudioPatch_l(handle);
4322 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004323 return status;
4324}
4325
Eric Laurent1c333e22014-05-20 10:48:17 -07004326status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4327{
4328 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004329
jiabin10d86fd2019-10-31 17:20:42 -07004330 mPatch = audio_patch{};
4331 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004332
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004333 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004334 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4335 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004336 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004337 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004338 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004339 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004340 }
4341 return status;
4342}
4343
Eric Laurent83b88082014-06-20 18:31:16 -07004344void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4345{
4346 Mutex::Autolock _l(mLock);
4347 mTracks.add(track);
4348}
4349
4350void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4351{
4352 Mutex::Autolock _l(mLock);
4353 destroyTrack_l(track);
4354}
4355
Mikhail Naganovdc769682018-05-04 15:34:08 -07004356void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004357{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004358 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004359 config->role = AUDIO_PORT_ROLE_SOURCE;
4360 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4361 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004362 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4363 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4364 config->flags.output = mOutput->flags;
4365 }
Eric Laurent83b88082014-06-20 18:31:16 -07004366}
4367
Eric Laurent81784c32012-11-19 14:55:58 -08004368// ----------------------------------------------------------------------------
4369
4370AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabin10d86fd2019-10-31 17:20:42 -07004371 audio_io_handle_t id, bool systemReady, type_t type)
4372 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004373 // mAudioMixer below
4374 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004375 mFastMixerFutex(0),
4376 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004377 // mOutputSink below
4378 // mPipeSink below
4379 // mNormalSink below
4380{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004381 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabin10d86fd2019-10-31 17:20:42 -07004382 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004383 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004384 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004385 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4386 mNormalFrameCount);
4387 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4388
Andy Hungfbfc3952015-01-15 13:33:51 -08004389 if (type == DUPLICATING) {
4390 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4391 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4392 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4393 return;
4394 }
Eric Laurent81784c32012-11-19 14:55:58 -08004395 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004396 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004397 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004398 const NBAIO_Format offers[1] = {Format_from_SR_C(
4399 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004400#if !LOG_NDEBUG
4401 ssize_t index =
4402#else
4403 (void)
4404#endif
4405 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004406 ALOG_ASSERT(index == 0);
4407
4408 // initialize fast mixer depending on configuration
4409 bool initFastMixer;
4410 switch (kUseFastMixer) {
4411 case FastMixer_Never:
4412 initFastMixer = false;
4413 break;
4414 case FastMixer_Always:
4415 initFastMixer = true;
4416 break;
4417 case FastMixer_Static:
4418 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004419 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4420 // where the period is less than an experimentally determined threshold that can be
4421 // scheduled reliably with CFS. However, the BT A2DP HAL is
4422 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4423 initFastMixer = mFrameCount < mNormalFrameCount
jiabin10d86fd2019-10-31 17:20:42 -07004424 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004425 break;
4426 }
Andy Hungfda69402017-02-15 14:33:12 -08004427 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4428 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4429 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004430 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004431 audio_format_t fastMixerFormat;
4432 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4433 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4434 } else {
4435 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4436 }
4437 if (mFormat != fastMixerFormat) {
4438 // change our Sink format to accept our intermediate precision
4439 mFormat = fastMixerFormat;
4440 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004441 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004442 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4443 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4444 }
Eric Laurent81784c32012-11-19 14:55:58 -08004445
4446 // create a MonoPipe to connect our submix to FastMixer
4447 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004448
Andy Hung1258c1a2014-05-23 21:22:17 -07004449 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004450 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004451 format.mFormat = fastMixerFormat;
4452 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4453
Eric Laurent81784c32012-11-19 14:55:58 -08004454 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4455 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4456 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4457 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4458 const NBAIO_Format offers[1] = {format};
4459 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004460#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004461 ssize_t index =
4462#else
4463 (void)
4464#endif
4465 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004466 ALOG_ASSERT(index == 0);
4467 monoPipe->setAvgFrames((mScreenState & 1) ?
4468 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4469 mPipeSink = monoPipe;
4470
Eric Laurent81784c32012-11-19 14:55:58 -08004471 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004472 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004473 FastMixerStateQueue *sq = mFastMixer->sq();
4474#ifdef STATE_QUEUE_DUMP
4475 sq->setObserverDump(&mStateQueueObserverDump);
4476 sq->setMutatorDump(&mStateQueueMutatorDump);
4477#endif
4478 FastMixerState *state = sq->begin();
4479 FastTrack *fastTrack = &state->mFastTracks[0];
4480 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4481 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4482 fastTrack->mVolumeProvider = NULL;
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07004483 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4484 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4485 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004486 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004487 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabin84114c32019-04-10 16:38:07 -07004488 fastTrack->mHapticIntensity = AudioMixer::HAPTIC_SCALE_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004489 fastTrack->mGeneration++;
4490 state->mFastTracksGen++;
4491 state->mTrackMask = 1;
4492 // fast mixer will use the HAL output sink
4493 state->mOutputSink = mOutputSink.get();
4494 state->mOutputSinkGen++;
4495 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004496 // specify sink channel mask when haptic channel mask present as it can not
4497 // be calculated directly from channel count
4498 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07004499 ? AUDIO_CHANNEL_NONE
4500 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004501 state->mCommand = FastMixerState::COLD_IDLE;
4502 // already done in constructor initialization list
4503 //mFastMixerFutex = 0;
4504 state->mColdFutexAddr = &mFastMixerFutex;
4505 state->mColdGen++;
4506 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004507 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4508 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004509 sq->end();
4510 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4511
Eric Tan0513b5d2018-09-17 10:32:48 -07004512 NBLog::thread_info_t info;
4513 info.id = mId;
4514 info.type = NBLog::FASTMIXER;
4515 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4516
Eric Laurent81784c32012-11-19 14:55:58 -08004517 // start the fast mixer
4518 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4519 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004520 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004521 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004522
4523#ifdef AUDIO_WATCHDOG
4524 // create and start the watchdog
4525 mAudioWatchdog = new AudioWatchdog();
4526 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4527 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4528 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004529 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004530#endif
Andy Hung8946a282018-04-19 20:04:56 -07004531 } else {
4532#ifdef TEE_SINK
4533 // Only use the MixerThread tee if there is no FastMixer.
4534 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4535 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4536#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004537 }
4538
4539 switch (kUseFastMixer) {
4540 case FastMixer_Never:
4541 case FastMixer_Dynamic:
4542 mNormalSink = mOutputSink;
4543 break;
4544 case FastMixer_Always:
4545 mNormalSink = mPipeSink;
4546 break;
4547 case FastMixer_Static:
4548 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4549 break;
4550 }
4551}
4552
4553AudioFlinger::MixerThread::~MixerThread()
4554{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004555 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004556 FastMixerStateQueue *sq = mFastMixer->sq();
4557 FastMixerState *state = sq->begin();
4558 if (state->mCommand == FastMixerState::COLD_IDLE) {
4559 int32_t old = android_atomic_inc(&mFastMixerFutex);
4560 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004561 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004562 }
4563 }
4564 state->mCommand = FastMixerState::EXIT;
4565 sq->end();
4566 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4567 mFastMixer->join();
4568 // Though the fast mixer thread has exited, it's state queue is still valid.
4569 // We'll use that extract the final state which contains one remaining fast track
4570 // corresponding to our sub-mix.
4571 state = sq->begin();
4572 ALOG_ASSERT(state->mTrackMask == 1);
4573 FastTrack *fastTrack = &state->mFastTracks[0];
4574 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4575 delete fastTrack->mBufferProvider;
4576 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004577 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004578#ifdef AUDIO_WATCHDOG
4579 if (mAudioWatchdog != 0) {
4580 mAudioWatchdog->requestExit();
4581 mAudioWatchdog->requestExitAndWait();
4582 mAudioWatchdog.clear();
4583 }
4584#endif
4585 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004586 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004587 delete mAudioMixer;
4588}
4589
4590
4591uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4592{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004593 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004594 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4595 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4596 }
4597 return latency;
4598}
4599
Eric Laurentbfb1b832013-01-07 09:53:42 -08004600ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004601{
4602 // FIXME we should only do one push per cycle; confirm this is true
4603 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004604 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004605 FastMixerStateQueue *sq = mFastMixer->sq();
4606 FastMixerState *state = sq->begin();
4607 if (state->mCommand != FastMixerState::MIX_WRITE &&
4608 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4609 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004610
4611 // FIXME workaround for first HAL write being CPU bound on some devices
4612 ATRACE_BEGIN("write");
4613 mOutput->write((char *)mSinkBuffer, 0);
4614 ATRACE_END();
4615
Eric Laurent81784c32012-11-19 14:55:58 -08004616 int32_t old = android_atomic_inc(&mFastMixerFutex);
4617 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004618 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004619 }
4620#ifdef AUDIO_WATCHDOG
4621 if (mAudioWatchdog != 0) {
4622 mAudioWatchdog->resume();
4623 }
4624#endif
4625 }
4626 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004627#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004628 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004629 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004630#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004631 sq->end();
4632 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4633 if (kUseFastMixer == FastMixer_Dynamic) {
4634 mNormalSink = mPipeSink;
4635 }
4636 } else {
4637 sq->end(false /*didModify*/);
4638 }
4639 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004640 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004641}
4642
4643void AudioFlinger::MixerThread::threadLoop_standby()
4644{
4645 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004646 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004647 FastMixerStateQueue *sq = mFastMixer->sq();
4648 FastMixerState *state = sq->begin();
4649 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004650 // Report any frames trapped in the Monopipe
4651 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4652 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4653 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4654 "monoPipeWritten:%lld monoPipeLeft:%lld",
4655 (long long)mFramesWritten, (long long)mSuspendedFrames,
4656 (long long)mPipeSink->framesWritten(), pipeFrames);
4657 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4658
Eric Laurent81784c32012-11-19 14:55:58 -08004659 state->mCommand = FastMixerState::COLD_IDLE;
4660 state->mColdFutexAddr = &mFastMixerFutex;
4661 state->mColdGen++;
4662 mFastMixerFutex = 0;
4663 sq->end();
4664 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4665 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4666 if (kUseFastMixer == FastMixer_Dynamic) {
4667 mNormalSink = mOutputSink;
4668 }
4669#ifdef AUDIO_WATCHDOG
4670 if (mAudioWatchdog != 0) {
4671 mAudioWatchdog->pause();
4672 }
4673#endif
4674 } else {
4675 sq->end(false /*didModify*/);
4676 }
4677 }
4678 PlaybackThread::threadLoop_standby();
4679}
4680
Eric Laurentbfb1b832013-01-07 09:53:42 -08004681bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4682{
4683 return false;
4684}
4685
4686bool AudioFlinger::PlaybackThread::shouldStandby_l()
4687{
4688 return !mStandby;
4689}
4690
4691bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4692{
4693 Mutex::Autolock _l(mLock);
4694 return waitingAsyncCallback_l();
4695}
4696
Eric Laurent81784c32012-11-19 14:55:58 -08004697// shared by MIXER and DIRECT, overridden by DUPLICATING
4698void AudioFlinger::PlaybackThread::threadLoop_standby()
4699{
4700 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004701 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004702 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004703 // discard any pending drain or write ack by incrementing sequence
4704 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4705 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004706 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004707 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4708 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004709 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004710 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004711}
4712
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004713void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4714{
4715 ALOGV("signal playback thread");
4716 broadcast_l();
4717}
4718
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004719void AudioFlinger::PlaybackThread::onAsyncError()
4720{
4721 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4722 invalidateTracks((audio_stream_type_t)i);
4723 }
4724}
4725
Eric Laurent81784c32012-11-19 14:55:58 -08004726void AudioFlinger::MixerThread::threadLoop_mix()
4727{
Eric Laurent81784c32012-11-19 14:55:58 -08004728 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004729 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004730 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004731 // increase sleep time progressively when application underrun condition clears.
4732 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4733 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4734 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004735 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004736 sleepTimeShift--;
4737 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004738 mSleepTimeUs = 0;
4739 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004740 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004741
Eric Laurent81784c32012-11-19 14:55:58 -08004742}
4743
4744void AudioFlinger::MixerThread::threadLoop_sleepTime()
4745{
4746 // If no tracks are ready, sleep once for the duration of an output
4747 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004748 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004749 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004750 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4751 // Using the Monopipe availableToWrite, we estimate the
4752 // sleep time to retry for more data (before we underrun).
4753 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4754 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4755 const size_t pipeFrames = monoPipe->maxFrames();
4756 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4757 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4758 const size_t framesDelay = std::min(
4759 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4760 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4761 pipeFrames, framesLeft, framesDelay);
4762 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4763 } else {
4764 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4765 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4766 mSleepTimeUs = kMinThreadSleepTimeUs;
4767 }
4768 // reduce sleep time in case of consecutive application underruns to avoid
4769 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4770 // duration we would end up writing less data than needed by the audio HAL if
4771 // the condition persists.
4772 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4773 sleepTimeShift++;
4774 }
Eric Laurent81784c32012-11-19 14:55:58 -08004775 }
4776 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004777 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004778 }
4779 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004780 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4781 // before effects processing or output.
4782 if (mMixerBufferValid) {
4783 memset(mMixerBuffer, 0, mMixerBufferSize);
4784 } else {
4785 memset(mSinkBuffer, 0, mSinkBufferSize);
4786 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004787 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004788 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4789 "anticipated start");
4790 }
4791 // TODO add standby time extension fct of effect tail
4792}
4793
4794// prepareTracks_l() must be called with ThreadBase::mLock held
4795AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4796 Vector< sp<Track> > *tracksToRemove)
4797{
Andy Hungc0691382018-09-12 18:01:57 -07004798 // clean up deleted track ids in AudioMixer before allocating new tracks
4799 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4800 // for each trackId, destroy it in the AudioMixer
4801 if (mAudioMixer->exists(trackId)) {
4802 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004803 }
4804 });
Andy Hungc0691382018-09-12 18:01:57 -07004805 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004806
4807 mixer_state mixerStatus = MIXER_IDLE;
4808 // find out which tracks need to be processed
4809 size_t count = mActiveTracks.size();
4810 size_t mixedTracks = 0;
4811 size_t tracksWithEffect = 0;
4812 // counts only _active_ fast tracks
4813 size_t fastTracks = 0;
4814 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4815
4816 float masterVolume = mMasterVolume;
4817 bool masterMute = mMasterMute;
4818
4819 if (masterMute) {
4820 masterVolume = 0;
4821 }
4822 // Delegate master volume control to effect in output mix effect chain if needed
4823 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4824 if (chain != 0) {
4825 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4826 chain->setVolume_l(&v, &v);
4827 masterVolume = (float)((v + (1 << 23)) >> 24);
4828 chain.clear();
4829 }
4830
4831 // prepare a new state to push
4832 FastMixerStateQueue *sq = NULL;
4833 FastMixerState *state = NULL;
4834 bool didModify = false;
4835 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004836 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004837 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004838 sq = mFastMixer->sq();
4839 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004840 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004841 }
4842
Andy Hung69aed5f2014-02-25 17:24:40 -08004843 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004844 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004845
Andy Hungbd3b2b02018-05-21 10:53:11 -07004846 // DeferredOperations handles statistics after setting mixerStatus.
4847 class DeferredOperations {
4848 public:
Andy Hungea840382020-05-05 21:50:17 -07004849 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4850 : mMixerStatus(mixerStatus)
4851 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004852
4853 // when leaving scope, tally frames properly.
4854 ~DeferredOperations() {
4855 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4856 // because that is when the underrun occurs.
4857 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004858 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004859 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004860 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004861 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004862 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004863 }
4864 }
Andy Hungea840382020-05-05 21:50:17 -07004865 // send the max underrun frames for this mixer period
4866 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004867 }
4868
4869 // tallyUnderrunFrames() is called to update the track counters
4870 // with the number of underrun frames for a particular mixer period.
4871 // We defer tallying until we know the final mixer status.
4872 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4873 mUnderrunFrames.emplace_back(track, underrunFrames);
4874 }
4875
4876 private:
4877 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004878 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004879 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004880 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004881 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004882
jiabin245cdd92018-12-07 17:55:15 -08004883 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004884 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004885 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004886
4887 // this const just means the local variable doesn't change
4888 Track* const track = t.get();
4889
4890 // process fast tracks
4891 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004892 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4893 "%s(%d): FastTrack(%d) present without FastMixer",
4894 __func__, id(), track->id());
4895
jiabin245cdd92018-12-07 17:55:15 -08004896 if (track->getHapticPlaybackEnabled()) {
4897 noFastHapticTrack = false;
4898 }
Eric Laurent81784c32012-11-19 14:55:58 -08004899
4900 // It's theoretically possible (though unlikely) for a fast track to be created
4901 // and then removed within the same normal mix cycle. This is not a problem, as
4902 // the track never becomes active so it's fast mixer slot is never touched.
4903 // The converse, of removing an (active) track and then creating a new track
4904 // at the identical fast mixer slot within the same normal mix cycle,
4905 // is impossible because the slot isn't marked available until the end of each cycle.
4906 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004907 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004908 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4909 FastTrack *fastTrack = &state->mFastTracks[j];
4910
4911 // Determine whether the track is currently in underrun condition,
4912 // and whether it had a recent underrun.
4913 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4914 FastTrackUnderruns underruns = ftDump->mUnderruns;
4915 uint32_t recentFull = (underruns.mBitFields.mFull -
4916 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4917 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4918 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4919 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4920 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4921 uint32_t recentUnderruns = recentPartial + recentEmpty;
4922 track->mObservedUnderruns = underruns;
4923 // don't count underruns that occur while stopping or pausing
4924 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004925 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004926 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4927 recentUnderruns > 0) {
4928 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004929 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004930 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004931 // Immediately account for FastTrack underruns.
4932 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004933
4934 // This is similar to the state machine for normal tracks,
4935 // with a few modifications for fast tracks.
4936 bool isActive = true;
4937 switch (track->mState) {
4938 case TrackBase::STOPPING_1:
4939 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004940 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004941 track->mState = TrackBase::STOPPING_2;
4942 }
4943 break;
4944 case TrackBase::PAUSING:
4945 // ramp down is not yet implemented
4946 track->setPaused();
4947 break;
4948 case TrackBase::RESUMING:
4949 // ramp up is not yet implemented
4950 track->mState = TrackBase::ACTIVE;
4951 break;
4952 case TrackBase::ACTIVE:
4953 if (recentFull > 0 || recentPartial > 0) {
4954 // track has provided at least some frames recently: reset retry count
4955 track->mRetryCount = kMaxTrackRetries;
4956 }
4957 if (recentUnderruns == 0) {
4958 // no recent underruns: stay active
4959 break;
4960 }
4961 // there has recently been an underrun of some kind
4962 if (track->sharedBuffer() == 0) {
4963 // were any of the recent underruns "empty" (no frames available)?
4964 if (recentEmpty == 0) {
4965 // no, then ignore the partial underruns as they are allowed indefinitely
4966 break;
4967 }
4968 // there has recently been an "empty" underrun: decrement the retry counter
4969 if (--(track->mRetryCount) > 0) {
4970 break;
4971 }
4972 // indicate to client process that the track was disabled because of underrun;
4973 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004974 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004975 // remove from active list, but state remains ACTIVE [confusing but true]
4976 isActive = false;
4977 break;
4978 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004979 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004980 case TrackBase::STOPPING_2:
4981 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004982 case TrackBase::STOPPED:
4983 case TrackBase::FLUSHED: // flush() while active
4984 // Check for presentation complete if track is inactive
4985 // We have consumed all the buffers of this track.
4986 // This would be incomplete if we auto-paused on underrun
4987 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004988 uint32_t latency = 0;
4989 status_t result = mOutput->stream->getLatency(&latency);
4990 ALOGE_IF(result != OK,
4991 "Error when retrieving output stream latency: %d", result);
4992 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004993 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004994 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4995 // track stays in active list until presentation is complete
4996 break;
4997 }
4998 }
4999 if (track->isStopping_2()) {
5000 track->mState = TrackBase::STOPPED;
5001 }
5002 if (track->isStopped()) {
5003 // Can't reset directly, as fast mixer is still polling this track
5004 // track->reset();
5005 // So instead mark this track as needing to be reset after push with ack
5006 resetMask |= 1 << i;
5007 }
5008 isActive = false;
5009 break;
5010 case TrackBase::IDLE:
5011 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005012 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005013 }
5014
5015 if (isActive) {
5016 // was it previously inactive?
5017 if (!(state->mTrackMask & (1 << j))) {
5018 ExtendedAudioBufferProvider *eabp = track;
5019 VolumeProvider *vp = track;
5020 fastTrack->mBufferProvider = eabp;
5021 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005022 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005023 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005024 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005025 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005026 fastTrack->mGeneration++;
5027 state->mTrackMask |= 1 << j;
5028 didModify = true;
5029 // no acknowledgement required for newly active tracks
5030 }
Kevin Rocard12381092018-04-11 09:19:59 -07005031 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005032 float volume;
5033 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5034 volume = 0.f;
5035 } else {
5036 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5037 }
5038
5039 handleVoipVolume_l(&volume);
5040
Eric Laurent81784c32012-11-19 14:55:58 -08005041 // cache the combined master volume and stream type volume for fast mixer; this
5042 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005043 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005044 proxy->framesReleased()).first;
5045 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005046 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005047 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5048 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5049 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005050
Kevin Rocard12381092018-04-11 09:19:59 -07005051 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005052 ++fastTracks;
5053 } else {
5054 // was it previously active?
5055 if (state->mTrackMask & (1 << j)) {
5056 fastTrack->mBufferProvider = NULL;
5057 fastTrack->mGeneration++;
5058 state->mTrackMask &= ~(1 << j);
5059 didModify = true;
5060 // If any fast tracks were removed, we must wait for acknowledgement
5061 // because we're about to decrement the last sp<> on those tracks.
5062 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5063 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005064 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5065 // AudioTrack may start (which may not be with a start() but with a write()
5066 // after underrun) and immediately paused or released. In that case the
5067 // FastTrack state hasn't had time to update.
5068 // TODO Remove the ALOGW when this theory is confirmed.
5069 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005070 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5071 j, track->mState, state->mTrackMask, recentUnderruns,
5072 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005073 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005074 }
5075 tracksToRemove->add(track);
5076 // Avoids a misleading display in dumpsys
5077 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5078 }
jiabin245cdd92018-12-07 17:55:15 -08005079 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5080 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5081 didModify = true;
5082 }
Eric Laurent81784c32012-11-19 14:55:58 -08005083 continue;
5084 }
5085
5086 { // local variable scope to avoid goto warning
5087
5088 audio_track_cblk_t* cblk = track->cblk();
5089
5090 // The first time a track is added we wait
5091 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005092 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005093
5094 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005095 // use the trackId as the AudioMixer name.
5096 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005097 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005098 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005099 track->mChannelMask,
5100 track->mFormat,
5101 track->mSessionId);
5102 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005103 ALOGW("%s(): AudioMixer cannot create track(%d)"
5104 " mask %#x, format %#x, sessionId %d",
5105 __func__, trackId,
5106 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005107 tracksToRemove->add(track);
5108 track->invalidate(); // consider it dead.
5109 continue;
5110 }
5111 }
5112
Eric Laurent81784c32012-11-19 14:55:58 -08005113 // make sure that we have enough frames to mix one full buffer.
5114 // enforce this condition only once to enable draining the buffer in case the client
5115 // app does not call stop() and relies on underrun to stop:
5116 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5117 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005118 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005119 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005120 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005121
5122 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005123 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005124 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5125 // add frames already consumed but not yet released by the resampler
5126 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005127 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005128
Eric Laurent81784c32012-11-19 14:55:58 -08005129 uint32_t minFrames = 1;
5130 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5131 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005132 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005133 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005134
5135 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005136 if (ATRACE_ENABLED()) {
5137 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005138 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005139 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005140 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005141 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005142 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005143 !track->isPaused() && !track->isTerminated())
5144 {
Andy Hungc0691382018-09-12 18:01:57 -07005145 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005146
5147 mixedTracks++;
5148
Andy Hung69aed5f2014-02-25 17:24:40 -08005149 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5150 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005151 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005152 if (track->mainBuffer() != mSinkBuffer &&
5153 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005154 if (mEffectBufferEnabled) {
5155 mEffectBufferValid = true; // Later can set directly.
5156 }
Eric Laurent81784c32012-11-19 14:55:58 -08005157 chain = getEffectChain_l(track->sessionId());
5158 // Delegate volume control to effect in track effect chain if needed
5159 if (chain != 0) {
5160 tracksWithEffect++;
5161 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005162 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005163 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005164 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005165 }
5166 }
5167
5168
5169 int param = AudioMixer::VOLUME;
5170 if (track->mFillingUpStatus == Track::FS_FILLED) {
5171 // no ramp for the first volume setting
5172 track->mFillingUpStatus = Track::FS_ACTIVE;
5173 if (track->mState == TrackBase::RESUMING) {
5174 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005175 // If a new track is paused immediately after start, do not ramp on resume.
5176 if (cblk->mServer != 0) {
5177 param = AudioMixer::RAMP_VOLUME;
5178 }
Eric Laurent81784c32012-11-19 14:55:58 -08005179 }
Andy Hungc0691382018-09-12 18:01:57 -07005180 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005181 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005182 // FIXME should not make a decision based on mServer
5183 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005184 // If the track is stopped before the first frame was mixed,
5185 // do not apply ramp
5186 param = AudioMixer::RAMP_VOLUME;
5187 }
5188
5189 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005190 uint32_t vl, vr; // in U8.24 integer format
5191 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005192 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005193 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005194 // Always fetch volumeshaper volume to ensure state is updated.
5195 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5196 const float vh = track->getVolumeHandler()->getVolume(
5197 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005198
Eric Laurenteab90452019-06-24 15:17:46 -07005199 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5200 v = 0;
5201 }
5202
5203 handleVoipVolume_l(&v);
5204
5205 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005206 vl = vr = 0;
5207 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005208 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005209 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005210 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005211 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5212 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005213 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005214 if (vlf > GAIN_FLOAT_UNITY) {
5215 ALOGV("Track left volume out of range: %.3g", vlf);
5216 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005217 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005218 if (vrf > GAIN_FLOAT_UNITY) {
5219 ALOGV("Track right volume out of range: %.3g", vrf);
5220 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005221 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005222 // now apply the master volume and stream type volume and shaper volume
5223 vlf *= v * vh;
5224 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005225 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005226 // then derive vl and vr as U8.24 versions for the effect chain
5227 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5228 vl = (uint32_t) (scaleto8_24 * vlf);
5229 vr = (uint32_t) (scaleto8_24 * vrf);
5230 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005231 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005232 // send level comes from shared memory and so may be corrupt
5233 if (sendLevel > MAX_GAIN_INT) {
5234 ALOGV("Track send level out of range: %04X", sendLevel);
5235 sendLevel = MAX_GAIN_INT;
5236 }
Andy Hung6be49402014-05-30 10:42:03 -07005237 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5238 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005239 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005240
Kevin Rocard12381092018-04-11 09:19:59 -07005241 track->setFinalVolume((vrf + vlf) / 2.f);
5242
Eric Laurent81784c32012-11-19 14:55:58 -08005243 // Delegate volume control to effect in track effect chain if needed
5244 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5245 // Do not ramp volume if volume is controlled by effect
5246 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005247 // Update remaining floating point volume levels
5248 vlf = (float)vl / (1 << 24);
5249 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005250 track->mHasVolumeController = true;
5251 } else {
5252 // force no volume ramp when volume controller was just disabled or removed
5253 // from effect chain to avoid volume spike
5254 if (track->mHasVolumeController) {
5255 param = AudioMixer::VOLUME;
5256 }
5257 track->mHasVolumeController = false;
5258 }
5259
Eric Laurent81784c32012-11-19 14:55:58 -08005260 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005261 mAudioMixer->setBufferProvider(trackId, track);
5262 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005263
Andy Hungc0691382018-09-12 18:01:57 -07005264 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5265 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5266 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005267 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005268 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005269 AudioMixer::TRACK,
5270 AudioMixer::FORMAT, (void *)track->format());
5271 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005272 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005273 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005274 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005275 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005276 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005277 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005278 AudioMixer::MIXER_CHANNEL_MASK,
5279 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005280 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005281 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005282 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005283 if (reqSampleRate == 0) {
5284 reqSampleRate = mSampleRate;
5285 } else if (reqSampleRate > maxSampleRate) {
5286 reqSampleRate = maxSampleRate;
5287 }
Eric Laurent81784c32012-11-19 14:55:58 -08005288 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005289 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005290 AudioMixer::RESAMPLE,
5291 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005292 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005293
Andy Hung333ab962019-05-28 20:23:35 -07005294 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005295 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005296 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005297 AudioMixer::TIMESTRETCH,
5298 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005299 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005300
Andy Hung69aed5f2014-02-25 17:24:40 -08005301 /*
5302 * Select the appropriate output buffer for the track.
5303 *
Andy Hung98ef9782014-03-04 14:46:50 -08005304 * Tracks with effects go into their own effects chain buffer
5305 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005306 *
5307 * Other tracks can use mMixerBuffer for higher precision
5308 * channel accumulation. If this buffer is enabled
5309 * (mMixerBufferEnabled true), then selected tracks will accumulate
5310 * into it.
5311 *
5312 */
5313 if (mMixerBufferEnabled
5314 && (track->mainBuffer() == mSinkBuffer
5315 || track->mainBuffer() == mMixerBuffer)) {
5316 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005317 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005318 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005319 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005320 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005321 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005322 AudioMixer::TRACK,
5323 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5324 // TODO: override track->mainBuffer()?
5325 mMixerBufferValid = true;
5326 } else {
5327 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005328 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005329 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005330 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005331 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005332 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005333 AudioMixer::TRACK,
5334 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5335 }
Eric Laurent81784c32012-11-19 14:55:58 -08005336 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005337 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005338 AudioMixer::TRACK,
5339 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005340 mAudioMixer->setParameter(
5341 trackId,
5342 AudioMixer::TRACK,
5343 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005344 mAudioMixer->setParameter(
5345 trackId,
5346 AudioMixer::TRACK,
5347 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005348
5349 // reset retry count
5350 track->mRetryCount = kMaxTrackRetries;
5351
5352 // If one track is ready, set the mixer ready if:
5353 // - the mixer was not ready during previous round OR
5354 // - no other track is not ready
5355 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5356 mixerStatus != MIXER_TRACKS_ENABLED) {
5357 mixerStatus = MIXER_TRACKS_READY;
5358 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005359
5360 // Enable the next few lines to instrument a test for underrun log handling.
5361 // TODO: Remove when we have a better way of testing the underrun log.
5362#if 0
5363 static int i;
5364 if ((++i & 0xf) == 0) {
5365 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5366 }
5367#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005368 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005369 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005370 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005371 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5372 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005373 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005374 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005375 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005376
Eric Laurent81784c32012-11-19 14:55:58 -08005377 // clear effect chain input buffer if an active track underruns to avoid sending
5378 // previous audio buffer again to effects
5379 chain = getEffectChain_l(track->sessionId());
5380 if (chain != 0) {
5381 chain->clearInputBuffer();
5382 }
5383
Andy Hungc0691382018-09-12 18:01:57 -07005384 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005385 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5386 track->isStopped() || track->isPaused()) {
5387 // We have consumed all the buffers of this track.
5388 // Remove it from the list of active tracks.
5389 // TODO: use actual buffer filling status instead of latency when available from
5390 // audio HAL
5391 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005392 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005393 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5394 if (track->isStopped()) {
5395 track->reset();
5396 }
5397 tracksToRemove->add(track);
5398 }
5399 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005400 // No buffers for this track. Give it a few chances to
5401 // fill a buffer, then remove it from active list.
5402 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005403 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5404 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005405 tracksToRemove->add(track);
5406 // indicate to client process that the track was disabled because of underrun;
5407 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005408 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005409 // If one track is not ready, mark the mixer also not ready if:
5410 // - the mixer was ready during previous round OR
5411 // - no other track is ready
5412 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5413 mixerStatus != MIXER_TRACKS_READY) {
5414 mixerStatus = MIXER_TRACKS_ENABLED;
5415 }
5416 }
Andy Hungc0691382018-09-12 18:01:57 -07005417 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005418 }
5419
5420 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005421
5422 }
5423
jiabin245cdd92018-12-07 17:55:15 -08005424 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5425 // When there is no fast track playing haptic and FastMixer exists,
5426 // enabling the first FastTrack, which provides mixed data from normal
5427 // tracks, to play haptic data.
5428 FastTrack *fastTrack = &state->mFastTracks[0];
5429 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5430 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5431 didModify = true;
5432 }
5433 }
5434
Eric Laurent81784c32012-11-19 14:55:58 -08005435 // Push the new FastMixer state if necessary
5436 bool pauseAudioWatchdog = false;
5437 if (didModify) {
5438 state->mFastTracksGen++;
5439 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5440 if (kUseFastMixer == FastMixer_Dynamic &&
5441 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5442 state->mCommand = FastMixerState::COLD_IDLE;
5443 state->mColdFutexAddr = &mFastMixerFutex;
5444 state->mColdGen++;
5445 mFastMixerFutex = 0;
5446 if (kUseFastMixer == FastMixer_Dynamic) {
5447 mNormalSink = mOutputSink;
5448 }
5449 // If we go into cold idle, need to wait for acknowledgement
5450 // so that fast mixer stops doing I/O.
5451 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5452 pauseAudioWatchdog = true;
5453 }
Eric Laurent81784c32012-11-19 14:55:58 -08005454 }
5455 if (sq != NULL) {
5456 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005457 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5458 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5459 // when bringing the output sink into standby.)
5460 //
5461 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5462 //
5463 // This occurs with BT suspend when we idle the FastMixer with
5464 // active tracks, which may be added or removed.
5465 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005466 }
5467#ifdef AUDIO_WATCHDOG
5468 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5469 mAudioWatchdog->pause();
5470 }
5471#endif
5472
5473 // Now perform the deferred reset on fast tracks that have stopped
5474 while (resetMask != 0) {
5475 size_t i = __builtin_ctz(resetMask);
5476 ALOG_ASSERT(i < count);
5477 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005478 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005479 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5480 track->reset();
5481 }
5482
Andy Hung80d03d22018-04-10 10:32:11 -07005483 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5484 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5485 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5486 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5487 // See also the implementation of destroyTrack_l().
5488 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005489 const int trackId = track->id();
5490 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5491 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005492 }
5493 }
5494
Eric Laurent81784c32012-11-19 14:55:58 -08005495 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005496 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005497
Eric Laurent97d547d2014-09-02 14:45:53 -07005498 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5499 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005500 }
5501
5502 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005503 // as long as there are effects we should clear the effects buffer, to avoid
5504 // passing a non-clean buffer to the effect chain
5505 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005506 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005507 // sink or mix buffer must be cleared if all tracks are connected to an
5508 // effect chain as in this case the mixer will not write to the sink or mix buffer
5509 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005510 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5511 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005512 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005513 if (mMixerBufferValid) {
5514 memset(mMixerBuffer, 0, mMixerBufferSize);
5515 // TODO: In testing, mSinkBuffer below need not be cleared because
5516 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5517 // after mixing.
5518 //
5519 // To enforce this guarantee:
5520 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5521 // (mixedTracks == 0 && fastTracks > 0))
5522 // must imply MIXER_TRACKS_READY.
5523 // Later, we may clear buffers regardless, and skip much of this logic.
5524 }
Andy Hung98ef9782014-03-04 14:46:50 -08005525 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005526 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005527 }
5528
5529 // if any fast tracks, then status is ready
5530 mMixerStatusIgnoringFastTracks = mixerStatus;
5531 if (fastTracks > 0) {
5532 mixerStatus = MIXER_TRACKS_READY;
5533 }
5534 return mixerStatus;
5535}
5536
Eric Laurentad7dd962016-09-22 12:38:37 -07005537// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005538uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005539{
5540 uint32_t trackCount = 0;
5541 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005542 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005543 trackCount++;
5544 }
5545 }
5546 return trackCount;
5547}
5548
Andy Hung1bc088a2018-02-09 15:57:31 -08005549// isTrackAllowed_l() must be called with ThreadBase::mLock held
5550bool AudioFlinger::MixerThread::isTrackAllowed_l(
5551 audio_channel_mask_t channelMask, audio_format_t format,
5552 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005553{
Andy Hung1bc088a2018-02-09 15:57:31 -08005554 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5555 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005556 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005557 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov32f0d162019-07-30 14:42:32 -07005558 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005559 ALOGW("%s: invalid format: %#x", __func__, format);
5560 return false;
5561 }
Mikhail Naganov32f0d162019-07-30 14:42:32 -07005562 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005563 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5564 return false;
5565 }
5566 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005567}
5568
Eric Laurent10351942014-05-08 18:49:52 -07005569// checkForNewParameter_l() must be called with ThreadBase::mLock held
5570bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5571 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005572{
Eric Laurent81784c32012-11-19 14:55:58 -08005573 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005574 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005575
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005576 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005577
Eric Laurent10351942014-05-08 18:49:52 -07005578 AudioParameter param = AudioParameter(keyValuePair);
5579 int value;
5580 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5581 reconfig = true;
5582 }
5583 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005584 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005585 status = BAD_VALUE;
5586 } else {
5587 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005588 reconfig = true;
5589 }
Eric Laurent10351942014-05-08 18:49:52 -07005590 }
5591 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005592 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005593 status = BAD_VALUE;
5594 } else {
5595 // no need to save value, since it's constant
5596 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005597 }
Eric Laurent10351942014-05-08 18:49:52 -07005598 }
5599 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5600 // do not accept frame count changes if tracks are open as the track buffer
5601 // size depends on frame count and correct behavior would not be guaranteed
5602 // if frame count is changed after track creation
5603 if (!mTracks.isEmpty()) {
5604 status = INVALID_OPERATION;
5605 } else {
5606 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005607 }
Eric Laurent10351942014-05-08 18:49:52 -07005608 }
5609 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07005610 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005611 }
Eric Laurent81784c32012-11-19 14:55:58 -08005612
Eric Laurent10351942014-05-08 18:49:52 -07005613 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005614 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005615 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005616 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005617 if (!mStandby) {
5618 mThreadMetrics.logEndInterval();
5619 mStandby = true;
5620 }
Eric Laurent10351942014-05-08 18:49:52 -07005621 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005622 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005623 }
Eric Laurent10351942014-05-08 18:49:52 -07005624 if (status == NO_ERROR && reconfig) {
5625 readOutputParameters_l();
5626 delete mAudioMixer;
5627 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005628 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005629 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005630 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005631 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005632 track->mChannelMask,
5633 track->mFormat,
5634 track->mSessionId);
5635 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005636 "%s(): AudioMixer cannot create track(%d)"
5637 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005638 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005639 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005640 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005641 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005642 }
Eric Laurent81784c32012-11-19 14:55:58 -08005643 }
5644
Dean Wheatley68918102021-03-19 22:09:19 +11005645 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005646}
5647
5648
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005649void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005650{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005651 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005652 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005653 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005654 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005655 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5656 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5657 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005658 if (hasFastMixer()) {
5659 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5660
5661 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5662 // while we are dumping it. It may be inconsistent, but it won't mutate!
5663 // This is a large object so we place it on the heap.
5664 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005665 const std::unique_ptr<FastMixerDumpState> copy =
5666 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005667 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005668
5669#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005670 // Similar for state queue
5671 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5672 observerCopy.dump(fd);
5673 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5674 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005675#endif
5676
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005677#ifdef AUDIO_WATCHDOG
5678 if (mAudioWatchdog != 0) {
5679 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5680 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5681 wdCopy.dump(fd);
5682 }
5683#endif
5684
5685 } else {
5686 dprintf(fd, " No FastMixer\n");
5687 }
Eric Laurent81784c32012-11-19 14:55:58 -08005688}
5689
5690uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5691{
5692 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5693}
5694
5695uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5696{
5697 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5698}
5699
5700void AudioFlinger::MixerThread::cacheParameters_l()
5701{
5702 PlaybackThread::cacheParameters_l();
5703
5704 // FIXME: Relaxed timing because of a certain device that can't meet latency
5705 // Should be reduced to 2x after the vendor fixes the driver issue
5706 // increase threshold again due to low power audio mode. The way this warning
5707 // threshold is calculated and its usefulness should be reconsidered anyway.
5708 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5709}
5710
5711// ----------------------------------------------------------------------------
5712
5713AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabin10d86fd2019-10-31 17:20:42 -07005714 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5715 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005716{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005717 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005718}
5719
Eric Laurent81784c32012-11-19 14:55:58 -08005720AudioFlinger::DirectOutputThread::~DirectOutputThread()
5721{
5722}
5723
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005724void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005725{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005726 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005727 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5728 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5729}
5730
5731void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5732{
5733 Mutex::Autolock _l(mLock);
5734 if (mMasterBalance != balance) {
5735 mMasterBalance.store(balance);
5736 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5737 broadcast_l();
5738 }
5739}
5740
Eric Laurent5850c4c2016-11-10 13:04:31 -08005741void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005742{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005743 float left, right;
5744
Andy Hung333ab962019-05-28 20:23:35 -07005745 // Ensure volumeshaper state always advances even when muted.
5746 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5747 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5748 proxy->framesReleased());
5749 mVolumeShaperActive = shaperActive;
5750
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005751 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005752 left = right = 0;
5753 } else {
5754 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005755 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005756
Glenn Kastenc56f3422014-03-21 17:53:17 -07005757 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5758 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5759 if (left > GAIN_FLOAT_UNITY) {
5760 left = GAIN_FLOAT_UNITY;
5761 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005762 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005763 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5764 if (right > GAIN_FLOAT_UNITY) {
5765 right = GAIN_FLOAT_UNITY;
5766 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005767 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005768 }
5769
5770 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005771 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005772 if (left != mLeftVolFloat || right != mRightVolFloat) {
5773 mLeftVolFloat = left;
5774 mRightVolFloat = right;
5775
Eric Laurentbfb1b832013-01-07 09:53:42 -08005776 // Delegate volume control to effect in track effect chain if needed
5777 // only one effect chain can be present on DirectOutputThread, so if
5778 // there is one, the track is connected to it
5779 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005780 // if effect chain exists, volume is handled by it.
5781 // Convert volumes from float to 8.24
5782 uint32_t vl = (uint32_t)(left * (1 << 24));
5783 uint32_t vr = (uint32_t)(right * (1 << 24));
5784 // Direct/Offload effect chains set output volume in setVolume_l().
5785 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5786 } else {
5787 // otherwise we directly set the volume.
5788 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005789 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005790 }
5791 }
5792}
5793
Phil Burk43b4dcc2015-06-09 16:53:44 -07005794void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5795{
5796 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005797 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005798
Eric Laurent0f0631e2015-07-06 18:01:25 -07005799 if (previousTrack != 0 && latestTrack != 0) {
5800 if (mType == DIRECT) {
5801 if (previousTrack.get() != latestTrack.get()) {
5802 mFlushPending = true;
5803 }
5804 } else /* mType == OFFLOAD */ {
5805 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5806 mFlushPending = true;
5807 }
5808 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005809 } else if (previousTrack == 0) {
5810 // there could be an old track added back during track transition for direct
5811 // output, so always issues flush to flush data of the previous track if it
5812 // was already destroyed with HAL paused, then flush can resume the playback
5813 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005814 }
5815 PlaybackThread::onAddNewTrack_l();
5816}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005817
Eric Laurent81784c32012-11-19 14:55:58 -08005818AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5819 Vector< sp<Track> > *tracksToRemove
5820)
5821{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005822 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005823 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005824 bool doHwPause = false;
5825 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005826
5827 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005828 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005829 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005830 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005831 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005832 continue;
5833 }
5834
Eric Laurent5850c4c2016-11-10 13:04:31 -08005835 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005836#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005837 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005838#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005839 // Only consider last track started for volume and mixer state control.
5840 // In theory an older track could underrun and restart after the new one starts
5841 // but as we only care about the transition phase between two tracks on a
5842 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005843 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005844 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005845
Kuowei Li23666472021-01-20 10:23:25 +08005846 if (track->isPausePending()) {
5847 track->pauseAck();
5848 // It is possible a track might have been flushed or stopped.
5849 // Other operations such as flush pending might occur on the next prepare.
5850 if (track->isPausing()) {
5851 track->setPaused();
5852 }
5853 // Always perform pause, as an immediate flush will change
5854 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005855 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005856 doHwPause = true;
5857 mHwPaused = true;
5858 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005859 } else if (track->isFlushPending()) {
5860 track->flushAck();
5861 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005862 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005863 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005864 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005865 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005866 if (last) {
5867 mLeftVolFloat = mRightVolFloat = -1.0;
5868 if (mHwPaused) {
5869 doHwResume = true;
5870 mHwPaused = false;
5871 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005872 }
5873 }
5874
Eric Laurent81784c32012-11-19 14:55:58 -08005875 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005876 // for all its buffers to be filled before processing it.
5877 // Allow draining the buffer in case the client
5878 // app does not call stop() and relies on underrun to stop:
5879 // hence the test on (track->mRetryCount > 1).
Andy Hung0765c9a2021-04-27 17:46:12 -07005880 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
5881 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
5882 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07005883 // Do not use a high threshold for compressed audio.
Andy Hung0765c9a2021-04-27 17:46:12 -07005884
5885 // target retry count that we will use is based on the time we wait for retries.
5886 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
5887 // the retry threshold is when we accept any size for PCM data. This is slightly
5888 // smaller than the retry count so we can push small bits of data without a glitch.
5889 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08005890 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005891 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung0765c9a2021-04-27 17:46:12 -07005892 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005893 minFrames = mNormalFrameCount;
5894 } else {
5895 minFrames = 1;
5896 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005897
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005898 const size_t framesReady = track->framesReady();
5899 const int trackId = track->id();
5900 if (ATRACE_ENABLED()) {
5901 std::string traceName("nRdy");
5902 traceName += std::to_string(trackId);
5903 ATRACE_INT(traceName.c_str(), framesReady);
5904 }
5905 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005906 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005907 {
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005908 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005909
5910 if (track->mFillingUpStatus == Track::FS_FILLED) {
5911 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005912 if (last) {
5913 // make sure processVolume_l() will apply new volume even if 0
5914 mLeftVolFloat = mRightVolFloat = -1.0;
5915 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005916 if (!mHwSupportsPause) {
5917 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005918 }
5919 }
5920
5921 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005922 processVolume_l(track, last);
5923 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005924 sp<Track> previousTrack = mPreviousTrack.promote();
5925 if (previousTrack != 0) {
5926 if (track != previousTrack.get()) {
5927 // Flush any data still being written from last track
5928 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005929 // Invalidate previous track to force a seek when resuming.
5930 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005931 }
5932 }
5933 mPreviousTrack = track;
5934
Eric Laurentd595b7c2013-04-03 17:27:56 -07005935 // reset retry count
Andy Hung0765c9a2021-04-27 17:46:12 -07005936 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005937 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005938 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005939 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005940 doHwResume = true;
5941 mHwPaused = false;
5942 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005943 }
Eric Laurent81784c32012-11-19 14:55:58 -08005944 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005945 // clear effect chain input buffer if the last active track started underruns
5946 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005947 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005948 mEffectChains[0]->clearInputBuffer();
5949 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005950 if (track->isStopping_1()) {
5951 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005952 if (last && mHwPaused) {
5953 doHwResume = true;
5954 mHwPaused = false;
5955 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005956 }
5957 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5958 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005959 // We have consumed all the buffers of this track.
5960 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005961 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005962 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005963 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5964 } else {
5965 audioHALFrames = 0;
5966 }
5967
Andy Hung818e7a32016-02-16 18:08:07 -08005968 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005969 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005970 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08005971 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005972 if (track->isStopping_2()) {
5973 track->mState = TrackBase::STOPPED;
5974 }
Eric Laurent81784c32012-11-19 14:55:58 -08005975 if (track->isStopped()) {
5976 track->reset();
5977 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005978 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005979 }
5980 } else {
5981 // No buffers for this track. Give it a few chances to
5982 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005983 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005984 if (--(track->mRetryCount) <= 0) {
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005985 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005986 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005987 // indicate to client process that the track was disabled because of underrun;
5988 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005989 track->disable();
Haynes Mathew George82fa4812017-01-24 20:06:05 -08005990 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
5991 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07005992 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5993 "minFrames = %u, mFormat = %#x",
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005994 framesReady, minFrames, mFormat);
Haynes Mathew George82fa4812017-01-24 20:06:05 -08005995 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005996 doHwPause = true;
5997 mHwPaused = true;
5998 }
Haynes Mathew George82fa4812017-01-24 20:06:05 -08005999 } else if (last) {
6000 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006001 }
6002 }
6003 }
6004 }
6005
Eric Laurentd1f69b02014-12-15 14:33:13 -08006006 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006007 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006008 for (size_t i = 0; i < mTracks.size(); i++) {
6009 if (mTracks[i]->isFlushPending()) {
6010 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006011 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006012 }
6013 }
6014 }
6015
6016 // make sure the pause/flush/resume sequence is executed in the right order.
6017 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6018 // before flush and then resume HW. This can happen in case of pause/flush/resume
6019 // if resume is received before pause is executed.
6020 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006021 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006022 status_t result = mOutput->stream->pause();
6023 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006024 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006025 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006026 flushHw_l();
6027 }
6028 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006029 status_t result = mOutput->stream->resume();
6030 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006031 }
Eric Laurent81784c32012-11-19 14:55:58 -08006032 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006033 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006034
6035 return mixerStatus;
6036}
6037
6038void AudioFlinger::DirectOutputThread::threadLoop_mix()
6039{
Eric Laurent81784c32012-11-19 14:55:58 -08006040 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006041 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006042 // output audio to hardware
6043 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006044 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006045 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006046 status_t status = mActiveTrack->getNextBuffer(&buffer);
6047 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006048 // no need to pad with 0 for compressed audio
6049 if (audio_has_proportional_frames(mFormat)) {
6050 memset(curBuf, 0, frameCount * mFrameSize);
6051 }
Eric Laurent81784c32012-11-19 14:55:58 -08006052 break;
6053 }
6054 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6055 frameCount -= buffer.frameCount;
6056 curBuf += buffer.frameCount * mFrameSize;
6057 mActiveTrack->releaseBuffer(&buffer);
6058 }
Andy Hung2098f272014-02-27 14:00:06 -08006059 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006060 mSleepTimeUs = 0;
6061 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006062 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006063}
6064
6065void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6066{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006067 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006068 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006069 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006070 return;
6071 }
Andy Hung6b605f22021-04-27 17:40:26 -07006072 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6073 mSleepTimeUs = mActiveSleepTimeUs;
6074 } else {
6075 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006076 }
Andy Hung6b605f22021-04-27 17:40:26 -07006077 // Note: In S or later, we do not write zeroes for
6078 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006079}
6080
Eric Laurentd1f69b02014-12-15 14:33:13 -08006081void AudioFlinger::DirectOutputThread::threadLoop_exit()
6082{
6083 {
6084 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006085 for (size_t i = 0; i < mTracks.size(); i++) {
6086 if (mTracks[i]->isFlushPending()) {
6087 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006088 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006089 }
6090 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006091 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006092 flushHw_l();
6093 }
6094 }
6095 PlaybackThread::threadLoop_exit();
6096}
6097
6098// must be called with thread mutex locked
6099bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6100{
6101 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006102 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006103
6104 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6105 // after a timeout and we will enter standby then.
6106 if (mTracks.size() > 0) {
6107 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006108 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6109 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006110 }
6111
Eric Laurent5cff4032015-05-26 13:49:58 -07006112 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006113}
6114
Eric Laurent10351942014-05-08 18:49:52 -07006115// checkForNewParameter_l() must be called with ThreadBase::mLock held
6116bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6117 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006118{
6119 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006120 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006121
Eric Laurent10351942014-05-08 18:49:52 -07006122 AudioParameter param = AudioParameter(keyValuePair);
6123 int value;
6124 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07006125 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006126 }
Eric Laurent10351942014-05-08 18:49:52 -07006127 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6128 // do not accept frame count changes if tracks are open as the track buffer
6129 // size depends on frame count and correct behavior would not be garantied
6130 // if frame count is changed after track creation
6131 if (!mTracks.isEmpty()) {
6132 status = INVALID_OPERATION;
6133 } else {
6134 reconfig = true;
6135 }
6136 }
6137 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006138 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006139 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006140 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006141 if (!mStandby) {
6142 mThreadMetrics.logEndInterval();
6143 mStandby = true;
6144 }
Eric Laurent10351942014-05-08 18:49:52 -07006145 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006146 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006147 }
6148 if (status == NO_ERROR && reconfig) {
6149 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006150 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006151 }
6152 }
6153
Dean Wheatley68918102021-03-19 22:09:19 +11006154 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006155}
6156
6157uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6158{
6159 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006160 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006161 time = PlaybackThread::activeSleepTimeUs();
6162 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006163 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006164 }
6165 return time;
6166}
6167
6168uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6169{
6170 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006171 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006172 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6173 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006174 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006175 }
6176 return time;
6177}
6178
6179uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6180{
6181 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006182 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006183 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6184 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006185 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006186 }
6187 return time;
6188}
6189
6190void AudioFlinger::DirectOutputThread::cacheParameters_l()
6191{
6192 PlaybackThread::cacheParameters_l();
6193
6194 // use shorter standby delay as on normal output to release
6195 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006196 // no delay on outputs with HW A/V sync
6197 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006198 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006199 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006200 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006201 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006202 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006203 }
Eric Laurent81784c32012-11-19 14:55:58 -08006204}
6205
Eric Laurente659ef42014-09-29 13:06:46 -07006206void AudioFlinger::DirectOutputThread::flushHw_l()
6207{
Phil Burk062e67a2015-02-11 13:40:50 -08006208 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006209 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006210 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006211 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006212 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006213}
6214
Andy Hung10cbff12017-02-21 17:30:14 -08006215int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6216 // If a VolumeShaper is active, we must wake up periodically to update volume.
6217 const int64_t NS_PER_MS = 1000000;
6218 return mVolumeShaperActive ?
6219 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6220}
6221
Eric Laurent81784c32012-11-19 14:55:58 -08006222// ----------------------------------------------------------------------------
6223
Eric Laurentbfb1b832013-01-07 09:53:42 -08006224AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006225 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006226 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006227 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006228 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006229 mDrainSequence(0),
6230 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006231{
6232}
6233
6234AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6235{
6236}
6237
6238void AudioFlinger::AsyncCallbackThread::onFirstRef()
6239{
6240 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6241}
6242
6243bool AudioFlinger::AsyncCallbackThread::threadLoop()
6244{
6245 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006246 uint32_t writeAckSequence;
6247 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006248 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006249
6250 {
6251 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006252 while (!((mWriteAckSequence & 1) ||
6253 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006254 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006255 exitPending())) {
6256 mWaitWorkCV.wait(mLock);
6257 }
6258
Eric Laurentbfb1b832013-01-07 09:53:42 -08006259 if (exitPending()) {
6260 break;
6261 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006262 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6263 mWriteAckSequence, mDrainSequence);
6264 writeAckSequence = mWriteAckSequence;
6265 mWriteAckSequence &= ~1;
6266 drainSequence = mDrainSequence;
6267 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006268 asyncError = mAsyncError;
6269 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006270 }
6271 {
Eric Laurent4de95592013-09-26 15:28:21 -07006272 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6273 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006274 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006275 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006276 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006277 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006278 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006279 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006280 if (asyncError) {
6281 playbackThread->onAsyncError();
6282 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006283 }
6284 }
6285 }
6286 return false;
6287}
6288
6289void AudioFlinger::AsyncCallbackThread::exit()
6290{
6291 ALOGV("AsyncCallbackThread::exit");
6292 Mutex::Autolock _l(mLock);
6293 requestExit();
6294 mWaitWorkCV.broadcast();
6295}
6296
Eric Laurent3b4529e2013-09-05 18:09:19 -07006297void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006298{
6299 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006300 // bit 0 is cleared
6301 mWriteAckSequence = sequence << 1;
6302}
6303
6304void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6305{
6306 Mutex::Autolock _l(mLock);
6307 // ignore unexpected callbacks
6308 if (mWriteAckSequence & 2) {
6309 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006310 mWaitWorkCV.signal();
6311 }
6312}
6313
Eric Laurent3b4529e2013-09-05 18:09:19 -07006314void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006315{
6316 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006317 // bit 0 is cleared
6318 mDrainSequence = sequence << 1;
6319}
6320
6321void AudioFlinger::AsyncCallbackThread::resetDraining()
6322{
6323 Mutex::Autolock _l(mLock);
6324 // ignore unexpected callbacks
6325 if (mDrainSequence & 2) {
6326 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006327 mWaitWorkCV.signal();
6328 }
6329}
6330
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006331void AudioFlinger::AsyncCallbackThread::setAsyncError()
6332{
6333 Mutex::Autolock _l(mLock);
6334 mAsyncError = true;
6335 mWaitWorkCV.signal();
6336}
6337
Eric Laurentbfb1b832013-01-07 09:53:42 -08006338
6339// ----------------------------------------------------------------------------
6340AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabin10d86fd2019-10-31 17:20:42 -07006341 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6342 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006343 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6344 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006345{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006346 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006347 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006348 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006349}
6350
Eric Laurentbfb1b832013-01-07 09:53:42 -08006351void AudioFlinger::OffloadThread::threadLoop_exit()
6352{
6353 if (mFlushPending || mHwPaused) {
6354 // If a flush is pending or track was paused, just discard buffered data
6355 flushHw_l();
6356 } else {
6357 mMixerStatus = MIXER_DRAIN_ALL;
6358 threadLoop_drain();
6359 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006360 if (mUseAsyncWrite) {
6361 ALOG_ASSERT(mCallbackThread != 0);
6362 mCallbackThread->exit();
6363 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006364 PlaybackThread::threadLoop_exit();
6365}
6366
6367AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6368 Vector< sp<Track> > *tracksToRemove
6369)
6370{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006371 size_t count = mActiveTracks.size();
6372
6373 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006374 bool doHwPause = false;
6375 bool doHwResume = false;
6376
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006377 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006378
Eric Laurentbfb1b832013-01-07 09:53:42 -08006379 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006380 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006381 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006382#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006383 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006384#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006385 // Only consider last track started for volume and mixer state control.
6386 // In theory an older track could underrun and restart after the new one starts
6387 // but as we only care about the transition phase between two tracks on a
6388 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006389 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006390 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006391
Haynes Mathew George7844f672014-01-15 12:32:55 -08006392 if (track->isInvalid()) {
6393 ALOGW("An invalidated track shouldn't be in active list");
6394 tracksToRemove->add(track);
6395 continue;
6396 }
6397
6398 if (track->mState == TrackBase::IDLE) {
6399 ALOGW("An idle track shouldn't be in active list");
6400 continue;
6401 }
6402
Kuowei Li23666472021-01-20 10:23:25 +08006403 if (track->isPausePending()) {
6404 track->pauseAck();
6405 // It is possible a track might have been flushed or stopped.
6406 // Other operations such as flush pending might occur on the next prepare.
6407 if (track->isPausing()) {
6408 track->setPaused();
6409 }
6410 // Always perform pause if last, as an immediate flush will change
6411 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006412 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006413 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006414 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006415 mHwPaused = true;
6416 }
6417 // If we were part way through writing the mixbuffer to
6418 // the HAL we must save this until we resume
6419 // BUG - this will be wrong if a different track is made active,
6420 // in that case we want to discard the pending data in the
6421 // mixbuffer and tell the client to present it again when the
6422 // track is resumed
6423 mPausedWriteLength = mCurrentWriteLength;
6424 mPausedBytesRemaining = mBytesRemaining;
6425 mBytesRemaining = 0; // stop writing
6426 }
6427 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006428 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006429 if (track->isStopping_1()) {
6430 track->mRetryCount = kMaxTrackStopRetriesOffload;
6431 } else {
6432 track->mRetryCount = kMaxTrackRetriesOffload;
6433 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006434 track->flushAck();
6435 if (last) {
6436 mFlushPending = true;
6437 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006438 } else if (track->isResumePending()){
6439 track->resumeAck();
6440 if (last) {
6441 if (mPausedBytesRemaining) {
6442 // Need to continue write that was interrupted
6443 mCurrentWriteLength = mPausedWriteLength;
6444 mBytesRemaining = mPausedBytesRemaining;
6445 mPausedBytesRemaining = 0;
6446 }
6447 if (mHwPaused) {
6448 doHwResume = true;
6449 mHwPaused = false;
6450 // threadLoop_mix() will handle the case that we need to
6451 // resume an interrupted write
6452 }
6453 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006454 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006455
Eric Laurent3df841a2016-07-15 15:15:40 -07006456 mLeftVolFloat = mRightVolFloat = -1.0;
6457
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006458 // Do not handle new data in this iteration even if track->framesReady()
6459 mixerStatus = MIXER_TRACKS_ENABLED;
6460 }
6461 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006462 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006463 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006464 if (track->mFillingUpStatus == Track::FS_FILLED) {
6465 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006466 if (last) {
6467 // make sure processVolume_l() will apply new volume even if 0
6468 mLeftVolFloat = mRightVolFloat = -1.0;
6469 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006470 }
6471
6472 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006473 sp<Track> previousTrack = mPreviousTrack.promote();
6474 if (previousTrack != 0) {
6475 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006476 // Flush any data still being written from last track
6477 mBytesRemaining = 0;
6478 if (mPausedBytesRemaining) {
6479 // Last track was paused so we also need to flush saved
6480 // mixbuffer state and invalidate track so that it will
6481 // re-submit that unwritten data when it is next resumed
6482 mPausedBytesRemaining = 0;
6483 // Invalidate is a bit drastic - would be more efficient
6484 // to have a flag to tell client that some of the
6485 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006486 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006487 }
6488 // flush data already sent to the DSP if changing audio session as audio
6489 // comes from a different source. Also invalidate previous track to force a
6490 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006491 if (previousTrack->sessionId() != track->sessionId()) {
6492 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006493 }
6494 }
6495 }
6496 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006497 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006498 if (track->isStopping_1()) {
6499 track->mRetryCount = kMaxTrackStopRetriesOffload;
6500 } else {
6501 track->mRetryCount = kMaxTrackRetriesOffload;
6502 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006503 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006504 mixerStatus = MIXER_TRACKS_READY;
6505 }
6506 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006507 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006508 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006509 if (--(track->mRetryCount) <= 0) {
6510 // Hardware buffer can hold a large amount of audio so we must
6511 // wait for all current track's data to drain before we say
6512 // that the track is stopped.
6513 if (mBytesRemaining == 0) {
6514 // Only start draining when all data in mixbuffer
6515 // has been written
6516 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6517 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6518 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6519 if (last && !mStandby) {
6520 // do not modify drain sequence if we are already draining. This happens
6521 // when resuming from pause after drain.
6522 if ((mDrainSequence & 1) == 0) {
6523 mSleepTimeUs = 0;
6524 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6525 mixerStatus = MIXER_DRAIN_TRACK;
6526 mDrainSequence += 2;
6527 }
6528 if (mHwPaused) {
6529 // It is possible to move from PAUSED to STOPPING_1 without
6530 // a resume so we must ensure hardware is running
6531 doHwResume = true;
6532 mHwPaused = false;
6533 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006534 }
6535 }
Eric Laurente93cc032016-05-05 10:15:10 -07006536 } else if (last) {
6537 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6538 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006539 }
6540 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006541 // Drain has completed or we are in standby, signal presentation complete
6542 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006543 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006544 uint32_t latency = 0;
6545 status_t result = mOutput->stream->getLatency(&latency);
6546 ALOGE_IF(result != OK,
6547 "Error when retrieving output stream latency: %d", result);
6548 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006549 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006550 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006551 track->presentationComplete(framesWritten, audioHALFrames);
6552 track->reset();
6553 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006554 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006555 if (!mUseAsyncWrite) {
6556 // If we don't get explicit drain notification we must
6557 // register discontinuity regardless of whether this is
6558 // the previous (!last) or the upcoming (last) track
6559 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006560 mTimestampVerifier.discontinuity(
6561 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006562 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006563 }
6564 } else {
6565 // No buffers for this track. Give it a few chances to
6566 // fill a buffer, then remove it from active list.
6567 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006568 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006569 uint64_t position = 0;
6570 struct timespec unused;
6571 // The running check restarts the retry counter at least once.
6572 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6573 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6574 running = true;
6575 mOffloadUnderrunPosition = position;
6576 }
6577 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006578 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6579 (long long)position, (long long)mOffloadUnderrunPosition);
6580 }
6581 if (running) { // still running, give us more time.
6582 track->mRetryCount = kMaxTrackRetriesOffload;
6583 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006584 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6585 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006586 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006587 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006588 // it will then automatically call start() when data is available
6589 track->disable();
6590 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006591 } else if (last){
6592 mixerStatus = MIXER_TRACKS_ENABLED;
6593 }
6594 }
6595 }
6596 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006597 if (track->isReady()) { // check ready to prevent premature start.
6598 processVolume_l(track, last);
6599 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006600 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006601
Eric Laurentea0fade2013-10-04 16:23:48 -07006602 // make sure the pause/flush/resume sequence is executed in the right order.
6603 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6604 // before flush and then resume HW. This can happen in case of pause/flush/resume
6605 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006606 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006607 status_t result = mOutput->stream->pause();
6608 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006609 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006610 if (mFlushPending) {
6611 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006612 }
Eric Laurentfd477972013-10-25 18:10:40 -07006613 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006614 status_t result = mOutput->stream->resume();
6615 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006616 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006617
Eric Laurentbfb1b832013-01-07 09:53:42 -08006618 // remove all the tracks that need to be...
6619 removeTracks_l(*tracksToRemove);
6620
6621 return mixerStatus;
6622}
6623
Eric Laurentbfb1b832013-01-07 09:53:42 -08006624// must be called with thread mutex locked
6625bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6626{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006627 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6628 mWriteAckSequence, mDrainSequence);
6629 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006630 return true;
6631 }
6632 return false;
6633}
6634
Eric Laurentbfb1b832013-01-07 09:53:42 -08006635bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6636{
6637 Mutex::Autolock _l(mLock);
6638 return waitingAsyncCallback_l();
6639}
6640
6641void AudioFlinger::OffloadThread::flushHw_l()
6642{
Eric Laurente659ef42014-09-29 13:06:46 -07006643 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006644 // Flush anything still waiting in the mixbuffer
6645 mCurrentWriteLength = 0;
6646 mBytesRemaining = 0;
6647 mPausedWriteLength = 0;
6648 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006649 // reset bytes written count to reflect that DSP buffers are empty after flush.
6650 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006651 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006652
Eric Laurentbfb1b832013-01-07 09:53:42 -08006653 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006654 // discard any pending drain or write ack by incrementing sequence
6655 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6656 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006657 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006658 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6659 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006660 }
6661}
6662
Haynes Mathew George05317d22016-05-03 16:34:26 -07006663void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6664{
6665 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006666 if (PlaybackThread::invalidateTracks_l(streamType)) {
6667 mFlushPending = true;
6668 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006669}
6670
Eric Laurentbfb1b832013-01-07 09:53:42 -08006671// ----------------------------------------------------------------------------
6672
Eric Laurent81784c32012-11-19 14:55:58 -08006673AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006674 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabin10d86fd2019-10-31 17:20:42 -07006675 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006676 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006677 mWaitTimeMs(UINT_MAX)
6678{
6679 addOutputTrack(mainThread);
6680}
6681
6682AudioFlinger::DuplicatingThread::~DuplicatingThread()
6683{
6684 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6685 mOutputTracks[i]->destroy();
6686 }
6687}
6688
6689void AudioFlinger::DuplicatingThread::threadLoop_mix()
6690{
6691 // mix buffers...
6692 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006693 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006694 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006695 if (mMixerBufferValid) {
6696 memset(mMixerBuffer, 0, mMixerBufferSize);
6697 } else {
6698 memset(mSinkBuffer, 0, mSinkBufferSize);
6699 }
Eric Laurent81784c32012-11-19 14:55:58 -08006700 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006701 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006702 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006703 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006704 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006705}
6706
6707void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6708{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006709 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006710 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006711 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006712 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006713 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006714 }
6715 } else if (mBytesWritten != 0) {
6716 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6717 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006718 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006719 } else {
6720 // flush remaining overflow buffers in output tracks
6721 writeFrames = 0;
6722 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006723 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006724 }
6725}
6726
Eric Laurentbfb1b832013-01-07 09:53:42 -08006727ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006728{
6729 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006730 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6731
6732 // Consider the first OutputTrack for timestamp and frame counting.
6733
6734 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6735 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6736 // we always claim success.
6737 if (i == 0) {
6738 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6739 ALOGD_IF(correction != 0 && writeFrames != 0,
6740 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6741 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6742 mFramesWritten -= correction;
6743 }
6744
6745 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006746 }
Andy Hungcf10d742020-04-28 15:38:24 -07006747 if (mStandby) {
6748 mThreadMetrics.logBeginInterval();
6749 mStandby = false;
6750 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006751 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006752}
6753
6754void AudioFlinger::DuplicatingThread::threadLoop_standby()
6755{
6756 // DuplicatingThread implements standby by stopping all tracks
6757 for (size_t i = 0; i < outputTracks.size(); i++) {
6758 outputTracks[i]->stop();
6759 }
6760}
6761
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006762void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006763{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006764 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006765
6766 std::stringstream ss;
6767 const size_t numTracks = mOutputTracks.size();
6768 ss << " " << numTracks << " OutputTracks";
6769 if (numTracks > 0) {
6770 ss << ":";
6771 for (const auto &track : mOutputTracks) {
6772 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006773 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006774 if (thread.get() != nullptr) {
6775 ss << thread.get() << ", " << thread->id();
6776 } else {
6777 ss << "null";
6778 }
6779 ss << ")";
6780 }
6781 }
6782 ss << "\n";
6783 std::string result = ss.str();
6784 write(fd, result.c_str(), result.size());
6785}
6786
Eric Laurent81784c32012-11-19 14:55:58 -08006787void AudioFlinger::DuplicatingThread::saveOutputTracks()
6788{
6789 outputTracks = mOutputTracks;
6790}
6791
6792void AudioFlinger::DuplicatingThread::clearOutputTracks()
6793{
6794 outputTracks.clear();
6795}
6796
6797void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6798{
6799 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006800 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6801 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6802 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6803 const size_t frameCount =
6804 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6805 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6806 // from different OutputTracks and their associated MixerThreads (e.g. one may
6807 // nearly empty and the other may be dropping data).
6808
6809 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006810 this,
6811 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006812 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006813 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006814 frameCount,
6815 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006816 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6817 if (status != NO_ERROR) {
6818 ALOGE("addOutputTrack() initCheck failed %d", status);
6819 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006820 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006821 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6822 mOutputTracks.add(outputTrack);
6823 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6824 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006825}
6826
6827void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6828{
6829 Mutex::Autolock _l(mLock);
6830 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6831 if (mOutputTracks[i]->thread() == thread) {
6832 mOutputTracks[i]->destroy();
6833 mOutputTracks.removeAt(i);
6834 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006835 if (thread->getOutput() == mOutput) {
6836 mOutput = NULL;
6837 }
Eric Laurent81784c32012-11-19 14:55:58 -08006838 return;
6839 }
6840 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006841 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006842}
6843
6844// caller must hold mLock
6845void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6846{
6847 mWaitTimeMs = UINT_MAX;
6848 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6849 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6850 if (strong != 0) {
6851 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6852 if (waitTimeMs < mWaitTimeMs) {
6853 mWaitTimeMs = waitTimeMs;
6854 }
6855 }
6856 }
6857}
6858
6859
6860bool AudioFlinger::DuplicatingThread::outputsReady(
6861 const SortedVector< sp<OutputTrack> > &outputTracks)
6862{
6863 for (size_t i = 0; i < outputTracks.size(); i++) {
6864 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6865 if (thread == 0) {
6866 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6867 outputTracks[i].get());
6868 return false;
6869 }
6870 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6871 // see note at standby() declaration
6872 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6873 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6874 thread.get());
6875 return false;
6876 }
6877 }
6878 return true;
6879}
6880
Kevin Rocard12381092018-04-11 09:19:59 -07006881void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6882 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006883{
Kevin Rocard12381092018-04-11 09:19:59 -07006884 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6885 outputTrack->setMetadatas(metadata.tracks);
6886 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006887}
6888
Eric Laurent81784c32012-11-19 14:55:58 -08006889uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6890{
6891 return (mWaitTimeMs * 1000) / 2;
6892}
6893
6894void AudioFlinger::DuplicatingThread::cacheParameters_l()
6895{
6896 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6897 updateWaitTime_l();
6898
6899 MixerThread::cacheParameters_l();
6900}
6901
Eric Laurent6acd1d42017-01-04 14:23:29 -08006902
Eric Laurent81784c32012-11-19 14:55:58 -08006903// ----------------------------------------------------------------------------
6904// Record
6905// ----------------------------------------------------------------------------
6906
6907AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6908 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006909 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006910 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006911 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006912 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006913 mInput(input),
Mikhail Naganovaf288872019-09-25 13:05:02 -07006914 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006915 mActiveTracks(&this->mLocalLog),
6916 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006917 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006918 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006919 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6920 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006921 // mFastCapture below
6922 , mFastCaptureFutex(0)
6923 // mInputSource
6924 // mPipeSink
6925 // mPipeSource
6926 , mPipeFramesP2(0)
6927 // mPipeMemory
6928 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006929 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006930 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006931{
Glenn Kastend7dca052015-03-05 16:05:54 -08006932 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6933 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006934
George Burgess IVa8f90c12020-05-14 11:27:19 -07006935 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07006936 mIsMsdDevice = strcmp(
6937 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6938 }
6939
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006940 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006941
Andy Hungc8fddf32018-08-08 18:32:37 -07006942 // TODO: We may also match on address as well as device type for
6943 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabin10d86fd2019-10-31 17:20:42 -07006944 // TODO: This property should be ensure that only contains one single device type.
6945 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6946 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006947 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6948 : AUDIO_DEVICE_NONE));
6949
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006950 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006951 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006952 size_t numCounterOffers = 0;
6953 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006954#if !LOG_NDEBUG
6955 ssize_t index =
6956#else
6957 (void)
6958#endif
6959 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006960 ALOG_ASSERT(index == 0);
6961
6962 // initialize fast capture depending on configuration
6963 bool initFastCapture;
6964 switch (kUseFastCapture) {
6965 case FastCapture_Never:
6966 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006967 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006968 break;
6969 case FastCapture_Always:
6970 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006971 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006972 break;
6973 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006974 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006975 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6976 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6977 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006978 break;
6979 // case FastCapture_Dynamic:
6980 }
6981
6982 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006983 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006984 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006985 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6986 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006987 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006988 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006989 const sp<MemoryDealer> roHeap(readOnlyHeap());
6990 sp<IMemory> pipeMemory;
6991 if ((roHeap == 0) ||
6992 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07006993 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006994 ALOGE("not enough memory for pipe buffer size=%zu; "
6995 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6996 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6997 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006998 goto failed;
6999 }
7000 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7001 memset(pipeBuffer, 0, pipeSize);
7002 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7003 const NBAIO_Format offers[1] = {format};
7004 size_t numCounterOffers = 0;
7005 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7006 ALOG_ASSERT(index == 0);
7007 mPipeSink = pipe;
7008 PipeReader *pipeReader = new PipeReader(*pipe);
7009 numCounterOffers = 0;
7010 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7011 ALOG_ASSERT(index == 0);
7012 mPipeSource = pipeReader;
7013 mPipeFramesP2 = pipeFramesP2;
7014 mPipeMemory = pipeMemory;
7015
7016 // create fast capture
7017 mFastCapture = new FastCapture();
7018 FastCaptureStateQueue *sq = mFastCapture->sq();
7019#ifdef STATE_QUEUE_DUMP
7020 // FIXME
7021#endif
7022 FastCaptureState *state = sq->begin();
7023 state->mCblk = NULL;
7024 state->mInputSource = mInputSource.get();
7025 state->mInputSourceGen++;
7026 state->mPipeSink = pipe;
7027 state->mPipeSinkGen++;
7028 state->mFrameCount = mFrameCount;
7029 state->mCommand = FastCaptureState::COLD_IDLE;
7030 // already done in constructor initialization list
7031 //mFastCaptureFutex = 0;
7032 state->mColdFutexAddr = &mFastCaptureFutex;
7033 state->mColdGen++;
7034 state->mDumpState = &mFastCaptureDumpState;
7035#ifdef TEE_SINK
7036 // FIXME
7037#endif
7038 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7039 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7040 sq->end();
7041 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7042
7043 // start the fast capture
7044 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7045 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007046 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007047 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007048#ifdef AUDIO_WATCHDOG
7049 // FIXME
7050#endif
7051
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007052 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007053 }
Andy Hung8946a282018-04-19 20:04:56 -07007054#ifdef TEE_SINK
7055 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7056 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7057#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007058failed: ;
7059
7060 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007061}
7062
Eric Laurent81784c32012-11-19 14:55:58 -08007063AudioFlinger::RecordThread::~RecordThread()
7064{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007065 if (mFastCapture != 0) {
7066 FastCaptureStateQueue *sq = mFastCapture->sq();
7067 FastCaptureState *state = sq->begin();
7068 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7069 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7070 if (old == -1) {
7071 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7072 }
7073 }
7074 state->mCommand = FastCaptureState::EXIT;
7075 sq->end();
7076 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7077 mFastCapture->join();
7078 mFastCapture.clear();
7079 }
7080 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007081 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007082 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007083}
7084
7085void AudioFlinger::RecordThread::onFirstRef()
7086{
Glenn Kastend7dca052015-03-05 16:05:54 -08007087 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007088}
7089
Eric Laurent555530a2017-02-07 18:17:24 -08007090void AudioFlinger::RecordThread::preExit()
7091{
7092 ALOGV(" preExit()");
7093 Mutex::Autolock _l(mLock);
7094 for (size_t i = 0; i < mTracks.size(); i++) {
7095 sp<RecordTrack> track = mTracks[i];
7096 track->invalidate();
7097 }
7098 mActiveTracks.clear();
7099 mStartStopCond.broadcast();
7100}
7101
Eric Laurent81784c32012-11-19 14:55:58 -08007102bool AudioFlinger::RecordThread::threadLoop()
7103{
Eric Laurent81784c32012-11-19 14:55:58 -08007104 nsecs_t lastWarning = 0;
7105
7106 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007107
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007108reacquire_wakelock:
7109 sp<RecordTrack> activeTrack;
7110 {
7111 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007112 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007113 }
7114
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007115 // used to request a deferred sleep, to be executed later while mutex is unlocked
7116 uint32_t sleepUs = 0;
7117
Andy Hung446f4df2019-02-21 12:26:41 -08007118 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7119
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007120 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007121 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007122 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007123
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007124 // activeTracks accumulates a copy of a subset of mActiveTracks
7125 Vector< sp<RecordTrack> > activeTracks;
7126
Glenn Kasten735f45f2014-08-18 15:51:59 -07007127 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007128 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007129
Glenn Kasten735f45f2014-08-18 15:51:59 -07007130 // reference to a fast track which is about to be removed
7131 sp<RecordTrack> fastTrackToRemove;
7132
Eric Laurent33403f02020-05-29 18:35:06 -07007133 bool silenceFastCapture = false;
7134
Eric Laurent81784c32012-11-19 14:55:58 -08007135 { // scope for mLock
7136 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007137
Eric Laurent021cf962014-05-13 10:18:14 -07007138 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007139
Eric Laurent000a4192014-01-29 15:17:32 -08007140 // check exitPending here because checkForNewParameters_l() and
7141 // checkForNewParameters_l() can temporarily release mLock
7142 if (exitPending()) {
7143 break;
7144 }
7145
Eric Laurent5c25d562016-07-13 17:17:45 -07007146 // sleep with mutex unlocked
7147 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007148 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007149 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7150 ATRACE_END();
7151 sleepUs = 0;
7152 continue;
7153 }
7154
Glenn Kasten2b806402013-11-20 16:37:38 -08007155 // if no active track(s), then standby and release wakelock
7156 size_t size = mActiveTracks.size();
7157 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007158 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007159 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007160 releaseWakeLock_l();
7161 ALOGV("RecordThread: loop stopping");
7162 // go to sleep
7163 mWaitWorkCV.wait(mLock);
7164 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007165 goto reacquire_wakelock;
7166 }
7167
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007168 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007169 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007170 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007171
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007172 activeTrack = mActiveTracks[i];
7173 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007174 if (activeTrack->isFastTrack()) {
7175 ALOG_ASSERT(fastTrackToRemove == 0);
7176 fastTrackToRemove = activeTrack;
7177 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007178 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007179 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007180 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007181 continue;
7182 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007183
7184 TrackBase::track_state activeTrackState = activeTrack->mState;
7185 switch (activeTrackState) {
7186
7187 case TrackBase::PAUSING:
7188 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007189 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007190 doBroadcast = true;
7191 size--;
7192 continue;
7193
7194 case TrackBase::STARTING_1:
7195 sleepUs = 10000;
7196 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007197 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007198 continue;
7199
7200 case TrackBase::STARTING_2:
7201 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007202 if (mStandby) {
7203 mThreadMetrics.logBeginInterval();
7204 mStandby = false;
7205 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007206 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007207 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007208 break;
7209
7210 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007211 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007212 break;
7213
Andy Hungce685402018-10-05 17:23:27 -07007214 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7215 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7216 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007217 default:
Andy Hungce685402018-10-05 17:23:27 -07007218 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7219 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007220 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007221
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007222 if (activeTrack->isFastTrack()) {
7223 ALOG_ASSERT(!mFastTrackAvail);
7224 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007225 // if the active fast track is silenced either:
7226 // 1) silence the whole capture from fast capture buffer if this is
7227 // the only active track
7228 // 2) invalidate this track: this will cause the client to reconnect and possibly
7229 // be invalidated again until unsilenced
7230 if (activeTrack->isSilenced()) {
7231 if (size > 1) {
7232 activeTrack->invalidate();
7233 ALOG_ASSERT(fastTrackToRemove == 0);
7234 fastTrackToRemove = activeTrack;
7235 removeTrack_l(activeTrack);
7236 mActiveTracks.remove(activeTrack);
7237 size--;
7238 continue;
7239 } else {
7240 silenceFastCapture = true;
7241 }
7242 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007243 fastTrack = activeTrack;
7244 }
Eric Laurent33403f02020-05-29 18:35:06 -07007245
7246 activeTracks.add(activeTrack);
7247 i++;
7248
Glenn Kasten9e982352013-08-14 14:39:50 -07007249 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007250
Andy Hungdae27702016-10-31 14:01:16 -07007251 mActiveTracks.updatePowerState(this);
7252
Kevin Rocard069c2712018-03-29 19:09:14 -07007253 updateMetadata_l();
7254
Eric Laurent5c25d562016-07-13 17:17:45 -07007255 if (allStopped) {
7256 standbyIfNotAlreadyInStandby();
7257 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007258 if (doBroadcast) {
7259 mStartStopCond.broadcast();
7260 }
7261
7262 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007263 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007264 if (sleepUs == 0) {
7265 sleepUs = kRecordThreadSleepUs;
7266 }
7267 continue;
7268 }
7269 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007270
Eric Laurent81784c32012-11-19 14:55:58 -08007271 lockEffectChains_l(effectChains);
7272 }
7273
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007274 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007275
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007276 size_t size = effectChains.size();
7277 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007278 // thread mutex is not locked, but effect chain is locked
7279 effectChains[i]->process_l();
7280 }
7281
Glenn Kasten735f45f2014-08-18 15:51:59 -07007282 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007283 if (mFastCapture != 0) {
7284 FastCaptureStateQueue *sq = mFastCapture->sq();
7285 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007286 bool didModify = false;
7287 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007288 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7289 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7290 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7291 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7292 if (old == -1) {
7293 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7294 }
7295 }
7296 state->mCommand = FastCaptureState::READ_WRITE;
7297#if 0 // FIXME
7298 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007299 FastThreadDumpState::kSamplingNforLowRamDevice :
7300 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007301#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007302 didModify = true;
7303 }
7304 audio_track_cblk_t *cblkOld = state->mCblk;
7305 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7306 if (cblkNew != cblkOld) {
7307 state->mCblk = cblkNew;
7308 // block until acked if removing a fast track
7309 if (cblkOld != NULL) {
7310 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7311 }
7312 didModify = true;
7313 }
jiabin01c8f562018-07-19 17:47:28 -07007314 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7315 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7316 if (state->mFastPatchRecordBufferProvider != abp) {
7317 state->mFastPatchRecordBufferProvider = abp;
7318 state->mFastPatchRecordFormat = fastTrack == 0 ?
7319 AUDIO_FORMAT_INVALID : fastTrack->format();
7320 didModify = true;
7321 }
Eric Laurent33403f02020-05-29 18:35:06 -07007322 if (state->mSilenceCapture != silenceFastCapture) {
7323 state->mSilenceCapture = silenceFastCapture;
7324 didModify = true;
7325 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007326 sq->end(didModify);
7327 if (didModify) {
7328 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007329#if 0
7330 if (kUseFastCapture == FastCapture_Dynamic) {
7331 mNormalSource = mPipeSource;
7332 }
7333#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007334 }
7335 }
7336
Glenn Kasten735f45f2014-08-18 15:51:59 -07007337 // now run the fast track destructor with thread mutex unlocked
7338 fastTrackToRemove.clear();
7339
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007340 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7341 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7342 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7343 // If destination is non-contiguous, first read past the nominal end of buffer, then
7344 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007345
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007346 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007347 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007348 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007349
7350 // If an NBAIO source is present, use it to read the normal capture's data
7351 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007352 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007353
7354 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7355 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7356 // we immediately retry the read() to get data and prevent another overflow.
7357 for (int retries = 0; retries <= 2; ++retries) {
7358 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7359 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7360 framesToRead);
7361 if (framesRead != OVERRUN) break;
7362 }
7363
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007364 const ssize_t availableToRead = mPipeSource->availableToRead();
7365 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007366 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007367 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7368 "more frames to read than fifo size, %zd > %zu",
7369 availableToRead, mPipeFramesP2);
7370 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7371 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7372 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7373 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007374 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7375 }
7376 if (framesRead < 0) {
7377 status_t status = (status_t) framesRead;
7378 switch (status) {
7379 case OVERRUN:
7380 ALOGW("overrun on read from pipe");
7381 framesRead = 0;
7382 break;
7383 case NEGOTIATE:
7384 ALOGE("re-negotiation is needed");
7385 framesRead = -1; // Will cause an attempt to recover.
7386 break;
7387 default:
7388 ALOGE("unknown error %d on read from pipe", status);
7389 break;
7390 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007391 }
7392 // otherwise use the HAL / AudioStreamIn directly
7393 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007394 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007395 size_t bytesRead;
Mikhail Naganovaf288872019-09-25 13:05:02 -07007396 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007397 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007398 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007399 if (result < 0) {
7400 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007401 } else {
7402 framesRead = bytesRead / mFrameSize;
7403 }
7404 }
7405
Andy Hung446f4df2019-02-21 12:26:41 -08007406 const int64_t lastIoEndNs = systemTime(); // end IO timing
7407
Andy Hung3f0c9022016-01-15 17:49:46 -08007408 // Update server timestamp with server stats
7409 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007410 if (framesRead >= 0) {
7411 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7412 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7413 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007414
7415 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007416 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007417 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007418 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007419 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7420 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7421 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganovaf288872019-09-25 13:05:02 -07007422 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007423 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7424
7425 mTimestampVerifier.add(position, time, mSampleRate);
7426
7427 // Correct timestamps
7428 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007429 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007430 id(), (long long)time, (long long)position);
7431 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7432 position = correctedTimestamp.mFrames;
7433 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007434 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007435 id(), (long long)time, (long long)position);
7436 }
7437
Andy Hung3f0c9022016-01-15 17:49:46 -08007438 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7439 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7440 // Note: In general record buffers should tend to be empty in
7441 // a properly running pipeline.
7442 //
7443 // Also, it is not advantageous to call get_presentation_position during the read
7444 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007445 } else {
7446 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007447 }
7448 }
Andy Hunge6c37112019-02-26 17:38:10 -08007449
7450 // From the timestamp, input read latency is negative output write latency.
7451 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7452 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7453 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7454 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7455 mLatencyMs.add(latencyMs);
7456 }
7457
Andy Hung3f0c9022016-01-15 17:49:46 -08007458 // Use this to track timestamp information
7459 // ALOGD("%s", mTimestamp.toString().c_str());
7460
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007461 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007462 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007463 // Force input into standby so that it tries to recover at next read attempt
7464 inputStandBy();
7465 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007466 }
7467 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007468 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007469 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007470 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007471 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007472
Andy Hung8946a282018-04-19 20:04:56 -07007473#ifdef TEE_SINK
7474 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7475#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007476 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007477 {
7478 size_t part1 = mRsmpInFramesP2 - rear;
7479 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007480 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007481 (framesRead - part1) * mFrameSize);
7482 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007483 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007484 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007485
7486 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007487
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007488 // loop over each active track
7489 for (size_t i = 0; i < size; i++) {
7490 activeTrack = activeTracks[i];
7491
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007492 // skip fast tracks, as those are handled directly by FastCapture
7493 if (activeTrack->isFastTrack()) {
7494 continue;
7495 }
7496
Andy Hung73c02e42015-03-29 01:13:58 -07007497 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007498 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7499
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007500 enum {
7501 OVERRUN_UNKNOWN,
7502 OVERRUN_TRUE,
7503 OVERRUN_FALSE
7504 } overrun = OVERRUN_UNKNOWN;
7505
7506 // loop over getNextBuffer to handle circular sink
7507 for (;;) {
7508
7509 activeTrack->mSink.frameCount = ~0;
7510 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7511 size_t framesOut = activeTrack->mSink.frameCount;
7512 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7513
Andy Hung73c02e42015-03-29 01:13:58 -07007514 // check available frames and handle overrun conditions
7515 // if the record track isn't draining fast enough.
7516 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007517 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007518 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7519 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007520 overrun = OVERRUN_TRUE;
7521 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007522 if (framesOut == 0 || framesIn == 0) {
7523 break;
7524 }
7525
Andy Hung6770c6f2015-04-07 13:43:36 -07007526 // Don't allow framesOut to be larger than what is possible with resampling
7527 // from framesIn.
7528 // This isn't strictly necessary but helps limit buffer resizing in
7529 // RecordBufferConverter. TODO: remove when no longer needed.
7530 framesOut = min(framesOut,
7531 destinationFramesPossible(
7532 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007533
7534 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007535 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007536 // straight from RecordThread buffer to RecordTrack buffer.
7537 AudioBufferProvider::Buffer buffer;
7538 buffer.frameCount = framesOut;
7539 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7540 if (status == OK && buffer.frameCount != 0) {
7541 ALOGV_IF(buffer.frameCount != framesOut,
7542 "%s() read less than expected (%zu vs %zu)",
7543 __func__, buffer.frameCount, framesOut);
7544 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007545 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007546 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7547 } else {
7548 framesOut = 0;
7549 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7550 __func__, status, buffer.frameCount);
7551 }
7552 } else {
7553 // process frames from the RecordThread buffer provider to the RecordTrack
7554 // buffer
7555 framesOut = activeTrack->mRecordBufferConverter->convert(
7556 activeTrack->mSink.raw,
7557 activeTrack->mResamplerBufferProvider,
7558 framesOut);
7559 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007560
7561 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7562 overrun = OVERRUN_FALSE;
7563 }
7564
7565 if (activeTrack->mFramesToDrop == 0) {
7566 if (framesOut > 0) {
7567 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007568 // Sanitize before releasing if the track has no access to the source data
7569 // An idle UID receives silence from non virtual devices until active
7570 if (activeTrack->isSilenced()) {
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007571 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007572 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007573 activeTrack->releaseBuffer(&activeTrack->mSink);
7574 }
7575 } else {
7576 // FIXME could do a partial drop of framesOut
7577 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007578 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007579 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007580 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007581 }
7582 } else {
7583 activeTrack->mFramesToDrop += framesOut;
7584 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7585 activeTrack->mSyncStartEvent->isCancelled()) {
7586 ALOGW("Synced record %s, session %d, trigger session %d",
7587 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7588 activeTrack->sessionId(),
7589 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007590 activeTrack->mSyncStartEvent->triggerSession() :
7591 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007592 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007593 }
7594 }
7595 }
7596
7597 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007598 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007599 }
7600 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007601
7602 switch (overrun) {
7603 case OVERRUN_TRUE:
7604 // client isn't retrieving buffers fast enough
7605 if (!activeTrack->setOverflow()) {
7606 nsecs_t now = systemTime();
7607 // FIXME should lastWarning per track?
7608 if ((now - lastWarning) > kWarningThrottleNs) {
7609 ALOGW("RecordThread: buffer overflow");
7610 lastWarning = now;
7611 }
7612 }
7613 break;
7614 case OVERRUN_FALSE:
7615 activeTrack->clearOverflow();
7616 break;
7617 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007618 break;
7619 }
7620
Andy Hung3f0c9022016-01-15 17:49:46 -08007621 // update frame information and push timestamp out
7622 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007623 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007624 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7625 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007626 }
7627
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007628unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007629 // enable changes in effect chain
7630 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007631 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007632 if (audio_has_proportional_frames(mFormat)
7633 && loopCount == lastLoopCountRead + 1) {
7634 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7635 const double jitterMs =
7636 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7637 {framesRead, readPeriodNs},
7638 {0, 0} /* lastTimestamp */, mSampleRate);
7639 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7640
7641 Mutex::Autolock _l(mLock);
7642 mIoJitterMs.add(jitterMs);
7643 mProcessTimeMs.add(processMs);
7644 }
7645 // update timing info.
7646 mLastIoBeginNs = lastIoBeginNs;
7647 mLastIoEndNs = lastIoEndNs;
7648 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007649 }
7650
Glenn Kasten93e471f2013-08-19 08:40:07 -07007651 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007652
7653 {
7654 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007655 for (size_t i = 0; i < mTracks.size(); i++) {
7656 sp<RecordTrack> track = mTracks[i];
7657 track->invalidate();
7658 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007659 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007660 mStartStopCond.broadcast();
7661 }
7662
7663 releaseWakeLock();
7664
7665 ALOGV("RecordThread %p exiting", this);
7666 return false;
7667}
7668
Glenn Kasten93e471f2013-08-19 08:40:07 -07007669void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007670{
7671 if (!mStandby) {
7672 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007673 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007674 mStandby = true;
7675 }
7676}
7677
7678void AudioFlinger::RecordThread::inputStandBy()
7679{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007680 // Idle the fast capture if it's currently running
7681 if (mFastCapture != 0) {
7682 FastCaptureStateQueue *sq = mFastCapture->sq();
7683 FastCaptureState *state = sq->begin();
7684 if (!(state->mCommand & FastCaptureState::IDLE)) {
7685 state->mCommand = FastCaptureState::COLD_IDLE;
7686 state->mColdFutexAddr = &mFastCaptureFutex;
7687 state->mColdGen++;
7688 mFastCaptureFutex = 0;
7689 sq->end();
7690 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7691 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7692#if 0
7693 if (kUseFastCapture == FastCapture_Dynamic) {
7694 // FIXME
7695 }
7696#endif
7697#ifdef AUDIO_WATCHDOG
7698 // FIXME
7699#endif
7700 } else {
7701 sq->end(false /*didModify*/);
7702 }
7703 }
Mikhail Naganovaf288872019-09-25 13:05:02 -07007704 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007705 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007706
7707 // If going into standby, flush the pipe source.
7708 if (mPipeSource.get() != nullptr) {
7709 const ssize_t flushed = mPipeSource->flush();
7710 if (flushed > 0) {
7711 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7712 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7713 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7714 }
7715 }
Eric Laurent81784c32012-11-19 14:55:58 -08007716}
7717
Glenn Kasten05997e22014-03-13 15:08:33 -07007718// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007719sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007720 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007721 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007722 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007723 audio_format_t format,
7724 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007725 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007726 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007727 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007728 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007729 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007730 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007731 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007732 status_t *status,
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007733 audio_port_handle_t portId,
7734 const String16& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08007735{
Glenn Kasten74935e42013-12-19 08:56:45 -08007736 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007737 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007738 sp<RecordTrack> track;
7739 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007740 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007741 audio_input_flags_t requestedFlags = *flags;
7742 uint32_t sampleRate;
7743
7744 lStatus = initCheck();
7745 if (lStatus != NO_ERROR) {
7746 ALOGE("createRecordTrack_l() audio driver not initialized");
7747 goto Exit;
7748 }
7749
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007750 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7751 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7752 lStatus = BAD_VALUE;
7753 goto Exit;
7754 }
7755
Eric Laurentf14db3c2017-12-08 14:20:36 -08007756 if (*pSampleRate == 0) {
7757 *pSampleRate = mSampleRate;
7758 }
7759 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007760
7761 // special case for FAST flag considered OK if fast capture is present
7762 if (hasFastCapture()) {
7763 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7764 }
7765
Eric Laurentf14db3c2017-12-08 14:20:36 -08007766 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007767 if ((*flags & inputFlags) != *flags) {
7768 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7769 " input flags (%08x)",
7770 *flags, inputFlags);
7771 *flags = (audio_input_flags_t)(*flags & inputFlags);
7772 }
Eric Laurent81784c32012-11-19 14:55:58 -08007773
Glenn Kasten90e58b12013-07-31 16:16:02 -07007774 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007775 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007776 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007777 // we formerly checked for a callback handler (non-0 tid),
7778 // but that is no longer required for TRANSFER_OBTAIN mode
7779 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007780 // Frame count is not specified (0), or is less than or equal the pipe depth.
7781 // It is OK to provide a higher capacity than requested.
7782 // We will force it to mPipeFramesP2 below.
7783 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007784 // PCM data
7785 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007786 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007787 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007788 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007789 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007790 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007791 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007792 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007793 hasFastCapture() &&
7794 // there are sufficient fast track slots available
7795 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007796 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007797 // check compatibility with audio effects.
7798 Mutex::Autolock _l(mLock);
7799 // Do not accept FAST flag if the session has software effects
7800 sp<EffectChain> chain = getEffectChain_l(sessionId);
7801 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007802 audio_input_flags_t old = *flags;
7803 chain->checkInputFlagCompatibility(flags);
7804 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007805 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7806 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007807 }
7808 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007809 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007810 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7811 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007812 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007813 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7814 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007815 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007816 this, frameCount, mFrameCount, mPipeFramesP2,
7817 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007818 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007819 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007820 }
7821 }
7822
Eric Laurentf14db3c2017-12-08 14:20:36 -08007823 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7824 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7825 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7826 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7827 lStatus = BAD_TYPE;
7828 goto Exit;
7829 }
7830
Glenn Kasten74105912014-07-03 12:28:53 -07007831 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007832 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007833 // fast track: frame count is exactly the pipe depth
7834 frameCount = mPipeFramesP2;
7835 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007836 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007837 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007838 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7839 // or 20 ms if there is a fast capture
7840 // TODO This could be a roundupRatio inline, and const
7841 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7842 * sampleRate + mSampleRate - 1) / mSampleRate;
7843 // minimum number of notification periods is at least kMinNotifications,
7844 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7845 static const size_t kMinNotifications = 3;
7846 static const uint32_t kMinMs = 30;
7847 // TODO This could be a roundupRatio inline
7848 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7849 // TODO This could be a roundupRatio inline
7850 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7851 maxNotificationFrames;
7852 const size_t minFrameCount = maxNotificationFrames *
7853 max(kMinNotifications, minNotificationsByMs);
7854 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007855 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7856 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007857 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007858 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007859 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007860 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007861
7862 { // scope for mLock
7863 Mutex::Autolock _l(mLock);
7864
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007865 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007866 format, channelMask, frameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007867 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, uid,
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007868 *flags, TrackBase::TYPE_DEFAULT, opPackageName, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007869
Glenn Kasten03003332013-08-06 15:40:54 -07007870 lStatus = track->initCheck();
7871 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007872 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007873 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007874 goto Exit;
7875 }
7876 mTracks.add(track);
7877
Eric Laurent05067782016-06-01 18:27:28 -07007878 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007879 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7880 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7881 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007882 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007883 }
Eric Laurent81784c32012-11-19 14:55:58 -08007884 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007885
Eric Laurent81784c32012-11-19 14:55:58 -08007886 lStatus = NO_ERROR;
7887
7888Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007889 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007890 return track;
7891}
7892
7893status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7894 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007895 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007896{
7897 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7898 sp<ThreadBase> strongMe = this;
7899 status_t status = NO_ERROR;
7900
7901 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007902 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007903 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007904 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007905 triggerSession,
7906 recordTrack->sessionId(),
7907 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007908 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007909 // Sync event can be cancelled by the trigger session if the track is not in a
7910 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007911 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007912 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007913 } else {
7914 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007915 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007916 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007917 }
7918 }
7919
7920 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007921 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007922 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007923 if (recordTrack->isInvalid()) {
7924 recordTrack->clearSyncStartEvent();
Eric Laurent717bc282020-08-21 17:10:39 -07007925 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
7926 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07007927 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007928 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7929 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007930 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7931 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007932 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007933 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007934 } else {
7935 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007936 }
7937 return status;
7938 }
7939
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007940 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7941 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7942 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007943 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007944 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007945 status_t status = NO_ERROR;
7946 if (recordTrack->isExternalTrack()) {
7947 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007948 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007949 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007950 if (recordTrack->isInvalid()) {
7951 recordTrack->clearSyncStartEvent();
7952 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7953 recordTrack->mState = TrackBase::STARTING_2;
7954 // STARTING_2 forces destroy to call stopInput.
7955 }
Eric Laurent717bc282020-08-21 17:10:39 -07007956 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
7957 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07007958 }
7959 if (recordTrack->mState != TrackBase::STARTING_1) {
7960 ALOGW("%s(%d): unsynchronized mState:%d change",
7961 __func__, recordTrack->id(), recordTrack->mState);
7962 // Someone else has changed state, let them take over,
7963 // leave mState in the new state.
7964 recordTrack->clearSyncStartEvent();
7965 return INVALID_OPERATION;
7966 }
7967 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007968 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007969 ALOGW("%s(%d): startInput failed, status %d",
7970 __func__, recordTrack->id(), status);
7971 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7972 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007973 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007974 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007975 return status;
7976 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07007977 sendIoConfigEvent_l(
7978 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08007979 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07007980
7981 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
7982
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007983 // Catch up with current buffer indices if thread is already running.
7984 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7985 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7986 // see previously buffered data before it called start(), but with greater risk of overrun.
7987
Andy Hung73c02e42015-03-29 01:13:58 -07007988 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007989 if (!recordTrack->isDirect()) {
7990 // clear any converter state as new data will be discontinuous
7991 recordTrack->mRecordBufferConverter->reset();
7992 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007993 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007994 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007995 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007996 return status;
7997 }
Eric Laurent81784c32012-11-19 14:55:58 -08007998}
7999
Eric Laurent81784c32012-11-19 14:55:58 -08008000void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8001{
8002 sp<SyncEvent> strongEvent = event.promote();
8003
8004 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008005 sp<RefBase> ptr = strongEvent->cookie().promote();
8006 if (ptr != 0) {
8007 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8008 recordTrack->handleSyncStartEvent(strongEvent);
8009 }
Eric Laurent81784c32012-11-19 14:55:58 -08008010 }
8011}
8012
Glenn Kastena8356f62013-07-25 14:37:52 -07008013bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008014 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008015 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008016 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008017 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008018 return false;
8019 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008020 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008021 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008022
Andy Hungabfab202019-03-07 19:45:54 -08008023 // NOTE: Waiting here is important to keep stop synchronous.
8024 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008025 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8026 mWaitWorkCV.broadcast(); // signal thread to stop
8027 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008028 }
Andy Hungce685402018-10-05 17:23:27 -07008029
8030 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008031 ALOGV("Record stopped OK");
8032 return true;
8033 }
Andy Hungce685402018-10-05 17:23:27 -07008034
8035 // don't handle anything - we've been invalidated or restarted and in a different state
8036 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8037 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008038 return false;
8039}
8040
Glenn Kasten0f11b512014-01-31 16:18:54 -08008041bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008042{
8043 return false;
8044}
8045
Glenn Kasten0f11b512014-01-31 16:18:54 -08008046status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008047{
8048#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8049 if (!isValidSyncEvent(event)) {
8050 return BAD_VALUE;
8051 }
8052
Glenn Kastend848eb42016-03-08 13:42:11 -08008053 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008054 status_t ret = NAME_NOT_FOUND;
8055
8056 Mutex::Autolock _l(mLock);
8057
8058 for (size_t i = 0; i < mTracks.size(); i++) {
8059 sp<RecordTrack> track = mTracks[i];
8060 if (eventSession == track->sessionId()) {
8061 (void) track->setSyncEvent(event);
8062 ret = NO_ERROR;
8063 }
8064 }
8065 return ret;
8066#else
8067 return BAD_VALUE;
8068#endif
8069}
8070
jiabin653cc0a2018-01-17 17:54:10 -08008071status_t AudioFlinger::RecordThread::getActiveMicrophones(
8072 std::vector<media::MicrophoneInfo>* activeMicrophones)
8073{
8074 ALOGV("RecordThread::getActiveMicrophones");
8075 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07008076 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8077 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008078}
8079
Paul McLean12340082019-03-19 09:35:05 -06008080status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8081 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008082{
Paul McLean12340082019-03-19 09:35:05 -06008083 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008084 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008085 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008086}
8087
Paul McLean12340082019-03-19 09:35:05 -06008088status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008089{
Paul McLean12340082019-03-19 09:35:05 -06008090 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008091 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008092 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008093}
8094
Kevin Rocard069c2712018-03-29 19:09:14 -07008095void AudioFlinger::RecordThread::updateMetadata_l()
8096{
8097 if (mInput == nullptr || mInput->stream == nullptr ||
8098 !mActiveTracks.readAndClearHasChanged()) {
8099 return;
8100 }
8101 StreamInHalInterface::SinkMetadata metadata;
8102 for (const sp<RecordTrack> &track : mActiveTracks) {
8103 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent6109cdb2020-11-20 18:41:04 +01008104 record_track_metadata_v7_t trackMetadata;
8105 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008106 .source = track->attributes().source,
8107 .gain = 1, // capture tracks do not have volumes
Eric Laurent6109cdb2020-11-20 18:41:04 +01008108 };
8109 trackMetadata.channel_mask = track->channelMask(),
8110 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8111
8112 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008113 }
8114 mInput->stream->updateSinkMetadata(metadata);
8115}
8116
Eric Laurent81784c32012-11-19 14:55:58 -08008117// destroyTrack_l() must be called with ThreadBase::mLock held
8118void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8119{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008120 track->terminate();
8121 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08008122 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008123 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008124 removeTrack_l(track);
8125 }
8126}
8127
8128void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8129{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008130 String8 result;
8131 track->appendDump(result, false /* active */);
8132 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8133
Eric Laurent81784c32012-11-19 14:55:58 -08008134 mTracks.remove(track);
8135 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008136 if (track->isFastTrack()) {
8137 ALOG_ASSERT(!mFastTrackAvail);
8138 mFastTrackAvail = true;
8139 }
Eric Laurent81784c32012-11-19 14:55:58 -08008140}
8141
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008142void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008143{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008144 AudioStreamIn *input = mInput;
8145 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8146 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008147 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008148 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008149 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008150 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008151 }
Andy Hungbfa64962017-06-12 14:43:19 -07008152
8153 if (input != nullptr) {
8154 dprintf(fd, " Hal stream dump:\n");
8155 (void)input->stream->dump(fd);
8156 }
8157
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008158 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008159 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008160
Glenn Kasten2f90c512015-12-02 11:40:09 -08008161 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8162 // while we are dumping it. It may be inconsistent, but it won't mutate!
8163 // This is a large object so we place it on the heap.
8164 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008165 const std::unique_ptr<FastCaptureDumpState> copy =
8166 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008167 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008168}
8169
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008170void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008171{
Eric Laurent81784c32012-11-19 14:55:58 -08008172 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008173 size_t numtracks = mTracks.size();
8174 size_t numactive = mActiveTracks.size();
8175 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008176 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008177 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008178 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008179 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008180 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008181 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008182 for (size_t i = 0; i < numtracks ; ++i) {
8183 sp<RecordTrack> track = mTracks[i];
8184 if (track != 0) {
8185 bool active = mActiveTracks.indexOf(track) >= 0;
8186 if (active) {
8187 numactiveseen++;
8188 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008189 result.append(prefix);
8190 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008191 }
Eric Laurent81784c32012-11-19 14:55:58 -08008192 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008193 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008194 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008195 }
8196
Marco Nelissenb2208842014-02-07 14:00:50 -08008197 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008198 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008199 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008200 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008201 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008202 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008203 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008204 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008205 result.append(prefix);
8206 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008207 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008208 }
Eric Laurent81784c32012-11-19 14:55:58 -08008209
8210 }
8211 write(fd, result.string(), result.size());
8212}
8213
Eric Laurent5ada82e2019-08-29 17:53:54 -07008214void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008215{
8216 Mutex::Autolock _l(mLock);
8217 for (size_t i = 0; i < mTracks.size() ; i++) {
8218 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008219 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008220 track->setSilenced(silenced);
8221 }
8222 }
8223}
Andy Hung73c02e42015-03-29 01:13:58 -07008224
8225void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8226{
8227 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8228 RecordThread *recordThread = (RecordThread *) threadBase.get();
8229 mRsmpInFront = recordThread->mRsmpInRear;
8230 mRsmpInUnrel = 0;
8231}
8232
8233void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8234 size_t *framesAvailable, bool *hasOverrun)
8235{
8236 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8237 RecordThread *recordThread = (RecordThread *) threadBase.get();
8238 const int32_t rear = recordThread->mRsmpInRear;
8239 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008240 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008241
8242 size_t framesIn;
8243 bool overrun = false;
8244 if (filled < 0) {
8245 // should not happen, but treat like a massive overrun and re-sync
8246 framesIn = 0;
8247 mRsmpInFront = rear;
8248 overrun = true;
8249 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8250 framesIn = (size_t) filled;
8251 } else {
8252 // client is not keeping up with server, but give it latest data
8253 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008254 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8255 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008256 overrun = true;
8257 }
8258 if (framesAvailable != NULL) {
8259 *framesAvailable = framesIn;
8260 }
8261 if (hasOverrun != NULL) {
8262 *hasOverrun = overrun;
8263 }
8264}
8265
Eric Laurent81784c32012-11-19 14:55:58 -08008266// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008267status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008268 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008269{
Andy Hung73c02e42015-03-29 01:13:58 -07008270 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008271 if (threadBase == 0) {
8272 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008273 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008274 return NOT_ENOUGH_DATA;
8275 }
8276 RecordThread *recordThread = (RecordThread *) threadBase.get();
8277 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008278 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008279 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008280 // FIXME should not be P2 (don't want to increase latency)
8281 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008282 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008283 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008284 front &= recordThread->mRsmpInFramesP2 - 1;
8285 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008286 if (part1 > (size_t) filled) {
8287 part1 = filled;
8288 }
8289 size_t ask = buffer->frameCount;
8290 ALOG_ASSERT(ask > 0);
8291 if (part1 > ask) {
8292 part1 = ask;
8293 }
8294 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008295 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008296 buffer->raw = NULL;
8297 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008298 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008299 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008300 }
8301
Andy Hung57446612015-04-19 23:56:46 -07008302 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008303 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008304 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008305 return NO_ERROR;
8306}
8307
8308// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008309void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8310 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008311{
Hongwei Wang95e37682019-04-12 11:13:36 -07008312 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008313 if (stepCount == 0) {
8314 return;
8315 }
Andy Hung73c02e42015-03-29 01:13:58 -07008316 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8317 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008318 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008319 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008320 buffer->frameCount = 0;
8321}
8322
Eric Laurentd8365c52017-07-16 15:27:05 -07008323void AudioFlinger::RecordThread::checkBtNrec()
8324{
8325 Mutex::Autolock _l(mLock);
8326 checkBtNrec_l();
8327}
8328
8329void AudioFlinger::RecordThread::checkBtNrec_l()
8330{
8331 // disable AEC and NS if the device is a BT SCO headset supporting those
8332 // pre processings
jiabin10d86fd2019-10-31 17:20:42 -07008333 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008334 mAudioFlinger->btNrecIsOff();
8335 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8336 for (size_t i = 0; i < mEffectChains.size(); i++) {
8337 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8338 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8339 }
8340 }
8341}
8342
Andy Hung97a893e2015-03-29 01:03:07 -07008343
Eric Laurent10351942014-05-08 18:49:52 -07008344bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8345 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008346{
8347 bool reconfig = false;
8348
Eric Laurent10351942014-05-08 18:49:52 -07008349 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008350
Eric Laurent10351942014-05-08 18:49:52 -07008351 audio_format_t reqFormat = mFormat;
8352 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008353 // 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 -07008354 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8355
8356 AudioParameter param = AudioParameter(keyValuePair);
8357 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008358
8359 // scope for AutoPark extends to end of method
8360 AutoPark<FastCapture> park(mFastCapture);
8361
Eric Laurent10351942014-05-08 18:49:52 -07008362 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8363 // channel count change can be requested. Do we mandate the first client defines the
8364 // HAL sampling rate and channel count or do we allow changes on the fly?
8365 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8366 samplingRate = value;
8367 reconfig = true;
8368 }
8369 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008370 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008371 status = BAD_VALUE;
8372 } else {
8373 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008374 reconfig = true;
8375 }
Eric Laurent10351942014-05-08 18:49:52 -07008376 }
8377 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8378 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008379 if (!audio_is_input_channel(mask) ||
8380 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008381 status = BAD_VALUE;
8382 } else {
8383 channelMask = mask;
8384 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008385 }
Eric Laurent10351942014-05-08 18:49:52 -07008386 }
8387 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8388 // do not accept frame count changes if tracks are open as the track buffer
8389 // size depends on frame count and correct behavior would not be guaranteed
8390 // if frame count is changed after track creation
8391 if (mActiveTracks.size() > 0) {
8392 status = INVALID_OPERATION;
8393 } else {
8394 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008395 }
Eric Laurent10351942014-05-08 18:49:52 -07008396 }
8397 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07008398 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008399 }
8400 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8401 mAudioSource != (audio_source_t)value) {
jiabin10d86fd2019-10-31 17:20:42 -07008402 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008403 }
Glenn Kastene198c362013-08-13 09:13:36 -07008404
Eric Laurent10351942014-05-08 18:49:52 -07008405 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008406 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008407 if (status == INVALID_OPERATION) {
8408 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008409 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008410 }
8411 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008412 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008413 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8414 if (mInput->stream->getAudioProperties(&config) == OK &&
8415 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8416 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8417 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_8) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008418 status = NO_ERROR;
8419 }
Eric Laurent81784c32012-11-19 14:55:58 -08008420 }
Eric Laurent10351942014-05-08 18:49:52 -07008421 if (status == NO_ERROR) {
8422 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008423 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008424 }
8425 }
Eric Laurent81784c32012-11-19 14:55:58 -08008426 }
Eric Laurent10351942014-05-08 18:49:52 -07008427
Eric Laurent81784c32012-11-19 14:55:58 -08008428 return reconfig;
8429}
8430
8431String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8432{
Eric Laurent81784c32012-11-19 14:55:58 -08008433 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008434 if (initCheck() == NO_ERROR) {
8435 String8 out_s8;
8436 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8437 return out_s8;
8438 }
Eric Laurent81784c32012-11-19 14:55:58 -08008439 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008440 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008441}
8442
Eric Laurent09f1ed22019-04-24 17:45:17 -07008443void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8444 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008445 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8446
8447 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008448
8449 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008450 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008451 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008452 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008453 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008454 desc->mChannelMask = mChannelMask;
8455 desc->mSamplingRate = mSampleRate;
8456 desc->mFormat = mFormat;
8457 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008458 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008459 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008460 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008461 case AUDIO_CLIENT_STARTED:
8462 desc->mPatch = mPatch;
8463 desc->mPortId = portId;
8464 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008465 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008466 default:
8467 break;
8468 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008469 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008470}
8471
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008472void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008473{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008474 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8475 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008476 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008477 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8478 if (audio_is_linear_pcm(mFormat)) {
8479 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8480 mChannelCount, FCC_8);
8481 } else {
8482 // Can have more that FCC_8 channels in encoded streams.
8483 ALOGI("HAL format %#x is not linear pcm", mFormat);
8484 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008485 result = mInput->stream->getFrameSize(&mFrameSize);
8486 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008487 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8488 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008489 result = mInput->stream->getBufferSize(&mBufferSize);
8490 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008491 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008492 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8493 "mBufferSize=%zu, mFrameCount=%zu",
8494 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008495 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008496 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
Glenn Kasten85948432013-08-19 12:09:05 -07008497 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008498 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008499 // A larger value should allow more old data to be read after a track calls start(),
8500 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008501 //
8502 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008503 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008504 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008505 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008506 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008507
8508 // TODO optimize audio capture buffer sizes ...
8509 // Here we calculate the size of the sliding buffer used as a source
8510 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8511 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8512 // be better to have it derived from the pipe depth in the long term.
8513 // The current value is higher than necessary. However it should not add to latency.
8514
Glenn Kasten85948432013-08-19 12:09:05 -07008515 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008516 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8517 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008518 // if posix_memalign fails, will segv here.
8519 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008520
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008521 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8522 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008523
8524 audio_input_flags_t flags = mInput->flags;
8525 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8526 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8527 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8528 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8529 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8530 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8531 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8532 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8533 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008534}
8535
Glenn Kasten5f972c02014-01-13 09:59:31 -08008536uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008537{
8538 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008539 uint32_t result;
8540 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8541 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008542 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008543 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008544}
8545
Glenn Kastend848eb42016-03-08 13:42:11 -08008546KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008547{
Glenn Kastend848eb42016-03-08 13:42:11 -08008548 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008549 Mutex::Autolock _l(mLock);
8550 for (size_t j = 0; j < mTracks.size(); ++j) {
8551 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008552 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008553 if (ids.indexOfKey(sessionId) < 0) {
8554 ids.add(sessionId, true);
8555 }
8556 }
8557 return ids;
8558}
8559
8560AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8561{
8562 Mutex::Autolock _l(mLock);
8563 AudioStreamIn *input = mInput;
8564 mInput = NULL;
8565 return input;
8566}
8567
8568// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008569sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008570{
8571 if (mInput == NULL) {
8572 return NULL;
8573 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008574 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008575}
8576
8577status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8578{
Eric Laurent81784c32012-11-19 14:55:58 -08008579 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008580 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008581 chain->setInBuffer(NULL);
8582 chain->setOutBuffer(NULL);
8583
8584 checkSuspendOnAddEffectChain_l(chain);
8585
Eric Laurent1b928682014-10-02 19:41:47 -07008586 // make sure enabled pre processing effects state is communicated to the HAL as we
8587 // just moved them to a new input stream.
8588 chain->syncHalEffectsState();
8589
Eric Laurent81784c32012-11-19 14:55:58 -08008590 mEffectChains.add(chain);
8591
8592 return NO_ERROR;
8593}
8594
8595size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8596{
8597 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008598
8599 for (size_t i = 0; i < mEffectChains.size(); i++) {
8600 if (chain == mEffectChains[i]) {
8601 mEffectChains.removeAt(i);
8602 break;
8603 }
Eric Laurent81784c32012-11-19 14:55:58 -08008604 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008605 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008606}
8607
Eric Laurent1c333e22014-05-20 10:48:17 -07008608status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8609 audio_patch_handle_t *handle)
8610{
8611 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008612
8613 // store new device and send to effects
jiabin10d86fd2019-10-31 17:20:42 -07008614 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin4e826212020-08-07 17:32:40 -07008615 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008616 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008617 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08008618 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008619 }
8620
Eric Laurentd8365c52017-07-16 15:27:05 -07008621 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008622
8623 // store new source and send to effects
8624 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8625 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008626 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008627 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008628 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008629 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008630
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008631 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008632 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8633 status = hwDevice->createAudioPatch(patch->num_sources,
8634 patch->sources,
8635 patch->num_sinks,
8636 patch->sinks,
8637 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008638 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008639 char *address;
8640 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8641 address = audio_device_address_to_parameter(
8642 patch->sources[0].ext.device.type,
8643 patch->sources[0].ext.device.address);
8644 } else {
8645 address = (char *)calloc(1, 1);
8646 }
8647 AudioParameter param = AudioParameter(String8(address));
8648 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008649 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008650 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008651 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008652 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008653 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008654 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008655 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008656
jiabin10d86fd2019-10-31 17:20:42 -07008657 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008658 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabin10d86fd2019-10-31 17:20:42 -07008659 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008660 }
Eric Laurent296fb132015-05-01 11:38:42 -07008661
Andy Hungc2b11cb2020-04-22 09:04:01 -07008662 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008663 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008664 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008665 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008666 // also dispatch to active AudioRecords
8667 for (const auto &track : mActiveTracks) {
8668 track->logEndInterval();
8669 track->logBeginInterval(pathSourcesAsString);
8670 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008671 return status;
8672}
8673
8674status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8675{
8676 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008677
jiabin10d86fd2019-10-31 17:20:42 -07008678 mPatch = audio_patch{};
8679 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008680
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008681 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008682 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8683 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008684 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008685 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008686 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008687 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008688 }
8689 return status;
8690}
8691
jiabin10d86fd2019-10-31 17:20:42 -07008692void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8693{
wendy lin56aa82b2020-12-02 15:19:55 +08008694 Mutex::Autolock _l(mLock);
jiabin10d86fd2019-10-31 17:20:42 -07008695 mOutDevices = outDevices;
8696 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8697 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08008698 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabin10d86fd2019-10-31 17:20:42 -07008699 }
8700}
8701
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008702void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008703{
8704 Mutex::Autolock _l(mLock);
8705 mTracks.add(record);
Mikhail Naganovaf288872019-09-25 13:05:02 -07008706 if (record->getSource()) {
8707 mSource = record->getSource();
8708 }
Eric Laurent83b88082014-06-20 18:31:16 -07008709}
8710
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008711void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008712{
8713 Mutex::Autolock _l(mLock);
Mikhail Naganovaf288872019-09-25 13:05:02 -07008714 if (mSource == record->getSource()) {
8715 mSource = mInput;
8716 }
Eric Laurent83b88082014-06-20 18:31:16 -07008717 destroyTrack_l(record);
8718}
8719
Mikhail Naganovdc769682018-05-04 15:34:08 -07008720void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008721{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008722 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008723 config->role = AUDIO_PORT_ROLE_SINK;
8724 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8725 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008726 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8727 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8728 config->flags.input = mInput->flags;
8729 }
Eric Laurent83b88082014-06-20 18:31:16 -07008730}
Eric Laurent1c333e22014-05-20 10:48:17 -07008731
Eric Laurent6acd1d42017-01-04 14:23:29 -08008732// ----------------------------------------------------------------------------
8733// Mmap
8734// ----------------------------------------------------------------------------
8735
8736AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8737 : mThread(thread)
8738{
Phil Burk9fabbf82017-08-03 12:02:00 -07008739 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008740}
8741
8742AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8743{
Phil Burk9fabbf82017-08-03 12:02:00 -07008744 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008745}
8746
8747status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8748 struct audio_mmap_buffer_info *info)
8749{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008750 return mThread->createMmapBuffer(minSizeFrames, info);
8751}
8752
8753status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8754{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008755 return mThread->getMmapPosition(position);
8756}
8757
Eric Laurenta54f1282017-07-01 19:39:32 -07008758status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008759 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008760
8761{
jiabind1f1cb62020-03-24 11:57:57 -07008762 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008763}
8764
8765status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8766{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008767 return mThread->stop(handle);
8768}
8769
Eric Laurent18b57012017-02-13 16:23:52 -08008770status_t AudioFlinger::MmapThreadHandle::standby()
8771{
Eric Laurent18b57012017-02-13 16:23:52 -08008772 return mThread->standby();
8773}
8774
Eric Laurent6acd1d42017-01-04 14:23:29 -08008775
8776AudioFlinger::MmapThread::MmapThread(
8777 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07008778 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07008779 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008780 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008781 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008782 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008783 mActiveTracks(&this->mLocalLog),
8784 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8785 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008786{
Eric Laurent18b57012017-02-13 16:23:52 -08008787 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008788 readHalParameters_l();
8789}
8790
8791AudioFlinger::MmapThread::~MmapThread()
8792{
Eric Laurent18b57012017-02-13 16:23:52 -08008793 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008794}
8795
8796void AudioFlinger::MmapThread::onFirstRef()
8797{
8798 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8799}
8800
8801void AudioFlinger::MmapThread::disconnect()
8802{
Eric Laurent331679c2018-04-16 17:03:16 -07008803 ActiveTracks<MmapTrack> activeTracks;
8804 {
8805 Mutex::Autolock _l(mLock);
8806 for (const sp<MmapTrack> &t : mActiveTracks) {
8807 activeTracks.add(t);
8808 }
8809 }
8810 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008811 stop(t->portId());
8812 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008813 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008814 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008815 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008816 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008817 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008818 }
8819}
8820
8821
8822void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8823 audio_stream_type_t streamType __unused,
8824 audio_session_t sessionId,
8825 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008826 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008827 audio_port_handle_t portId)
8828{
8829 mAttr = *attr;
8830 mSessionId = sessionId;
8831 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008832 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008833 mPortId = portId;
8834}
8835
8836status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8837 struct audio_mmap_buffer_info *info)
8838{
8839 if (mHalStream == 0) {
8840 return NO_INIT;
8841 }
Eric Laurent18b57012017-02-13 16:23:52 -08008842 mStandby = true;
8843 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008844 return mHalStream->createMmapBuffer(minSizeFrames, info);
8845}
8846
8847status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8848{
8849 if (mHalStream == 0) {
8850 return NO_INIT;
8851 }
8852 return mHalStream->getMmapPosition(position);
8853}
8854
Eric Laurent331679c2018-04-16 17:03:16 -07008855status_t AudioFlinger::MmapThread::exitStandby()
8856{
8857 status_t ret = mHalStream->start();
8858 if (ret != NO_ERROR) {
8859 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8860 return ret;
8861 }
Andy Hungcf10d742020-04-28 15:38:24 -07008862 if (mStandby) {
8863 mThreadMetrics.logBeginInterval();
8864 mStandby = false;
8865 }
Eric Laurent331679c2018-04-16 17:03:16 -07008866 return NO_ERROR;
8867}
8868
Eric Laurenta54f1282017-07-01 19:39:32 -07008869status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008870 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008871 audio_port_handle_t *handle)
8872{
Eric Laurenta54f1282017-07-01 19:39:32 -07008873 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8874 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008875 if (mHalStream == 0) {
8876 return NO_INIT;
8877 }
8878
8879 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008880
Eric Laurenta54f1282017-07-01 19:39:32 -07008881 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008882 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008883 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008884 }
8885
8886 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8887
8888 audio_io_handle_t io = mId;
8889 if (isOutput()) {
8890 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8891 config.sample_rate = mSampleRate;
8892 config.channel_mask = mChannelMask;
8893 config.format = mFormat;
8894 audio_stream_type_t stream = streamType();
8895 audio_output_flags_t flags =
8896 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008897 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008898 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008899 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8900 mSessionId,
8901 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008902 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008903 client.clientUid,
8904 &config,
8905 flags,
8906 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008907 &portId,
8908 &secondaryOutputs);
8909 ALOGD_IF(!secondaryOutputs.empty(),
8910 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008911 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008912 audio_config_base_t config;
8913 config.sample_rate = mSampleRate;
8914 config.channel_mask = mChannelMask;
8915 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008916 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008917 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07008918 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07008919 mSessionId,
8920 client.clientPid,
8921 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008922 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008923 &config,
8924 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8925 &deviceId,
8926 &portId);
8927 }
8928 // APM should not chose a different input or output stream for the same set of attributes
8929 // and audo configuration
8930 if (ret != NO_ERROR || io != mId) {
8931 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8932 __FUNCTION__, ret, io, mId);
8933 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008934 }
8935
8936 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008937 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008938 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008939 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008940 }
8941
Eric Laurent331679c2018-04-16 17:03:16 -07008942 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008943 // abort if start is rejected by audio policy manager
8944 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008945 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008946 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008947 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008948 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008949 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008950 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008951 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008952 }
Eric Laurent331679c2018-04-16 17:03:16 -07008953 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008954 } else {
8955 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008956 }
8957 return PERMISSION_DENIED;
8958 }
8959
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008960 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07008961 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
8962 mChannelMask, mSessionId, isOutput(), client.clientUid,
8963 client.clientPid, IPCThreadState::self()->getCallingPid(),
8964 portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008965
Eric Laurent4eb58f12018-12-07 16:41:02 -08008966 if (isOutput()) {
8967 // force volume update when a new track is added
8968 mHalVolFloat = -1.0f;
8969 } else if (!track->isSilenced_l()) {
8970 for (const sp<MmapTrack> &t : mActiveTracks) {
8971 if (t->isSilenced_l() && t->uid() != client.clientUid)
8972 t->invalidate();
8973 }
8974 }
8975
8976
Eric Laurent6acd1d42017-01-04 14:23:29 -08008977 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008978 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008979 if (chain != 0) {
8980 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8981 chain->incTrackCnt();
8982 chain->incActiveTrackCnt();
8983 }
8984
Andy Hungc2b11cb2020-04-22 09:04:01 -07008985 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08008986 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008987 broadcast_l();
8988
Eric Laurenta54f1282017-07-01 19:39:32 -07008989 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008990
8991 return NO_ERROR;
8992}
8993
8994status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8995{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008996 ALOGV("%s handle %d", __FUNCTION__, handle);
8997
8998 if (mHalStream == 0) {
8999 return NO_INIT;
9000 }
9001
Eric Laurenta54f1282017-07-01 19:39:32 -07009002 if (handle == mPortId) {
9003 mHalStream->stop();
9004 return NO_ERROR;
9005 }
9006
Eric Laurent331679c2018-04-16 17:03:16 -07009007 Mutex::Autolock _l(mLock);
9008
Eric Laurent6acd1d42017-01-04 14:23:29 -08009009 sp<MmapTrack> track;
9010 for (const sp<MmapTrack> &t : mActiveTracks) {
9011 if (handle == t->portId()) {
9012 track = t;
9013 break;
9014 }
9015 }
9016 if (track == 0) {
9017 return BAD_VALUE;
9018 }
9019
9020 mActiveTracks.remove(track);
9021
Eric Laurent331679c2018-04-16 17:03:16 -07009022 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009023 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009024 AudioSystem::stopOutput(track->portId());
9025 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009026 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009027 AudioSystem::stopInput(track->portId());
9028 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009029 }
Eric Laurent331679c2018-04-16 17:03:16 -07009030 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009031
9032 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9033 if (chain != 0) {
9034 chain->decActiveTrackCnt();
9035 chain->decTrackCnt();
9036 }
9037
9038 broadcast_l();
9039
Eric Laurent6acd1d42017-01-04 14:23:29 -08009040 return NO_ERROR;
9041}
9042
Eric Laurent18b57012017-02-13 16:23:52 -08009043status_t AudioFlinger::MmapThread::standby()
9044{
9045 ALOGV("%s", __FUNCTION__);
9046
9047 if (mHalStream == 0) {
9048 return NO_INIT;
9049 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009050 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009051 return INVALID_OPERATION;
9052 }
9053 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009054 if (!mStandby) {
9055 mThreadMetrics.logEndInterval();
9056 mStandby = true;
9057 }
Eric Laurent18b57012017-02-13 16:23:52 -08009058 releaseWakeLock();
9059 return NO_ERROR;
9060}
9061
Eric Laurent6acd1d42017-01-04 14:23:29 -08009062
9063void AudioFlinger::MmapThread::readHalParameters_l()
9064{
9065 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9066 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9067 mFormat = mHALFormat;
9068 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9069 result = mHalStream->getFrameSize(&mFrameSize);
9070 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009071 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9072 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009073 result = mHalStream->getBufferSize(&mBufferSize);
9074 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9075 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009076
Andy Hungcf10d742020-04-28 15:38:24 -07009077 // TODO: make a readHalParameters call?
9078 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009079 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9080 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9081 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9082 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9083 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9084 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9085 /*
9086 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9087 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9088 (int32_t)mHapticChannelMask)
9089 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9090 (int32_t)mHapticChannelCount)
9091 */
9092 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9093 formatToString(mHALFormat).c_str())
9094 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9095 (int32_t)mFrameCount) // sic - added HAL
9096 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009097}
9098
9099bool AudioFlinger::MmapThread::threadLoop()
9100{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009101 checkSilentMode_l();
9102
9103 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9104
9105 while (!exitPending())
9106 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009107 Vector< sp<EffectChain> > effectChains;
9108
Andy Hung13850be2019-03-14 11:33:09 -07009109 { // under Thread lock
9110 Mutex::Autolock _l(mLock);
9111
Eric Laurent6acd1d42017-01-04 14:23:29 -08009112 if (mSignalPending) {
9113 // A signal was raised while we were unlocked
9114 mSignalPending = false;
9115 } else {
9116 if (mConfigEvents.isEmpty()) {
9117 // we're about to wait, flush the binder command buffer
9118 IPCThreadState::self()->flushCommands();
9119
9120 if (exitPending()) {
9121 break;
9122 }
9123
Eric Laurent6acd1d42017-01-04 14:23:29 -08009124 // wait until we have something to do...
9125 ALOGV("%s going to sleep", myName.string());
9126 mWaitWorkCV.wait(mLock);
9127 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009128
9129 checkSilentMode_l();
9130
9131 continue;
9132 }
9133 }
9134
9135 processConfigEvents_l();
9136
9137 processVolume_l();
9138
9139 checkInvalidTracks_l();
9140
9141 mActiveTracks.updatePowerState(this);
9142
Kevin Rocard069c2712018-03-29 19:09:14 -07009143 updateMetadata_l();
9144
Eric Laurent6acd1d42017-01-04 14:23:29 -08009145 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009146 } // release Thread lock
9147
Eric Laurent6acd1d42017-01-04 14:23:29 -08009148 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009149 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009150 }
Andy Hung13850be2019-03-14 11:33:09 -07009151
9152 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009153 unlockEffectChains(effectChains);
9154 // Effect chains will be actually deleted here if they were removed from
9155 // mEffectChains list during mixing or effects processing
9156 }
9157
9158 threadLoop_exit();
9159
9160 if (!mStandby) {
9161 threadLoop_standby();
9162 mStandby = true;
9163 }
9164
Eric Laurent6acd1d42017-01-04 14:23:29 -08009165 ALOGV("Thread %p type %d exiting", this, mType);
9166 return false;
9167}
9168
9169// checkForNewParameter_l() must be called with ThreadBase::mLock held
9170bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9171 status_t& status)
9172{
9173 AudioParameter param = AudioParameter(keyValuePair);
9174 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009175 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009176 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07009177 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009178 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009179 if (sendToHal) {
9180 status = mHalStream->setParameters(keyValuePair);
9181 } else {
9182 status = NO_ERROR;
9183 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009184
9185 return false;
9186}
9187
9188String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9189{
9190 Mutex::Autolock _l(mLock);
9191 String8 out_s8;
9192 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9193 return out_s8;
9194 }
9195 return String8();
9196}
9197
Eric Laurent09f1ed22019-04-24 17:45:17 -07009198void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9199 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009200 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9201
9202 desc->mIoHandle = mId;
9203
9204 switch (event) {
9205 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009206 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009207 case AUDIO_INPUT_CONFIG_CHANGED:
9208 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009209 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009210 case AUDIO_OUTPUT_CONFIG_CHANGED:
9211 desc->mPatch = mPatch;
9212 desc->mChannelMask = mChannelMask;
9213 desc->mSamplingRate = mSampleRate;
9214 desc->mFormat = mFormat;
9215 desc->mFrameCount = mFrameCount;
9216 desc->mFrameCountHAL = mFrameCount;
9217 desc->mLatency = 0;
9218 break;
9219
9220 case AUDIO_INPUT_CLOSED:
9221 case AUDIO_OUTPUT_CLOSED:
9222 default:
9223 break;
9224 }
9225 mAudioFlinger->ioConfigChanged(event, desc, pid);
9226}
9227
9228status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9229 audio_patch_handle_t *handle)
9230{
9231 status_t status = NO_ERROR;
9232
9233 // store new device and send to effects
9234 audio_devices_t type = AUDIO_DEVICE_NONE;
9235 audio_port_handle_t deviceId;
jiabin10d86fd2019-10-31 17:20:42 -07009236 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9237 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9238 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009239 if (isOutput()) {
9240 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabin10d86fd2019-10-31 17:20:42 -07009241 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9242 && !mAudioHwDev->supportsAudioPatches(),
9243 "Enumerated device type(%#x) must not be used "
9244 "as it does not support audio patches",
9245 patch->sinks[i].ext.device.type);
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07009246 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabin10d86fd2019-10-31 17:20:42 -07009247 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9248 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009249 }
9250 deviceId = patch->sinks[0].id;
jiabin10d86fd2019-10-31 17:20:42 -07009251 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009252 } else {
9253 type = patch->sources[0].ext.device.type;
9254 deviceId = patch->sources[0].id;
jiabin10d86fd2019-10-31 17:20:42 -07009255 numDevices = mPatch.num_sources;
9256 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin4e826212020-08-07 17:32:40 -07009257 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009258 }
9259
9260 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08009261 if (isOutput()) {
9262 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9263 } else {
9264 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9265 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009266 }
9267
jiabin10d86fd2019-10-31 17:20:42 -07009268 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009269 // store new source and send to effects
9270 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9271 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9272 for (size_t i = 0; i < mEffectChains.size(); i++) {
9273 mEffectChains[i]->setAudioSource_l(mAudioSource);
9274 }
9275 }
9276 }
9277
9278 if (mAudioHwDev->supportsAudioPatches()) {
9279 status = mHalDevice->createAudioPatch(patch->num_sources,
9280 patch->sources,
9281 patch->num_sinks,
9282 patch->sinks,
9283 handle);
9284 } else {
9285 char *address;
9286 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9287 //FIXME: we only support address on first sink with HAL version < 3.0
9288 address = audio_device_address_to_parameter(
9289 patch->sinks[0].ext.device.type,
9290 patch->sinks[0].ext.device.address);
9291 } else {
9292 address = (char *)calloc(1, 1);
9293 }
9294 AudioParameter param = AudioParameter(String8(address));
9295 free(address);
9296 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9297 if (!isOutput()) {
9298 param.addInt(String8(AudioParameter::keyInputSource),
9299 (int)patch->sinks[0].ext.mix.usecase.source);
9300 }
9301 status = mHalStream->setParameters(param.toString());
9302 *handle = AUDIO_PATCH_HANDLE_NONE;
9303 }
9304
jiabin10d86fd2019-10-31 17:20:42 -07009305 if (numDevices == 0 || mDeviceId != deviceId) {
9306 if (isOutput()) {
9307 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9308 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009309 checkSilentMode_l();
jiabin10d86fd2019-10-31 17:20:42 -07009310 } else {
9311 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9312 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9313 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009314 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009315 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009316 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009317 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009318 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009319 }
jiabin10d86fd2019-10-31 17:20:42 -07009320 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009321 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009322 }
9323 return status;
9324}
9325
9326status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9327{
9328 status_t status = NO_ERROR;
9329
jiabin10d86fd2019-10-31 17:20:42 -07009330 mPatch = audio_patch{};
9331 mOutDeviceTypeAddrs.clear();
9332 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009333
9334 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9335 supportsAudioPatches : false;
9336
9337 if (supportsAudioPatches) {
9338 status = mHalDevice->releaseAudioPatch(handle);
9339 } else {
9340 AudioParameter param;
9341 param.addInt(String8(AudioParameter::keyRouting), 0);
9342 status = mHalStream->setParameters(param.toString());
9343 }
9344 return status;
9345}
9346
Mikhail Naganovdc769682018-05-04 15:34:08 -07009347void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009348{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009349 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009350 if (isOutput()) {
9351 config->role = AUDIO_PORT_ROLE_SOURCE;
9352 config->ext.mix.hw_module = mAudioHwDev->handle();
9353 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9354 } else {
9355 config->role = AUDIO_PORT_ROLE_SINK;
9356 config->ext.mix.hw_module = mAudioHwDev->handle();
9357 config->ext.mix.usecase.source = mAudioSource;
9358 }
9359}
9360
9361status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9362{
9363 audio_session_t session = chain->sessionId();
9364
9365 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9366 // Attach all tracks with same session ID to this chain.
9367 // indicate all active tracks in the chain
9368 for (const sp<MmapTrack> &track : mActiveTracks) {
9369 if (session == track->sessionId()) {
9370 chain->incTrackCnt();
9371 chain->incActiveTrackCnt();
9372 }
9373 }
9374
9375 chain->setThread(this);
9376 chain->setInBuffer(nullptr);
9377 chain->setOutBuffer(nullptr);
9378 chain->syncHalEffectsState();
9379
9380 mEffectChains.add(chain);
9381 checkSuspendOnAddEffectChain_l(chain);
9382 return NO_ERROR;
9383}
9384
9385size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9386{
9387 audio_session_t session = chain->sessionId();
9388
9389 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9390
9391 for (size_t i = 0; i < mEffectChains.size(); i++) {
9392 if (chain == mEffectChains[i]) {
9393 mEffectChains.removeAt(i);
9394 // detach all active tracks from the chain
9395 // detach all tracks with same session ID from this chain
9396 for (const sp<MmapTrack> &track : mActiveTracks) {
9397 if (session == track->sessionId()) {
9398 chain->decActiveTrackCnt();
9399 chain->decTrackCnt();
9400 }
9401 }
9402 break;
9403 }
9404 }
9405 return mEffectChains.size();
9406}
9407
Eric Laurent6acd1d42017-01-04 14:23:29 -08009408void AudioFlinger::MmapThread::threadLoop_standby()
9409{
9410 mHalStream->standby();
9411}
9412
9413void AudioFlinger::MmapThread::threadLoop_exit()
9414{
Phil Burk7dce7282017-09-27 13:51:41 -07009415 // Do not call callback->onTearDown() because it is redundant for thread exit
9416 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009417}
9418
9419status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9420{
9421 return BAD_VALUE;
9422}
9423
9424bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9425{
9426 return false;
9427}
9428
9429status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9430 const effect_descriptor_t *desc, audio_session_t sessionId)
9431{
9432 // No global effect sessions on mmap threads
Eric Laurenta20c4e92019-11-12 15:55:51 -08009433 if (audio_is_global_session(sessionId)) {
9434 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009435 desc->name, mThreadName);
9436 return BAD_VALUE;
9437 }
9438
9439 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9440 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9441 desc->name);
9442 return BAD_VALUE;
9443 }
9444 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009445 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9446 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009447 return BAD_VALUE;
9448 }
9449
9450 // Only allow effects without processing load or latency
9451 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9452 return BAD_VALUE;
9453 }
9454
9455 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009456}
9457
9458void AudioFlinger::MmapThread::checkInvalidTracks_l()
9459{
9460 for (const sp<MmapTrack> &track : mActiveTracks) {
9461 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009462 sp<MmapStreamCallback> callback = mCallback.promote();
9463 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009464 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009465 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009466 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009467 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9468 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9469 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009470 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009471 }
9472 }
9473}
9474
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009475void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009476{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009477 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9478 mAttr.content_type, mAttr.usage, mAttr.source);
9479 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009480 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009481 dprintf(fd, " No active clients\n");
9482 }
9483}
9484
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009485void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009486{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009487 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009488 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009489 dprintf(fd, " %zu Tracks\n", numtracks);
9490 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009491 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009492 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009493 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009494 for (size_t i = 0; i < numtracks ; ++i) {
9495 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009496 result.append(prefix);
9497 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009498 }
9499 } else {
9500 dprintf(fd, "\n");
9501 }
9502 write(fd, result.string(), result.size());
9503}
9504
9505AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9506 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -07009507 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009508 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009509 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009510 mStreamVolume(1.0),
9511 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009512 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009513{
9514 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9515 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9516 mMasterVolume = audioFlinger->masterVolume_l();
9517 mMasterMute = audioFlinger->masterMute_l();
9518 if (mAudioHwDev) {
9519 if (mAudioHwDev->canSetMasterVolume()) {
9520 mMasterVolume = 1.0;
9521 }
9522
9523 if (mAudioHwDev->canSetMasterMute()) {
9524 mMasterMute = false;
9525 }
9526 }
9527}
9528
9529void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9530 audio_stream_type_t streamType,
9531 audio_session_t sessionId,
9532 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009533 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009534 audio_port_handle_t portId)
9535{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009536 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009537 mStreamType = streamType;
9538}
9539
9540AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9541{
9542 Mutex::Autolock _l(mLock);
9543 AudioStreamOut *output = mOutput;
9544 mOutput = NULL;
9545 return output;
9546}
9547
9548void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9549{
9550 Mutex::Autolock _l(mLock);
9551 // Don't apply master volume in SW if our HAL can do it for us.
9552 if (mAudioHwDev &&
9553 mAudioHwDev->canSetMasterVolume()) {
9554 mMasterVolume = 1.0;
9555 } else {
9556 mMasterVolume = value;
9557 }
9558}
9559
9560void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9561{
9562 Mutex::Autolock _l(mLock);
9563 // Don't apply master mute in SW if our HAL can do it for us.
9564 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9565 mMasterMute = false;
9566 } else {
9567 mMasterMute = muted;
9568 }
9569}
9570
9571void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9572{
9573 Mutex::Autolock _l(mLock);
9574 if (stream == mStreamType) {
9575 mStreamVolume = value;
9576 broadcast_l();
9577 }
9578}
9579
9580float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9581{
9582 Mutex::Autolock _l(mLock);
9583 if (stream == mStreamType) {
9584 return mStreamVolume;
9585 }
9586 return 0.0f;
9587}
9588
9589void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9590{
9591 Mutex::Autolock _l(mLock);
9592 if (stream == mStreamType) {
9593 mStreamMute= muted;
9594 broadcast_l();
9595 }
9596}
9597
9598void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9599{
9600 Mutex::Autolock _l(mLock);
9601 if (streamType == mStreamType) {
9602 for (const sp<MmapTrack> &track : mActiveTracks) {
9603 track->invalidate();
9604 }
9605 broadcast_l();
9606 }
9607}
9608
9609void AudioFlinger::MmapPlaybackThread::processVolume_l()
9610{
9611 float volume;
9612
9613 if (mMasterMute || mStreamMute) {
9614 volume = 0;
9615 } else {
9616 volume = mMasterVolume * mStreamVolume;
9617 }
9618
9619 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009620
9621 // Convert volumes from float to 8.24
9622 uint32_t vol = (uint32_t)(volume * (1 << 24));
9623
9624 // Delegate volume control to effect in track effect chain if needed
9625 // only one effect chain can be present on DirectOutputThread, so if
9626 // there is one, the track is connected to it
9627 if (!mEffectChains.isEmpty()) {
9628 mEffectChains[0]->setVolume_l(&vol, &vol);
9629 volume = (float)vol / (1 << 24);
9630 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009631 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009632 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9633 mHalVolFloat = volume; // HW volume control worked, so update value.
9634 mNoCallbackWarningCount = 0;
9635 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009636 sp<MmapStreamCallback> callback = mCallback.promote();
9637 if (callback != 0) {
9638 int channelCount;
9639 if (isOutput()) {
9640 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9641 } else {
9642 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9643 }
9644 Vector<float> values;
9645 for (int i = 0; i < channelCount; i++) {
9646 values.add(volume);
9647 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009648 mHalVolFloat = volume; // SW volume control worked, so update value.
9649 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009650 mLock.unlock();
9651 callback->onVolumeChanged(mChannelMask, values);
9652 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009653 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009654 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9655 ALOGW("Could not set MMAP stream volume: no volume callback!");
9656 mNoCallbackWarningCount++;
9657 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009658 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009659 }
9660 }
9661}
9662
Kevin Rocard069c2712018-03-29 19:09:14 -07009663void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9664{
9665 if (mOutput == nullptr || mOutput->stream == nullptr ||
9666 !mActiveTracks.readAndClearHasChanged()) {
9667 return;
9668 }
9669 StreamOutHalInterface::SourceMetadata metadata;
9670 for (const sp<MmapTrack> &track : mActiveTracks) {
9671 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent6109cdb2020-11-20 18:41:04 +01009672 playback_track_metadata_v7_t trackMetadata;
9673 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009674 .usage = track->attributes().usage,
9675 .content_type = track->attributes().content_type,
9676 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent6109cdb2020-11-20 18:41:04 +01009677 };
9678 trackMetadata.channel_mask = track->channelMask(),
9679 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9680 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009681 }
9682 mOutput->stream->updateSourceMetadata(metadata);
9683}
9684
Eric Laurent6acd1d42017-01-04 14:23:29 -08009685void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9686{
9687 if (!mMasterMute) {
9688 char value[PROPERTY_VALUE_MAX];
9689 if (property_get("ro.audio.silent", value, "0") > 0) {
9690 char *endptr;
9691 unsigned long ul = strtoul(value, &endptr, 0);
9692 if (*endptr == '\0' && ul != 0) {
9693 ALOGD("Silence is golden");
9694 // The setprop command will not allow a property to be changed after
9695 // the first time it is set, so we don't have to worry about un-muting.
9696 setMasterMute_l(true);
9697 }
9698 }
9699 }
9700}
9701
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009702void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9703{
9704 MmapThread::toAudioPortConfig(config);
9705 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9706 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9707 config->flags.output = mOutput->flags;
9708 }
9709}
9710
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009711void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009712{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009713 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009714
Glenn Kastend3bb6452016-12-05 18:14:37 -08009715 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9716 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009717 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9718}
9719
9720AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9721 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -07009722 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009723 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009724 mInput(input)
9725{
9726 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9727 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9728}
9729
Eric Laurent331679c2018-04-16 17:03:16 -07009730status_t AudioFlinger::MmapCaptureThread::exitStandby()
9731{
Phil Burkf054fc32018-12-06 09:45:59 -08009732 {
9733 // mInput might have been cleared by clearInput()
9734 Mutex::Autolock _l(mLock);
9735 if (mInput != nullptr && mInput->stream != nullptr) {
9736 mInput->stream->setGain(1.0f);
9737 }
9738 }
Eric Laurent331679c2018-04-16 17:03:16 -07009739 return MmapThread::exitStandby();
9740}
9741
Eric Laurent6acd1d42017-01-04 14:23:29 -08009742AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9743{
9744 Mutex::Autolock _l(mLock);
9745 AudioStreamIn *input = mInput;
9746 mInput = NULL;
9747 return input;
9748}
Kevin Rocard069c2712018-03-29 19:09:14 -07009749
Eric Laurent331679c2018-04-16 17:03:16 -07009750
9751void AudioFlinger::MmapCaptureThread::processVolume_l()
9752{
9753 bool changed = false;
9754 bool silenced = false;
9755
9756 sp<MmapStreamCallback> callback = mCallback.promote();
9757 if (callback == 0) {
9758 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9759 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9760 mNoCallbackWarningCount++;
9761 }
9762 }
9763
9764 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9765 // track is silenced and unmute otherwise
9766 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9767 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9768 changed = true;
9769 silenced = mActiveTracks[i]->isSilenced_l();
9770 }
9771 }
9772
9773 if (changed) {
9774 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9775 }
9776}
9777
Kevin Rocard069c2712018-03-29 19:09:14 -07009778void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9779{
9780 if (mInput == nullptr || mInput->stream == nullptr ||
9781 !mActiveTracks.readAndClearHasChanged()) {
9782 return;
9783 }
9784 StreamInHalInterface::SinkMetadata metadata;
9785 for (const sp<MmapTrack> &track : mActiveTracks) {
9786 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent6109cdb2020-11-20 18:41:04 +01009787 record_track_metadata_v7_t trackMetadata;
9788 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009789 .source = track->attributes().source,
9790 .gain = 1, // capture tracks do not have volumes
Eric Laurent6109cdb2020-11-20 18:41:04 +01009791 };
9792 trackMetadata.channel_mask = track->channelMask(),
9793 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9794 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009795 }
9796 mInput->stream->updateSinkMetadata(metadata);
9797}
9798
Eric Laurent5ada82e2019-08-29 17:53:54 -07009799void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -07009800{
9801 Mutex::Autolock _l(mLock);
9802 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07009803 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -07009804 mActiveTracks[i]->setSilenced_l(silenced);
9805 broadcast_l();
9806 }
9807 }
9808}
9809
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009810void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9811{
9812 MmapThread::toAudioPortConfig(config);
9813 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9814 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9815 config->flags.input = mInput->flags;
9816 }
9817}
9818
Glenn Kasten63238ef2015-03-02 15:50:29 -08009819} // namespace android