blob: e964a09f3c37bbe87cc524ffd317fd457205232f [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
jiabinc52b1ff2019-10-31 17:20:42 -070034#include <media/AudioContainers.h>
35#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070036#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070037#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080038#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080041#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070044#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010045#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080046#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080047#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080048#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080050#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070051#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070052#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_ns.h>
54#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070055#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070058#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080059#include <media/nbaio/AudioStreamOutSink.h>
60#include <media/nbaio/MonoPipe.h>
61#include <media/nbaio/MonoPipeReader.h>
62#include <media/nbaio/Pipe.h>
63#include <media/nbaio/PipeReader.h>
64#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080065#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080066
Mikhail Naganov2996f672019-04-18 12:29:59 -070067#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080068#include <powermanager/PowerManager.h>
69
Kevin Rocard7588ff42018-01-08 11:11:30 -080070#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070071#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080072
Eric Laurent81784c32012-11-19 14:55:58 -080073#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080074#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070075#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070076#include <mediautils/SchedulingPolicyService.h>
77#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080078
Eric Laurent81784c32012-11-19 14:55:58 -080079#ifdef ADD_BATTERY_DATA
80#include <media/IMediaPlayerService.h>
81#include <media/IMediaDeathNotifier.h>
82#endif
83
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070085#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080086#include <cpustats/ThreadCpuUsage.h>
87#endif
88
Glenn Kastenc05b8d72016-03-24 09:48:17 -070089#include "AutoPark.h"
90
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080091#include <pthread.h>
92#include "TypedLogger.h"
93
Eric Laurent81784c32012-11-19 14:55:58 -080094// ----------------------------------------------------------------------------
95
96// Note: the following macro is used for extremely verbose logging message. In
97// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
98// 0; but one side effect of this is to turn all LOGV's as well. Some messages
99// are so verbose that we want to suppress them even when we have ALOG_ASSERT
100// turned on. Do not uncomment the #def below unless you really know what you
101// are doing and want to see all of the extremely verbose messages.
102//#define VERY_VERY_VERBOSE_LOGGING
103#ifdef VERY_VERY_VERBOSE_LOGGING
104#define ALOGVV ALOGV
105#else
106#define ALOGVV(a...) do { } while(0)
107#endif
108
Andy Hung6770c6f2015-04-07 13:43:36 -0700109// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700110#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700111
Andy Hung6770c6f2015-04-07 13:43:36 -0700112template <typename T>
113static inline T min(const T& a, const T& b)
114{
115 return a < b ? a : b;
116}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700117
Eric Laurent81784c32012-11-19 14:55:58 -0800118namespace android {
119
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700120using media::IEffectClient;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700121using media::permission::Identity;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700122
Eric Laurent81784c32012-11-19 14:55:58 -0800123// retry counts for buffer fill timeout
124// 50 * ~20msecs = 1 second
125static const int8_t kMaxTrackRetries = 50;
126static const int8_t kMaxTrackStartupRetries = 50;
127// allow less retry attempts on direct output thread.
128// direct outputs can be a scarce resource in audio hardware and should
129// be released as quickly as possible.
130static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700131
Eric Laurent51716182016-02-29 18:00:56 -0800132
Eric Laurent81784c32012-11-19 14:55:58 -0800133
134// don't warn about blocked writes or record buffer overflows more often than this
135static const nsecs_t kWarningThrottleNs = seconds(5);
136
137// RecordThread loop sleep time upon application overrun or audio HAL read error
138static const int kRecordThreadSleepUs = 5000;
139
Eric Laurent10351942014-05-08 18:49:52 -0700140// maximum time to wait in sendConfigEvent_l() for a status to be received
141static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800142
143// minimum sleep time for the mixer thread loop when tracks are active but in underrun
144static const uint32_t kMinThreadSleepTimeUs = 5000;
145// maximum divider applied to the active sleep time in the mixer thread loop
146static const uint32_t kMaxThreadSleepTimeShift = 2;
147
Andy Hung09a50072014-02-27 14:30:47 -0800148// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700149// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800150static const uint32_t kMinNormalSinkBufferSizeMs = 20;
151// maximum normal sink buffer size
152static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800153
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700154// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
155// FIXME This should be based on experimentally observed scheduling jitter
156static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
157
Eric Laurent972a1732013-09-04 09:42:59 -0700158// Offloaded output thread standby delay: allows track transition without going to standby
159static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
160
Eric Laurent51716182016-02-29 18:00:56 -0800161// Direct output thread minimum sleep time in idle or active(underrun) state
162static const nsecs_t kDirectMinSleepTimeUs = 10000;
163
Glenn Kasten1b291842016-07-18 14:55:21 -0700164// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
165// balance between power consumption and latency, and allows threads to be scheduled reliably
166// by the CFS scheduler.
167// FIXME Express other hardcoded references to 20ms with references to this constant and move
168// it appropriately.
169#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800170
Eric Laurent81784c32012-11-19 14:55:58 -0800171// Whether to use fast mixer
172static const enum {
173 FastMixer_Never, // never initialize or use: for debugging only
174 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
175 // normal mixer multiplier is 1
176 FastMixer_Static, // initialize if needed, then use all the time if initialized,
177 // multiplier is calculated based on min & max normal mixer buffer size
178 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
179 // multiplier is calculated based on min & max normal mixer buffer size
180 // FIXME for FastMixer_Dynamic:
181 // Supporting this option will require fixing HALs that can't handle large writes.
182 // For example, one HAL implementation returns an error from a large write,
183 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
184 // We could either fix the HAL implementations, or provide a wrapper that breaks
185 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
186} kUseFastMixer = FastMixer_Static;
187
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700188// Whether to use fast capture
189static const enum {
190 FastCapture_Never, // never initialize or use: for debugging only
191 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
192 FastCapture_Static, // initialize if needed, then use all the time if initialized
193} kUseFastCapture = FastCapture_Static;
194
Eric Laurent81784c32012-11-19 14:55:58 -0800195// Priorities for requestPriority
196static const int kPriorityAudioApp = 2;
197static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700198static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800199
Glenn Kastenea38ee72016-04-18 11:08:01 -0700200// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
201// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
202// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700203
204// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800205static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800206
Glenn Kasten03490092014-05-27 12:30:54 -0700207// The minimum and maximum allowed values
208static const int kFastTrackMultiplierMin = 1;
209static const int kFastTrackMultiplierMax = 2;
210
211// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
212static int sFastTrackMultiplier = kFastTrackMultiplier;
213
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700214// See Thread::readOnlyHeap().
215// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
216// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
217// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700218static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700219
Eric Laurent81784c32012-11-19 14:55:58 -0800220// ----------------------------------------------------------------------------
221
Andy Hungb68f5eb2019-12-03 16:49:17 -0800222// TODO: move all toString helpers to audio.h
223// under #ifdef __cplusplus #endif
224static std::string patchSinksToString(const struct audio_patch *patch)
225{
226 std::stringstream ss;
227 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700228 if (i > 0) {
229 ss << "|";
230 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800231 ss << "(" << toString(patch->sinks[i].ext.device.type)
232 << ", " << patch->sinks[i].ext.device.address << ")";
233 }
234 return ss.str();
235}
236
237static std::string patchSourcesToString(const struct audio_patch *patch)
238{
239 std::stringstream ss;
240 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700241 if (i > 0) {
242 ss << "|";
243 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800244 ss << "(" << toString(patch->sources[i].ext.device.type)
245 << ", " << patch->sources[i].ext.device.address << ")";
246 }
247 return ss.str();
248}
249
Glenn Kasten03490092014-05-27 12:30:54 -0700250static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
251
252static void sFastTrackMultiplierInit()
253{
254 char value[PROPERTY_VALUE_MAX];
255 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
256 char *endptr;
257 unsigned long ul = strtoul(value, &endptr, 0);
258 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
259 sFastTrackMultiplier = (int) ul;
260 }
261 }
262}
263
264// ----------------------------------------------------------------------------
265
Eric Laurent81784c32012-11-19 14:55:58 -0800266#ifdef ADD_BATTERY_DATA
267// To collect the amplifier usage
268static void addBatteryData(uint32_t params) {
269 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
270 if (service == NULL) {
271 // it already logged
272 return;
273 }
274
275 service->addBatteryData(params);
276}
277#endif
278
Andy Hung3f0c9022016-01-15 17:49:46 -0800279// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
280struct {
281 // call when you acquire a partial wakelock
282 void acquire(const sp<IBinder> &wakeLockToken) {
283 pthread_mutex_lock(&mLock);
284 if (wakeLockToken.get() == nullptr) {
285 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
286 } else {
287 if (mCount == 0) {
288 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
289 }
290 ++mCount;
291 }
292 pthread_mutex_unlock(&mLock);
293 }
294
295 // call when you release a partial wakelock.
296 void release(const sp<IBinder> &wakeLockToken) {
297 if (wakeLockToken.get() == nullptr) {
298 return;
299 }
300 pthread_mutex_lock(&mLock);
301 if (--mCount < 0) {
302 ALOGE("negative wakelock count");
303 mCount = 0;
304 }
305 pthread_mutex_unlock(&mLock);
306 }
307
308 // retrieves the boottime timebase offset from monotonic.
309 int64_t getBoottimeOffset() {
310 pthread_mutex_lock(&mLock);
311 int64_t boottimeOffset = mBoottimeOffset;
312 pthread_mutex_unlock(&mLock);
313 return boottimeOffset;
314 }
315
316 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
317 // and the selected timebase.
318 // Currently only TIMEBASE_BOOTTIME is allowed.
319 //
320 // This only needs to be called upon acquiring the first partial wakelock
321 // after all other partial wakelocks are released.
322 //
323 // We do an empirical measurement of the offset rather than parsing
324 // /proc/timer_list since the latter is not a formal kernel ABI.
325 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
326 int clockbase;
327 switch (timebase) {
328 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
329 clockbase = SYSTEM_TIME_BOOTTIME;
330 break;
331 default:
332 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
333 break;
334 }
335 // try three times to get the clock offset, choose the one
336 // with the minimum gap in measurements.
337 const int tries = 3;
338 nsecs_t bestGap, measured;
339 for (int i = 0; i < tries; ++i) {
340 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
341 const nsecs_t tbase = systemTime(clockbase);
342 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
343 const nsecs_t gap = tmono2 - tmono;
344 if (i == 0 || gap < bestGap) {
345 bestGap = gap;
346 measured = tbase - ((tmono + tmono2) >> 1);
347 }
348 }
349
350 // to avoid micro-adjusting, we don't change the timebase
351 // unless it is significantly different.
352 //
353 // Assumption: It probably takes more than toleranceNs to
354 // suspend and resume the device.
355 static int64_t toleranceNs = 10000; // 10 us
356 if (llabs(*offset - measured) > toleranceNs) {
357 ALOGV("Adjusting timebase offset old: %lld new: %lld",
358 (long long)*offset, (long long)measured);
359 *offset = measured;
360 }
361 }
362
363 pthread_mutex_t mLock;
364 int32_t mCount;
365 int64_t mBoottimeOffset;
366} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800367
368// ----------------------------------------------------------------------------
369// CPU Stats
370// ----------------------------------------------------------------------------
371
372class CpuStats {
373public:
374 CpuStats();
375 void sample(const String8 &title);
376#ifdef DEBUG_CPU_USAGE
377private:
378 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700379 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800380
Andy Hung16698b82018-08-01 10:48:38 -0700381 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800382
383 int mCpuNum; // thread's current CPU number
384 int mCpukHz; // frequency of thread's current CPU in kHz
385#endif
386};
387
388CpuStats::CpuStats()
389#ifdef DEBUG_CPU_USAGE
390 : mCpuNum(-1), mCpukHz(-1)
391#endif
392{
393}
394
Glenn Kasten0f11b512014-01-31 16:18:54 -0800395void CpuStats::sample(const String8 &title
396#ifndef DEBUG_CPU_USAGE
397 __unused
398#endif
399 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800400#ifdef DEBUG_CPU_USAGE
401 // get current thread's delta CPU time in wall clock ns
402 double wcNs;
403 bool valid = mCpuUsage.sampleAndEnable(wcNs);
404
405 // record sample for wall clock statistics
406 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700407 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800408 }
409
410 // get the current CPU number
411 int cpuNum = sched_getcpu();
412
413 // get the current CPU frequency in kHz
414 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
415
416 // check if either CPU number or frequency changed
417 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
418 mCpuNum = cpuNum;
419 mCpukHz = cpukHz;
420 // ignore sample for purposes of cycles
421 valid = false;
422 }
423
424 // if no change in CPU number or frequency, then record sample for cycle statistics
425 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700426 const double cycles = wcNs * cpukHz * 0.000001;
427 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800428 }
429
Eric Tan5b13ff82018-07-27 11:20:17 -0700430 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800431 // mCpuUsage.elapsed() is expensive, so don't call it every loop
432 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700433 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800434 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700435 const double perLoop = elapsed / (double) n;
436 const double perLoop100 = perLoop * 0.01;
437 const double perLoop1k = perLoop * 0.001;
438 const double mean = mWcStats.getMean();
439 const double stddev = mWcStats.getStdDev();
440 const double minimum = mWcStats.getMin();
441 const double maximum = mWcStats.getMax();
442 const double meanCycles = mHzStats.getMean();
443 const double stddevCycles = mHzStats.getStdDev();
444 const double minCycles = mHzStats.getMin();
445 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800446 mCpuUsage.resetElapsed();
447 mWcStats.reset();
448 mHzStats.reset();
449 ALOGD("CPU usage for %s over past %.1f secs\n"
450 " (%u mixer loops at %.1f mean ms per loop):\n"
451 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
452 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
453 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
454 title.string(),
455 elapsed * .000000001, n, perLoop * .000001,
456 mean * .001,
457 stddev * .001,
458 minimum * .001,
459 maximum * .001,
460 mean / perLoop100,
461 stddev / perLoop100,
462 minimum / perLoop100,
463 maximum / perLoop100,
464 meanCycles / perLoop1k,
465 stddevCycles / perLoop1k,
466 minCycles / perLoop1k,
467 maxCycles / perLoop1k);
468
469 }
470 }
471#endif
472};
473
474// ----------------------------------------------------------------------------
475// ThreadBase
476// ----------------------------------------------------------------------------
477
Glenn Kasten97b7b752014-09-28 13:04:24 -0700478// static
479const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
480{
481 switch (type) {
482 case MIXER:
483 return "MIXER";
484 case DIRECT:
485 return "DIRECT";
486 case DUPLICATING:
487 return "DUPLICATING";
488 case RECORD:
489 return "RECORD";
490 case OFFLOAD:
491 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700492 case MMAP_PLAYBACK:
493 return "MMAP_PLAYBACK";
494 case MMAP_CAPTURE:
495 return "MMAP_CAPTURE";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700496 default:
497 return "unknown";
498 }
499}
500
Eric Laurent81784c32012-11-19 14:55:58 -0800501AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700502 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800503 : Thread(false /*canCallJava*/),
504 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700505 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700506 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
507 isOut),
508 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700509 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800510 // are set by PlaybackThread::readOutputParameters_l() or
511 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700512 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700513 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700514 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800515 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700516 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800517 mSystemReady(systemReady),
518 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800519{
Andy Hungcf10d742020-04-28 15:38:24 -0700520 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700521 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800522}
523
524AudioFlinger::ThreadBase::~ThreadBase()
525{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700526 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700527 mConfigEvents.clear();
528
Eric Laurent81784c32012-11-19 14:55:58 -0800529 // do not lock the mutex in destructor
530 releaseWakeLock_l();
531 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800532 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800533 binder->unlinkToDeath(mDeathRecipient);
534 }
Andy Hungd0979812019-02-21 15:51:44 -0800535
536 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800537}
538
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700539status_t AudioFlinger::ThreadBase::readyToRun()
540{
541 status_t status = initCheck();
542 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800543 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700544 } else {
545 ALOGE("No working audio driver found.");
546 }
547 return status;
548}
549
Eric Laurent81784c32012-11-19 14:55:58 -0800550void AudioFlinger::ThreadBase::exit()
551{
552 ALOGV("ThreadBase::exit");
553 // do any cleanup required for exit to succeed
554 preExit();
555 {
556 // This lock prevents the following race in thread (uniprocessor for illustration):
557 // if (!exitPending()) {
558 // // context switch from here to exit()
559 // // exit() calls requestExit(), what exitPending() observes
560 // // exit() calls signal(), which is dropped since no waiters
561 // // context switch back from exit() to here
562 // mWaitWorkCV.wait(...);
563 // // now thread is hung
564 // }
565 AutoMutex lock(mLock);
566 requestExit();
567 mWaitWorkCV.broadcast();
568 }
569 // When Thread::requestExitAndWait is made virtual and this method is renamed to
570 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
571 requestExitAndWait();
572}
573
574status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
575{
Eric Laurent81784c32012-11-19 14:55:58 -0800576 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
577 Mutex::Autolock _l(mLock);
578
Eric Laurent10351942014-05-08 18:49:52 -0700579 return sendSetParameterConfigEvent_l(keyValuePairs);
580}
581
582// sendConfigEvent_l() must be called with ThreadBase::mLock held
583// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
584status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
585{
586 status_t status = NO_ERROR;
587
Eric Laurent72e3f392015-05-20 14:43:50 -0700588 if (event->mRequiresSystemReady && !mSystemReady) {
589 event->mWaitStatus = false;
590 mPendingConfigEvents.add(event);
591 return status;
592 }
Eric Laurent10351942014-05-08 18:49:52 -0700593 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700594 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800595 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700596 mLock.unlock();
597 {
598 Mutex::Autolock _l(event->mLock);
599 while (event->mWaitStatus) {
600 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
601 event->mStatus = TIMED_OUT;
602 event->mWaitStatus = false;
603 }
604 }
605 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800606 }
Eric Laurent10351942014-05-08 18:49:52 -0700607 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800608 return status;
609}
610
Eric Laurent09f1ed22019-04-24 17:45:17 -0700611void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
612 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800613{
614 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700615 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800616}
617
618// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700619void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
620 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800621{
Andy Hungd0979812019-02-21 15:51:44 -0800622 // The audio statistics history is exponentially weighted to forget events
623 // about five or more seconds in the past. In order to have
624 // crisper statistics for mediametrics, we reset the statistics on
625 // an IoConfigEvent, to reflect different properties for a new device.
626 mIoJitterMs.reset();
627 mLatencyMs.reset();
628 mProcessTimeMs.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100629 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800630
Eric Laurent09f1ed22019-04-24 17:45:17 -0700631 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700632 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800633}
634
Mikhail Naganov83f04272017-02-07 10:45:09 -0800635void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700636{
637 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800638 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700639}
640
Eric Laurent81784c32012-11-19 14:55:58 -0800641// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800642void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
643 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800644{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800645 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700646 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800647}
648
Eric Laurent10351942014-05-08 18:49:52 -0700649// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
650status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800651{
Andy Hung2ddee192015-12-18 17:34:44 -0800652 sp<ConfigEvent> configEvent;
653 AudioParameter param(keyValuePair);
654 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700655 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800656 setMasterMono_l(value != 0);
657 if (param.size() == 1) {
658 return NO_ERROR; // should be a solo parameter - we don't pass down
659 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700660 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800661 configEvent = new SetParameterConfigEvent(param.toString());
662 } else {
663 configEvent = new SetParameterConfigEvent(keyValuePair);
664 }
Eric Laurent10351942014-05-08 18:49:52 -0700665 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700666}
667
Eric Laurent1c333e22014-05-20 10:48:17 -0700668status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
669 const struct audio_patch *patch,
670 audio_patch_handle_t *handle)
671{
672 Mutex::Autolock _l(mLock);
673 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
674 status_t status = sendConfigEvent_l(configEvent);
675 if (status == NO_ERROR) {
676 CreateAudioPatchConfigEventData *data =
677 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
678 *handle = data->mHandle;
679 }
680 return status;
681}
682
683status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
684 const audio_patch_handle_t handle)
685{
686 Mutex::Autolock _l(mLock);
687 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
688 return sendConfigEvent_l(configEvent);
689}
690
jiabinc52b1ff2019-10-31 17:20:42 -0700691status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
692 const DeviceDescriptorBaseVector& outDevices)
693{
694 if (type() != RECORD) {
695 // The update out device operation is only for record thread.
696 return INVALID_OPERATION;
697 }
698 Mutex::Autolock _l(mLock);
699 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
700 return sendConfigEvent_l(configEvent);
701}
702
Eric Laurentec376dc2021-04-08 20:41:22 +0200703void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
704{
705 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
706 sp<ConfigEvent> configEvent =
707 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
708 sendConfigEvent_l(configEvent);
709}
Eric Laurent1c333e22014-05-20 10:48:17 -0700710
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700711// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700712void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700713{
Eric Laurent10351942014-05-08 18:49:52 -0700714 bool configChanged = false;
715
Eric Laurent81784c32012-11-19 14:55:58 -0800716 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700717 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700718 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800719 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700720 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700721 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700722 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
723 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800724 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700725 true /*asynchronous*/);
726 if (err != 0) {
727 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700728 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700729 }
730 } break;
731 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700732 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700733 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700734 } break;
735 case CFG_EVENT_SET_PARAMETER: {
736 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
737 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
738 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700739 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
740 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700741 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700742 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700743 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700744 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700745 CreateAudioPatchConfigEventData *data =
746 (CreateAudioPatchConfigEventData *)event->mData.get();
747 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700748 const DeviceTypeSet newDevices = getDeviceTypes();
749 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
750 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
751 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700752 } break;
753 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700754 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700755 ReleaseAudioPatchConfigEventData *data =
756 (ReleaseAudioPatchConfigEventData *)event->mData.get();
757 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700758 const DeviceTypeSet newDevices = getDeviceTypes();
759 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
760 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
761 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
762 } break;
763 case CFG_EVENT_UPDATE_OUT_DEVICE: {
764 UpdateOutDevicesConfigEventData *data =
765 (UpdateOutDevicesConfigEventData *)event->mData.get();
766 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700767 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200768 case CFG_EVENT_RESIZE_BUFFER: {
769 ResizeBufferConfigEventData *data =
770 (ResizeBufferConfigEventData *)event->mData.get();
771 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
772 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700773 default:
Eric Laurent10351942014-05-08 18:49:52 -0700774 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700775 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800776 }
Eric Laurent10351942014-05-08 18:49:52 -0700777 {
778 Mutex::Autolock _l(event->mLock);
779 if (event->mWaitStatus) {
780 event->mWaitStatus = false;
781 event->mCond.signal();
782 }
783 }
784 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
785 }
786
787 if (configChanged) {
788 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800789 }
Eric Laurent81784c32012-11-19 14:55:58 -0800790}
791
Marco Nelissenb2208842014-02-07 14:00:50 -0800792String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
793 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700794 const audio_channel_representation_t representation =
795 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700796
797 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800798 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700799 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
800 if (output) {
801 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
802 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
803 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
804 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
805 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
806 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
807 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
808 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
809 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
810 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
811 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
812 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
813 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
814 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
815 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
816 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
817 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
818 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700819 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
820 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800821 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
822 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700823 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
824 } else {
825 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
826 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
827 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
828 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
829 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
830 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
831 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
832 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
833 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
834 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
835 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
836 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700837 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
838 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
839 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
840 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
841 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
842 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700843 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
844 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
845 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
846 }
847 const int len = s.length();
848 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700849 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700850 s.unlockBuffer(len - 2); // remove trailing ", "
851 }
852 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800853 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700854 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
855 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
856 return s;
857 default:
858 s.appendFormat("unknown mask, representation:%d bits:%#x",
859 representation, audio_channel_mask_get_bits(mask));
860 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800861 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800862}
863
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700864void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800865{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800866 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
867 this, mThreadName, getTid(), type(), threadTypeToString(type()));
868
Eric Laurent81784c32012-11-19 14:55:58 -0800869 bool locked = AudioFlinger::dumpTryLock(mLock);
870 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800871 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800872 }
873
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700874 dumpBase_l(fd, args);
875 dumpInternals_l(fd, args);
876 dumpTracks_l(fd, args);
877 dumpEffectChains_l(fd, args);
878
879 if (locked) {
880 mLock.unlock();
881 }
882
883 dprintf(fd, " Local log:\n");
884 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
885}
886
887void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
888{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700889 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700890 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700891 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700892 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700893 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700894 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700895 dprintf(fd, " Channel count: %u\n", mChannelCount);
896 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800897 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700898 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700899 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700900 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800901 size_t numConfig = mConfigEvents.size();
902 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700903 const size_t SIZE = 256;
904 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800905 for (size_t i = 0; i < numConfig; i++) {
906 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700907 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800908 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700909 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800910 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700911 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800912 }
Andy Hung293558a2017-03-21 12:19:20 -0700913 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700914 dprintf(fd, " Output devices: %s (%s)\n",
915 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
916 dprintf(fd, " Input device: %#x (%s)\n",
917 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800918 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800919
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700920 // Dump timestamp statistics for the Thread types that support it.
921 if (mType == RECORD
922 || mType == MIXER
923 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700924 || mType == DIRECT
925 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700926 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700927 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700928 }
929
Andy Hung446f4df2019-02-21 12:26:41 -0800930 if (mLastIoBeginNs > 0) { // MMAP may not set this
931 dprintf(fd, " Last %s occurred (msecs): %lld\n",
932 isOutput() ? "write" : "read",
933 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
934 }
935
936 if (mProcessTimeMs.getN() > 0) {
937 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
938 }
939
940 if (mIoJitterMs.getN() > 0) {
941 dprintf(fd, " Hal %s jitter ms stats: %s\n",
942 isOutput() ? "write" : "read",
943 mIoJitterMs.toString().c_str());
944 }
945
Andy Hunge6c37112019-02-26 17:38:10 -0800946 if (mLatencyMs.getN() > 0) {
947 dprintf(fd, " Threadloop %s latency stats: %s\n",
948 isOutput() ? "write" : "read",
949 mLatencyMs.toString().c_str());
950 }
Eric Laurent81784c32012-11-19 14:55:58 -0800951}
952
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700953void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800954{
955 const size_t SIZE = 256;
956 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800957
Marco Nelissenb2208842014-02-07 14:00:50 -0800958 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000959 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800960 write(fd, buffer, strlen(buffer));
961
Marco Nelissenb2208842014-02-07 14:00:50 -0800962 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800963 sp<EffectChain> chain = mEffectChains[i];
964 if (chain != 0) {
965 chain->dump(fd, args);
966 }
967 }
968}
969
Andy Hungdae27702016-10-31 14:01:16 -0700970void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800971{
972 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700973 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800974}
975
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100976String16 AudioFlinger::ThreadBase::getWakeLockTag()
977{
978 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800979 case MIXER:
980 return String16("AudioMix");
981 case DIRECT:
982 return String16("AudioDirectOut");
983 case DUPLICATING:
984 return String16("AudioDup");
985 case RECORD:
986 return String16("AudioIn");
987 case OFFLOAD:
988 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -0700989 case MMAP_PLAYBACK:
990 return String16("MmapPlayback");
991 case MMAP_CAPTURE:
992 return String16("MmapCapture");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800993 default:
994 ALOG_ASSERT(false);
995 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100996 }
997}
998
Andy Hungdae27702016-10-31 14:01:16 -0700999void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001000{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001001 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001002 if (mPowerManager != 0) {
1003 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001004 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001005 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1006 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001007 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001008 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001009 {} /* workSource */,
1010 {} /* historyTag */);
1011 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001012 mWakeLockToken = binder;
1013 }
Chris Ye6597d732020-02-28 22:38:25 -08001014 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001015 }
Wei Jia3f273d12015-11-24 09:06:49 -08001016
Andy Hung3f0c9022016-01-15 17:49:46 -08001017 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001018 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1019 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001020}
1021
1022void AudioFlinger::ThreadBase::releaseWakeLock()
1023{
1024 Mutex::Autolock _l(mLock);
1025 releaseWakeLock_l();
1026}
1027
1028void AudioFlinger::ThreadBase::releaseWakeLock_l()
1029{
Andy Hung3f0c9022016-01-15 17:49:46 -08001030 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001031 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001032 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001033 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001034 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001035 }
1036 mWakeLockToken.clear();
1037 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001038}
1039
1040void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001041 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001042 // use checkService() to avoid blocking if power service is not up yet
1043 sp<IBinder> binder =
1044 defaultServiceManager()->checkService(String16("power"));
1045 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001046 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001047 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001048 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001049 binder->linkToDeath(mDeathRecipient);
1050 }
1051 }
1052}
1053
Andy Hungd01b0f12016-11-07 16:10:30 -08001054void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001055 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001056
1057#if !LOG_NDEBUG
1058 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001059 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001060 s << uid << " ";
1061 }
1062 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1063#endif
1064
Andy Hung438e7572015-12-14 15:51:17 -08001065 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1066 if (mSystemReady) {
1067 ALOGE("no wake lock to update, but system ready!");
1068 } else {
1069 ALOGW("no wake lock to update, system not ready yet");
1070 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001071 return;
1072 }
1073 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001074 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001075 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1076 mWakeLockToken, uidsAsInt);
1077 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001078 }
1079}
1080
Eric Laurent81784c32012-11-19 14:55:58 -08001081void AudioFlinger::ThreadBase::clearPowerManager()
1082{
1083 Mutex::Autolock _l(mLock);
1084 releaseWakeLock_l();
1085 mPowerManager.clear();
1086}
1087
jiabinc52b1ff2019-10-31 17:20:42 -07001088void AudioFlinger::ThreadBase::updateOutDevices(
1089 const DeviceDescriptorBaseVector& outDevices __unused)
1090{
1091 ALOGE("%s should only be called in RecordThread", __func__);
1092}
1093
Eric Laurentec376dc2021-04-08 20:41:22 +02001094void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1095{
1096 ALOGE("%s should only be called in RecordThread", __func__);
1097}
1098
Glenn Kasten0f11b512014-01-31 16:18:54 -08001099void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001100{
1101 sp<ThreadBase> thread = mThread.promote();
1102 if (thread != 0) {
1103 thread->clearPowerManager();
1104 }
1105 ALOGW("power manager service died !!!");
1106}
1107
Eric Laurent81784c32012-11-19 14:55:58 -08001108void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001109 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001110{
1111 sp<EffectChain> chain = getEffectChain_l(sessionId);
1112 if (chain != 0) {
1113 if (type != NULL) {
1114 chain->setEffectSuspended_l(type, suspend);
1115 } else {
1116 chain->setEffectSuspendedAll_l(suspend);
1117 }
1118 }
1119
1120 updateSuspendedSessions_l(type, suspend, sessionId);
1121}
1122
1123void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1124{
1125 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1126 if (index < 0) {
1127 return;
1128 }
1129
1130 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1131 mSuspendedSessions.valueAt(index);
1132
1133 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001134 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001135 for (int j = 0; j < desc->mRefCount; j++) {
1136 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1137 chain->setEffectSuspendedAll_l(true);
1138 } else {
1139 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1140 desc->mType.timeLow);
1141 chain->setEffectSuspended_l(&desc->mType, true);
1142 }
1143 }
1144 }
1145}
1146
1147void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1148 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001149 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001150{
1151 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1152
1153 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1154
1155 if (suspend) {
1156 if (index >= 0) {
1157 sessionEffects = mSuspendedSessions.valueAt(index);
1158 } else {
1159 mSuspendedSessions.add(sessionId, sessionEffects);
1160 }
1161 } else {
1162 if (index < 0) {
1163 return;
1164 }
1165 sessionEffects = mSuspendedSessions.valueAt(index);
1166 }
1167
1168
1169 int key = EffectChain::kKeyForSuspendAll;
1170 if (type != NULL) {
1171 key = type->timeLow;
1172 }
1173 index = sessionEffects.indexOfKey(key);
1174
1175 sp<SuspendedSessionDesc> desc;
1176 if (suspend) {
1177 if (index >= 0) {
1178 desc = sessionEffects.valueAt(index);
1179 } else {
1180 desc = new SuspendedSessionDesc();
1181 if (type != NULL) {
1182 desc->mType = *type;
1183 }
1184 sessionEffects.add(key, desc);
1185 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1186 }
1187 desc->mRefCount++;
1188 } else {
1189 if (index < 0) {
1190 return;
1191 }
1192 desc = sessionEffects.valueAt(index);
1193 if (--desc->mRefCount == 0) {
1194 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1195 sessionEffects.removeItemsAt(index);
1196 if (sessionEffects.isEmpty()) {
1197 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1198 sessionId);
1199 mSuspendedSessions.removeItem(sessionId);
1200 }
1201 }
1202 }
1203 if (!sessionEffects.isEmpty()) {
1204 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1205 }
1206}
1207
Eric Laurent6b446ce2019-12-13 10:56:31 -08001208void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1209 audio_session_t sessionId,
1210 bool threadLocked) {
1211 if (!threadLocked) {
1212 mLock.lock();
1213 }
Eric Laurent81784c32012-11-19 14:55:58 -08001214
Eric Laurent81784c32012-11-19 14:55:58 -08001215 if (mType != RECORD) {
1216 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1217 // another session. This gives the priority to well behaved effect control panels
1218 // and applications not using global effects.
1219 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1220 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001221 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001222 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1223 }
1224 }
1225
Eric Laurent6b446ce2019-12-13 10:56:31 -08001226 if (!threadLocked) {
1227 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001228 }
1229}
1230
Eric Laurent4c415062016-06-17 16:14:16 -07001231// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1232status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1233 const effect_descriptor_t *desc, audio_session_t sessionId)
1234{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001235 // No global output effect sessions on record threads
1236 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1237 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001238 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1239 desc->name, mThreadName);
1240 return BAD_VALUE;
1241 }
1242 // only pre processing effects on record thread
1243 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1244 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1245 desc->name, mThreadName);
1246 return BAD_VALUE;
1247 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001248
1249 // always allow effects without processing load or latency
1250 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1251 return NO_ERROR;
1252 }
1253
Eric Laurent4c415062016-06-17 16:14:16 -07001254 audio_input_flags_t flags = mInput->flags;
1255 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1256 if (flags & AUDIO_INPUT_FLAG_RAW) {
1257 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1258 desc->name, mThreadName);
1259 return BAD_VALUE;
1260 }
1261 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1262 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1263 desc->name, mThreadName);
1264 return BAD_VALUE;
1265 }
1266 }
jiabineb3bda02020-06-30 14:07:03 -07001267
1268 if (EffectModule::isHapticGenerator(&desc->type)) {
1269 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1270 return BAD_VALUE;
1271 }
Eric Laurent4c415062016-06-17 16:14:16 -07001272 return NO_ERROR;
1273}
1274
1275// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1276status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1277 const effect_descriptor_t *desc, audio_session_t sessionId)
1278{
1279 // no preprocessing on playback threads
1280 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1281 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1282 " thread %s", desc->name, mThreadName);
1283 return BAD_VALUE;
1284 }
1285
Eric Laurent3e4de772017-07-16 16:55:08 -07001286 // always allow effects without processing load or latency
1287 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1288 return NO_ERROR;
1289 }
1290
jiabineb3bda02020-06-30 14:07:03 -07001291 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1292 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1293 __func__);
1294 return BAD_VALUE;
1295 }
1296
Eric Laurent4c415062016-06-17 16:14:16 -07001297 switch (mType) {
1298 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001299#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001300 // Reject any effect on mixer multichannel sinks.
1301 // TODO: fix both format and multichannel issues with effects.
1302 if (mChannelCount != FCC_2) {
1303 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1304 " thread %s", desc->name, mChannelCount, mThreadName);
1305 return BAD_VALUE;
1306 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001307#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001308 audio_output_flags_t flags = mOutput->flags;
1309 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1310 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1311 // global effects are applied only to non fast tracks if they are SW
1312 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1313 break;
1314 }
1315 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1316 // only post processing on output stage session
1317 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1318 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1319 " on output stage session", desc->name);
1320 return BAD_VALUE;
1321 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001322 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1323 // only post processing on output stage session
1324 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1325 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1326 " on device session", desc->name);
1327 return BAD_VALUE;
1328 }
Eric Laurent4c415062016-06-17 16:14:16 -07001329 } else {
1330 // no restriction on effects applied on non fast tracks
1331 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1332 break;
1333 }
1334 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001335
Eric Laurent4c415062016-06-17 16:14:16 -07001336 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1337 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1338 desc->name);
1339 return BAD_VALUE;
1340 }
1341 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1342 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1343 " in fast mode", desc->name);
1344 return BAD_VALUE;
1345 }
1346 }
1347 } break;
1348 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001349 // nothing actionable on offload threads, if the effect:
1350 // - is offloadable: the effect can be created
1351 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1352 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001353 break;
1354 case DIRECT:
1355 // Reject any effect on Direct output threads for now, since the format of
1356 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1357 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1358 desc->name, mThreadName);
1359 return BAD_VALUE;
1360 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001361#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001362 // Reject any effect on mixer multichannel sinks.
1363 // TODO: fix both format and multichannel issues with effects.
1364 if (mChannelCount != FCC_2) {
1365 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1366 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1367 return BAD_VALUE;
1368 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001369#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001370 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001371 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1372 " thread %s", desc->name, mThreadName);
1373 return BAD_VALUE;
1374 }
1375 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1376 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1377 " DUPLICATING thread %s", desc->name, mThreadName);
1378 return BAD_VALUE;
1379 }
1380 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1381 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1382 " DUPLICATING thread %s", desc->name, mThreadName);
1383 return BAD_VALUE;
1384 }
1385 break;
1386 default:
1387 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1388 }
1389
1390 return NO_ERROR;
1391}
1392
Eric Laurent81784c32012-11-19 14:55:58 -08001393// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1394sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1395 const sp<AudioFlinger::Client>& client,
1396 const sp<IEffectClient>& effectClient,
1397 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001398 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001399 effect_descriptor_t *desc,
1400 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001401 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001402 bool pinned,
1403 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001404{
1405 sp<EffectModule> effect;
1406 sp<EffectHandle> handle;
1407 status_t lStatus;
1408 sp<EffectChain> chain;
1409 bool chainCreated = false;
1410 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001411 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001412
1413 lStatus = initCheck();
1414 if (lStatus != NO_ERROR) {
1415 ALOGW("createEffect_l() Audio driver not initialized.");
1416 goto Exit;
1417 }
1418
Eric Laurent81784c32012-11-19 14:55:58 -08001419 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1420
1421 { // scope for mLock
1422 Mutex::Autolock _l(mLock);
1423
Eric Laurent4c415062016-06-17 16:14:16 -07001424 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001425 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001426 goto Exit;
1427 }
1428
Eric Laurent81784c32012-11-19 14:55:58 -08001429 // check for existing effect chain with the requested audio session
1430 chain = getEffectChain_l(sessionId);
1431 if (chain == 0) {
1432 // create a new chain for this session
1433 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1434 chain = new EffectChain(this, sessionId);
1435 addEffectChain_l(chain);
1436 chain->setStrategy(getStrategyForSession_l(sessionId));
1437 chainCreated = true;
1438 } else {
1439 effect = chain->getEffectFromDesc_l(desc);
1440 }
1441
1442 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1443
1444 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001445 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001446 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001447 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001448 if (lStatus != NO_ERROR) {
1449 goto Exit;
1450 }
1451 effectCreated = true;
1452
jiabinc52b1ff2019-10-31 17:20:42 -07001453 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001454 effect->setDevices(outDeviceTypeAddrs());
1455 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001456 effect->setMode(mAudioFlinger->getMode());
1457 effect->setAudioSource(mAudioSource);
1458 }
jiabin1319f5a2021-03-30 22:21:24 +00001459 if (effect->isHapticGenerator()) {
1460 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1461 // for the HapticGenerator.
1462 const media::AudioVibratorInfo* defaultVibratorInfo =
1463 mAudioFlinger->getDefaultVibratorInfo_l();
1464 if (defaultVibratorInfo != nullptr) {
1465 // Only set the vibrator info when it is a valid one.
1466 effect->setVibratorInfo(defaultVibratorInfo);
1467 }
1468 }
Eric Laurent81784c32012-11-19 14:55:58 -08001469 // create effect handle and connect it to effect module
1470 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001471 lStatus = handle->initCheck();
1472 if (lStatus == OK) {
1473 lStatus = effect->addHandle(handle.get());
1474 }
Eric Laurent81784c32012-11-19 14:55:58 -08001475 if (enabled != NULL) {
1476 *enabled = (int)effect->isEnabled();
1477 }
1478 }
1479
1480Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001481 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001482 Mutex::Autolock _l(mLock);
1483 if (effectCreated) {
1484 chain->removeEffect_l(effect);
1485 }
Eric Laurent81784c32012-11-19 14:55:58 -08001486 if (chainCreated) {
1487 removeEffectChain_l(chain);
1488 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001489 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001490 }
1491
Glenn Kasten9156ef32013-08-06 15:39:08 -07001492 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001493 return handle;
1494}
1495
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001496void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1497 bool unpinIfLast)
1498{
1499 bool remove = false;
1500 sp<EffectModule> effect;
1501 {
1502 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001503 sp<EffectBase> effectBase = handle->effect().promote();
1504 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001505 return;
1506 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001507 effect = effectBase->asEffectModule();
1508 if (effect == nullptr) {
1509 return;
1510 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001511 // restore suspended effects if the disconnected handle was enabled and the last one.
1512 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1513 if (remove) {
1514 removeEffect_l(effect, true);
1515 }
1516 }
1517 if (remove) {
1518 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001519 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001520 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001521 }
1522 }
1523}
1524
Eric Laurent6b446ce2019-12-13 10:56:31 -08001525void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001526 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001527 Mutex::Autolock _l(mLock);
1528 broadcast_l();
1529 }
1530 if (!effect->isOffloadable()) {
1531 if (mType == ThreadBase::OFFLOAD) {
1532 PlaybackThread *t = (PlaybackThread *)this;
1533 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1534 }
1535 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1536 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1537 }
1538 }
1539}
1540
1541void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001542 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001543 Mutex::Autolock _l(mLock);
1544 broadcast_l();
1545 }
1546}
1547
Glenn Kastend848eb42016-03-08 13:42:11 -08001548sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1549 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001550{
1551 Mutex::Autolock _l(mLock);
1552 return getEffect_l(sessionId, effectId);
1553}
1554
Glenn Kastend848eb42016-03-08 13:42:11 -08001555sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1556 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001557{
1558 sp<EffectChain> chain = getEffectChain_l(sessionId);
1559 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1560}
1561
Eric Laurent6c796322019-04-09 14:13:17 -07001562std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1563{
1564 sp<EffectChain> chain = getEffectChain_l(sessionId);
1565 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1566}
1567
Eric Laurent81784c32012-11-19 14:55:58 -08001568// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1569// PlaybackThread::mLock held
1570status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1571{
1572 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001573 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001574 sp<EffectChain> chain = getEffectChain_l(sessionId);
1575 bool chainCreated = false;
1576
Eric Laurent5baf2af2013-09-12 17:37:00 -07001577 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001578 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001579 this, effect->desc().name, effect->desc().flags);
1580
Eric Laurent81784c32012-11-19 14:55:58 -08001581 if (chain == 0) {
1582 // create a new chain for this session
1583 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1584 chain = new EffectChain(this, sessionId);
1585 addEffectChain_l(chain);
1586 chain->setStrategy(getStrategyForSession_l(sessionId));
1587 chainCreated = true;
1588 }
1589 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1590
1591 if (chain->getEffectFromId_l(effect->id()) != 0) {
1592 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1593 this, effect->desc().name, chain.get());
1594 return BAD_VALUE;
1595 }
1596
Eric Laurent5baf2af2013-09-12 17:37:00 -07001597 effect->setOffloaded(mType == OFFLOAD, mId);
1598
Eric Laurent81784c32012-11-19 14:55:58 -08001599 status_t status = chain->addEffect_l(effect);
1600 if (status != NO_ERROR) {
1601 if (chainCreated) {
1602 removeEffectChain_l(chain);
1603 }
1604 return status;
1605 }
1606
jiabin8f278ee2019-11-11 12:16:27 -08001607 effect->setDevices(outDeviceTypeAddrs());
1608 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001609 effect->setMode(mAudioFlinger->getMode());
1610 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001611
Eric Laurent81784c32012-11-19 14:55:58 -08001612 return NO_ERROR;
1613}
1614
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001615void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001616
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001617 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001618 effect_descriptor_t desc = effect->desc();
1619 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1620 detachAuxEffect_l(effect->id());
1621 }
1622
Eric Laurent6b446ce2019-12-13 10:56:31 -08001623 sp<EffectChain> chain = effect->callback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001624 if (chain != 0) {
1625 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001626 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001627 removeEffectChain_l(chain);
1628 }
1629 } else {
1630 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1631 }
1632}
1633
1634void AudioFlinger::ThreadBase::lockEffectChains_l(
1635 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1636{
1637 effectChains = mEffectChains;
1638 for (size_t i = 0; i < mEffectChains.size(); i++) {
1639 mEffectChains[i]->lock();
1640 }
1641}
1642
1643void AudioFlinger::ThreadBase::unlockEffectChains(
1644 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1645{
1646 for (size_t i = 0; i < effectChains.size(); i++) {
1647 effectChains[i]->unlock();
1648 }
1649}
1650
Glenn Kastend848eb42016-03-08 13:42:11 -08001651sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001652{
1653 Mutex::Autolock _l(mLock);
1654 return getEffectChain_l(sessionId);
1655}
1656
Glenn Kastend848eb42016-03-08 13:42:11 -08001657sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1658 const
Eric Laurent81784c32012-11-19 14:55:58 -08001659{
1660 size_t size = mEffectChains.size();
1661 for (size_t i = 0; i < size; i++) {
1662 if (mEffectChains[i]->sessionId() == sessionId) {
1663 return mEffectChains[i];
1664 }
1665 }
1666 return 0;
1667}
1668
1669void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1670{
1671 Mutex::Autolock _l(mLock);
1672 size_t size = mEffectChains.size();
1673 for (size_t i = 0; i < size; i++) {
1674 mEffectChains[i]->setMode_l(mode);
1675 }
1676}
1677
Mikhail Naganovdc769682018-05-04 15:34:08 -07001678void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001679{
1680 config->type = AUDIO_PORT_TYPE_MIX;
1681 config->ext.mix.handle = mId;
1682 config->sample_rate = mSampleRate;
1683 config->format = mFormat;
1684 config->channel_mask = mChannelMask;
1685 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1686 AUDIO_PORT_CONFIG_FORMAT;
1687}
1688
Eric Laurent72e3f392015-05-20 14:43:50 -07001689void AudioFlinger::ThreadBase::systemReady()
1690{
1691 Mutex::Autolock _l(mLock);
1692 if (mSystemReady) {
1693 return;
1694 }
1695 mSystemReady = true;
1696
1697 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1698 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1699 }
1700 mPendingConfigEvents.clear();
1701}
1702
Andy Hungdae27702016-10-31 14:01:16 -07001703template <typename T>
1704ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1705 ssize_t index = mActiveTracks.indexOf(track);
1706 if (index >= 0) {
1707 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1708 return index;
1709 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001710 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001711 mActiveTracksGeneration++;
1712 mLatestActiveTrack = track;
1713 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001714 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001715 return mActiveTracks.add(track);
1716}
1717
1718template <typename T>
1719ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1720 ssize_t index = mActiveTracks.remove(track);
1721 if (index < 0) {
1722 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1723 return index;
1724 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001725 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001726 mActiveTracksGeneration++;
1727 --mBatteryCounter[track->uid()].second;
1728 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001729 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001730#ifdef TEE_SINK
1731 track->dumpTee(-1 /* fd */, "_REMOVE");
1732#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001733 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001734 return index;
1735}
1736
1737template <typename T>
1738void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1739 for (const sp<T> &track : mActiveTracks) {
1740 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001741 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001742 }
1743 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001744 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001745 mActiveTracks.clear();
1746 mLatestActiveTrack.clear();
1747 mBatteryCounter.clear();
1748}
1749
1750template <typename T>
1751void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1752 sp<ThreadBase> thread, bool force) {
1753 // Updates ActiveTracks client uids to the thread wakelock.
1754 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1755 thread->updateWakeLockUids_l(getWakeLockUids());
1756 mLastActiveTracksGeneration = mActiveTracksGeneration;
1757 }
1758
1759 // Updates BatteryNotifier uids
1760 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1761 const uid_t uid = it->first;
1762 ssize_t &previous = it->second.first;
1763 ssize_t &current = it->second.second;
1764 if (current > 0) {
1765 if (previous == 0) {
1766 BatteryNotifier::getInstance().noteStartAudio(uid);
1767 }
1768 previous = current;
1769 ++it;
1770 } else if (current == 0) {
1771 if (previous > 0) {
1772 BatteryNotifier::getInstance().noteStopAudio(uid);
1773 }
1774 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1775 } else /* (current < 0) */ {
1776 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1777 }
1778 }
1779}
Eric Laurent83b88082014-06-20 18:31:16 -07001780
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001781template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001782bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1783 const bool hasChanged = mHasChanged;
1784 mHasChanged = false;
1785 return hasChanged;
1786}
1787
1788template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001789void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1790 const char *funcName, const sp<T> &track) const {
1791 if (mLocalLog != nullptr) {
1792 String8 result;
1793 track->appendDump(result, false /* active */);
1794 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1795 }
1796}
1797
Eric Laurent6acd1d42017-01-04 14:23:29 -08001798void AudioFlinger::ThreadBase::broadcast_l()
1799{
1800 // Thread could be blocked waiting for async
1801 // so signal it to handle state changes immediately
1802 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1803 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1804 mSignalPending = true;
1805 mWaitWorkCV.broadcast();
1806}
1807
Andy Hungd0979812019-02-21 15:51:44 -08001808// Call only from threadLoop() or when it is idle.
1809// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1810void AudioFlinger::ThreadBase::sendStatistics(bool force)
1811{
1812 // Do not log if we have no stats.
1813 // We choose the timestamp verifier because it is the most likely item to be present.
1814 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1815 if (nstats == 0) {
1816 return;
1817 }
1818
1819 // Don't log more frequently than once per 12 hours.
1820 // We use BOOTTIME to include suspend time.
1821 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1822 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1823 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1824 return;
1825 }
1826
1827 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1828 mLastRecordedTimeNs = timeNs;
1829
Ray Essickf27e9872019-12-07 06:28:46 -08001830 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001831
1832#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1833
1834 // thread configuration
1835 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1836 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1837 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1838 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1839 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1840 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1841 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001842 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1843 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001844
1845 // thread statistics
1846 if (mIoJitterMs.getN() > 0) {
1847 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1848 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1849 }
1850 if (mProcessTimeMs.getN() > 0) {
1851 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1852 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1853 }
1854 const auto tsjitter = mTimestampVerifier.getJitterMs();
1855 if (tsjitter.getN() > 0) {
1856 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1857 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1858 }
1859 if (mLatencyMs.getN() > 0) {
1860 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1861 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1862 }
1863
1864 item->selfrecord();
1865}
1866
Eric Laurent81784c32012-11-19 14:55:58 -08001867// ----------------------------------------------------------------------------
1868// Playback
1869// ----------------------------------------------------------------------------
1870
1871AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1872 AudioStreamOut* output,
1873 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001874 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001875 bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07001876 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001877 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001878 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001879 mMixerBuffer(NULL),
1880 mMixerBufferSize(0),
1881 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1882 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001883 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001884 mEffectBuffer(NULL),
1885 mEffectBufferSize(0),
1886 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1887 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001888 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001889 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001890 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001891 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001892 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001893 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001894 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001895 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001896 mMixerStatus(MIXER_IDLE),
1897 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001898 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001899 mBytesRemaining(0),
1900 mCurrentWriteLength(0),
1901 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001902 mWriteAckSequence(0),
1903 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001904 mScreenState(AudioFlinger::mScreenState),
1905 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001906 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001907 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001908 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1909 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001910{
Glenn Kastend7dca052015-03-05 16:05:54 -08001911 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1912 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001913
1914 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1915 // it would be safer to explicitly pass initial masterVolume/masterMute as
1916 // parameter.
1917 //
1918 // If the HAL we are using has support for master volume or master mute,
1919 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1920 // and the mute set to false).
1921 mMasterVolume = audioFlinger->masterVolume_l();
1922 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001923 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001924 if (mOutput->audioHwDev->canSetMasterVolume()) {
1925 mMasterVolume = 1.0;
1926 }
1927
1928 if (mOutput->audioHwDev->canSetMasterMute()) {
1929 mMasterMute = false;
1930 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001931 mIsMsdDevice = strcmp(
1932 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001933 }
1934
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001935 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001936
Andy Hungc8fddf32018-08-08 18:32:37 -07001937 // TODO: We may also match on address as well as device type for
1938 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001939 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001940 // TODO: This property should be ensure that only contains one single device type.
1941 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1942 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001943 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1944 : AUDIO_DEVICE_NONE));
1945 }
1946
Mikhail Naganovf33115d2020-09-25 23:03:05 +00001947 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1948 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08001949 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001950 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1951 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001952 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001953 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1954 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001955 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1956 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001957}
1958
1959AudioFlinger::PlaybackThread::~PlaybackThread()
1960{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001961 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001962 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001963 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001964 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001965}
1966
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001967// Thread virtuals
1968
1969void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001970{
jiabinf6eb4c32020-02-25 14:06:25 -08001971 if (mOutput == nullptr || mOutput->stream == nullptr) {
1972 ALOGE("The stream is not open yet"); // This should not happen.
1973 } else {
1974 // setEventCallback will need a strong pointer as a parameter. Calling it
1975 // here instead of constructor of PlaybackThread so that the onFirstRef
1976 // callback would not be made on an incompletely constructed object.
1977 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07001978 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08001979 }
1980 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001981 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001982}
1983
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001984// ThreadBase virtuals
1985void AudioFlinger::PlaybackThread::preExit()
1986{
1987 ALOGV(" preExit()");
1988 // FIXME this is using hard-coded strings but in the future, this functionality will be
1989 // converted to use audio HAL extensions required to support tunneling
1990 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1991 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1992}
1993
1994void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001995{
Eric Laurent81784c32012-11-19 14:55:58 -08001996 String8 result;
1997
Marco Nelissenb2208842014-02-07 14:00:50 -08001998 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001999 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2000 const stream_type_t *st = &mStreamTypes[i];
2001 if (i > 0) {
2002 result.appendFormat(", ");
2003 }
2004 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2005 if (st->mute) {
2006 result.append("M");
2007 }
2008 }
2009 result.append("\n");
2010 write(fd, result.string(), result.length());
2011 result.clear();
2012
Eric Laurent81784c32012-11-19 14:55:58 -08002013 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2014 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002015 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002016 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002017
2018 size_t numtracks = mTracks.size();
2019 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002020 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002021 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002022 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002023 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002024 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002025 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002026 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002027 for (size_t i = 0; i < numtracks; ++i) {
2028 sp<Track> track = mTracks[i];
2029 if (track != 0) {
2030 bool active = mActiveTracks.indexOf(track) >= 0;
2031 if (active) {
2032 numactiveseen++;
2033 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002034 result.append(prefix);
2035 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002036 }
2037 }
2038 } else {
2039 result.append("\n");
2040 }
2041 if (numactiveseen != numactive) {
2042 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002043 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002044 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002045 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002046 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002047 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002048 sp<Track> track = mActiveTracks[i];
2049 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002050 result.append(prefix);
2051 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002052 }
2053 }
2054 }
2055
2056 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002057}
2058
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002059void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002060{
Andy Hung04cb8f72020-03-20 13:44:33 -07002061 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002062 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002063 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2064 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2065 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2066 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002067 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002068 dprintf(fd, " Total writes: %d\n", mNumWrites);
2069 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2070 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2071 dprintf(fd, " Suspend count: %d\n", mSuspended);
2072 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2073 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2074 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2075 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002076 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002077 AudioStreamOut *output = mOutput;
2078 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002079 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002080 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002081 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2082 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2083 if (mPipeSink.get() != nullptr) {
2084 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2085 }
2086 if (output != nullptr) {
2087 dprintf(fd, " Hal stream dump:\n");
2088 (void)output->stream->dump(fd);
2089 }
Eric Laurent81784c32012-11-19 14:55:58 -08002090}
2091
Eric Laurent81784c32012-11-19 14:55:58 -08002092// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2093sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2094 const sp<AudioFlinger::Client>& client,
2095 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002096 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002097 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002098 audio_format_t format,
2099 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002100 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002101 size_t *pNotificationFrameCount,
2102 uint32_t notificationsPerBuffer,
2103 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002104 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002105 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002106 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002107 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002108 const Identity& identity,
Eric Laurent81784c32012-11-19 14:55:58 -08002109 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002110 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002111 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002112 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002113{
Glenn Kasten74935e42013-12-19 08:56:45 -08002114 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002115 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002116 sp<Track> track;
2117 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002118 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002119 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002120 uint32_t sampleRate;
2121
2122 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2123 lStatus = BAD_VALUE;
2124 goto Exit;
2125 }
Eric Laurent21da6472017-11-09 16:29:26 -08002126
2127 if (*pSampleRate == 0) {
2128 *pSampleRate = mSampleRate;
2129 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002130 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002131
2132 // special case for FAST flag considered OK if fast mixer is present
2133 if (hasFastMixer()) {
2134 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2135 }
2136
2137 // Check if requested flags are compatible with output stream flags
2138 if ((*flags & outputFlags) != *flags) {
2139 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2140 *flags, outputFlags);
2141 *flags = (audio_output_flags_t)(*flags & outputFlags);
2142 }
Eric Laurent81784c32012-11-19 14:55:58 -08002143
Eric Laurent81784c32012-11-19 14:55:58 -08002144 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002145 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002146 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002147 // PCM data
2148 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002149 // TODO: extract as a data library function that checks that a computationally
2150 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002151 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002152 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2153 (channelMask == AUDIO_CHANNEL_OUT_MONO
2154 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002155 // hardware sample rate
2156 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002157 // normal mixer has an associated fast mixer
2158 hasFastMixer() &&
2159 // there are sufficient fast track slots available
2160 (mFastTrackAvailMask != 0)
2161 // FIXME test that MixerThread for this fast track has a capable output HAL
2162 // FIXME add a permission test also?
2163 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002164 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2165 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002166 // read the fast track multiplier property the first time it is needed
2167 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2168 if (ok != 0) {
2169 ALOGE("%s pthread_once failed: %d", __func__, ok);
2170 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002171 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002172 }
Eric Laurent4c415062016-06-17 16:14:16 -07002173
2174 // check compatibility with audio effects.
2175 { // scope for mLock
2176 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002177 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002178 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002179 AUDIO_SESSION_OUTPUT_STAGE,
2180 AUDIO_SESSION_OUTPUT_MIX,
2181 sessionId,
2182 }) {
2183 sp<EffectChain> chain = getEffectChain_l(session);
2184 if (chain.get() != nullptr) {
2185 audio_output_flags_t old = *flags;
2186 chain->checkOutputFlagCompatibility(flags);
2187 if (old != *flags) {
2188 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2189 (int)session, (int)old, (int)*flags);
2190 }
Eric Laurent4c415062016-06-17 16:14:16 -07002191 }
2192 }
2193 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002194 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002195 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2196 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002197 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002198 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2199 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002200 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002201 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002202 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002203 audio_is_linear_pcm(format), channelMask, sampleRate,
2204 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002205 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002206 }
2207 }
Eric Laurent21da6472017-11-09 16:29:26 -08002208
2209 if (!audio_has_proportional_frames(format)) {
2210 if (sharedBuffer != 0) {
2211 // Same comment as below about ignoring frameCount parameter for set()
2212 frameCount = sharedBuffer->size();
2213 } else if (frameCount == 0) {
2214 frameCount = mNormalFrameCount;
2215 }
2216 if (notificationFrameCount != frameCount) {
2217 notificationFrameCount = frameCount;
2218 }
2219 } else if (sharedBuffer != 0) {
2220 // FIXME: Ensure client side memory buffers need
2221 // not have additional alignment beyond sample
2222 // (e.g. 16 bit stereo accessed as 32 bit frame).
2223 size_t alignment = audio_bytes_per_sample(format);
2224 if (alignment & 1) {
2225 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2226 alignment = 1;
2227 }
2228 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2229 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2230 if (channelCount > 1) {
2231 // More than 2 channels does not require stronger alignment than stereo
2232 alignment <<= 1;
2233 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002234 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002235 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002236 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002237 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002238 goto Exit;
2239 }
Eric Laurent21da6472017-11-09 16:29:26 -08002240
2241 // When initializing a shared buffer AudioTrack via constructors,
2242 // there's no frameCount parameter.
2243 // But when initializing a shared buffer AudioTrack via set(),
2244 // there _is_ a frameCount parameter. We silently ignore it.
2245 frameCount = sharedBuffer->size() / frameSize;
2246 } else {
2247 size_t minFrameCount = 0;
2248 // For fast tracks we try to respect the application's request for notifications per buffer.
2249 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2250 if (notificationsPerBuffer > 0) {
2251 // Avoid possible arithmetic overflow during multiplication.
2252 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2253 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2254 notificationsPerBuffer, mFrameCount);
2255 } else {
2256 minFrameCount = mFrameCount * notificationsPerBuffer;
2257 }
2258 }
2259 } else {
2260 // For normal PCM streaming tracks, update minimum frame count.
2261 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2262 // cover audio hardware latency.
2263 // This is probably too conservative, but legacy application code may depend on it.
2264 // If you change this calculation, also review the start threshold which is related.
2265 uint32_t latencyMs = latency_l();
2266 if (latencyMs == 0) {
2267 ALOGE("Error when retrieving output stream latency");
2268 lStatus = UNKNOWN_ERROR;
2269 goto Exit;
2270 }
2271
2272 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2273 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2274
Eric Laurent81784c32012-11-19 14:55:58 -08002275 }
Eric Laurent21da6472017-11-09 16:29:26 -08002276 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002277 frameCount = minFrameCount;
2278 }
Eric Laurent81784c32012-11-19 14:55:58 -08002279 }
Eric Laurent21da6472017-11-09 16:29:26 -08002280
2281 // Make sure that application is notified with sufficient margin before underrun.
2282 // The client can divide the AudioTrack buffer into sub-buffers,
2283 // and expresses its desire to server as the notification frame count.
2284 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2285 size_t maxNotificationFrames;
2286 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2287 // notify every HAL buffer, regardless of the size of the track buffer
2288 maxNotificationFrames = mFrameCount;
2289 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002290 // Triple buffer the notification period for a triple buffered mixer period;
2291 // otherwise, double buffering for the notification period is fine.
2292 //
2293 // TODO: This should be moved to AudioTrack to modify the notification period
2294 // on AudioTrack::setBufferSizeInFrames() changes.
2295 const int nBuffering =
2296 (uint64_t{frameCount} * mSampleRate)
2297 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2298
Eric Laurent21da6472017-11-09 16:29:26 -08002299 maxNotificationFrames = frameCount / nBuffering;
2300 // If client requested a fast track but this was denied, then use the smaller maximum.
2301 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2302 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2303 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2304 maxNotificationFrames = maxNotificationFramesFastDenied;
2305 }
2306 }
2307 }
2308 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2309 if (notificationFrameCount == 0) {
2310 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2311 maxNotificationFrames, frameCount);
2312 } else {
2313 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2314 notificationFrameCount, maxNotificationFrames, frameCount);
2315 }
2316 notificationFrameCount = maxNotificationFrames;
2317 }
2318 }
2319
Glenn Kasten74935e42013-12-19 08:56:45 -08002320 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002321 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002322
Glenn Kastenc3df8382014-03-13 15:05:25 -07002323 switch (mType) {
2324
2325 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002326 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002327 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002328 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2329 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002330 sampleRate, format, channelMask, mOutput, mFormat);
2331 lStatus = BAD_VALUE;
2332 goto Exit;
2333 }
2334 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002335 break;
2336
2337 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002338 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002339 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2340 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002341 sampleRate, format, channelMask, mOutput, mFormat);
2342 lStatus = BAD_VALUE;
2343 goto Exit;
2344 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002345 break;
2346
2347 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002348 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002349 ALOGE("createTrack_l() Bad parameter: format %#x \""
2350 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002351 format, mOutput, mFormat);
2352 lStatus = BAD_VALUE;
2353 goto Exit;
2354 }
Andy Hungcd044842014-08-07 11:04:34 -07002355 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002356 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2357 lStatus = BAD_VALUE;
2358 goto Exit;
2359 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002360 break;
2361
Eric Laurent81784c32012-11-19 14:55:58 -08002362 }
2363
2364 lStatus = initCheck();
2365 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002366 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002367 goto Exit;
2368 }
2369
2370 { // scope for mLock
2371 Mutex::Autolock _l(mLock);
2372
2373 // all tracks in same audio session must share the same routing strategy otherwise
2374 // conflicts will happen when tracks are moved from one output to another by audio policy
2375 // manager
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002376 product_strategy_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002377 for (size_t i = 0; i < mTracks.size(); ++i) {
2378 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002379 if (t != 0 && t->isExternalTrack()) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002380 product_strategy_t actual = AudioSystem::getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002381 if (sessionId == t->sessionId() && strategy != actual) {
2382 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2383 strategy, actual);
2384 lStatus = BAD_VALUE;
2385 goto Exit;
2386 }
2387 }
2388 }
2389
yucliuc9c49cd2020-07-13 16:25:21 -07002390 // Set DIRECT flag if current thread is DirectOutputThread. This can
2391 // happen when the playback is rerouted to direct output thread by
2392 // dynamic audio policy.
2393 // Do NOT report the flag changes back to client, since the client
2394 // doesn't explicitly request a direct flag.
2395 audio_output_flags_t trackFlags = *flags;
2396 if (mType == DIRECT) {
2397 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2398 }
2399
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002400 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002401 channelMask, frameCount,
2402 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002403 sessionId, creatorPid, identity, trackFlags, TrackBase::TYPE_DEFAULT,
2404 portId, SIZE_MAX /*frameCountToBeReady*/);
Glenn Kasten03003332013-08-06 15:40:54 -07002405
Glenn Kasten03003332013-08-06 15:40:54 -07002406 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2407 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002408 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002409 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002410 goto Exit;
2411 }
2412 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002413 {
2414 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2415 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002416 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002417 }
2418 }
Eric Laurent81784c32012-11-19 14:55:58 -08002419
2420 sp<EffectChain> chain = getEffectChain_l(sessionId);
2421 if (chain != 0) {
2422 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2423 track->setMainBuffer(chain->inBuffer());
2424 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2425 chain->incTrackCnt();
2426 }
2427
Eric Laurent05067782016-06-01 18:27:28 -07002428 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002429 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2430 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2431 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002432 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002433 }
2434 }
2435
2436 lStatus = NO_ERROR;
2437
2438Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002439 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002440 return track;
2441}
2442
Andy Hung1bc088a2018-02-09 15:57:31 -08002443template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002444ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2445{
Andy Hungc0691382018-09-12 18:01:57 -07002446 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002447 const ssize_t index = mTracks.remove(track);
2448 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002449 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002450 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002451 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002452 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002453 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002454 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002455 }
2456 return index;
2457}
2458
Eric Laurent81784c32012-11-19 14:55:58 -08002459uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2460{
2461 return latency;
2462}
2463
2464uint32_t AudioFlinger::PlaybackThread::latency() const
2465{
2466 Mutex::Autolock _l(mLock);
2467 return latency_l();
2468}
2469uint32_t AudioFlinger::PlaybackThread::latency_l() const
2470{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002471 uint32_t latency;
2472 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2473 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002474 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002475 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002476}
2477
2478void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2479{
2480 Mutex::Autolock _l(mLock);
2481 // Don't apply master volume in SW if our HAL can do it for us.
2482 if (mOutput && mOutput->audioHwDev &&
2483 mOutput->audioHwDev->canSetMasterVolume()) {
2484 mMasterVolume = 1.0;
2485 } else {
2486 mMasterVolume = value;
2487 }
2488}
2489
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002490void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2491{
2492 mMasterBalance.store(balance);
2493}
2494
Eric Laurent81784c32012-11-19 14:55:58 -08002495void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2496{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002497 if (isDuplicating()) {
2498 return;
2499 }
Eric Laurent81784c32012-11-19 14:55:58 -08002500 Mutex::Autolock _l(mLock);
2501 // Don't apply master mute in SW if our HAL can do it for us.
2502 if (mOutput && mOutput->audioHwDev &&
2503 mOutput->audioHwDev->canSetMasterMute()) {
2504 mMasterMute = false;
2505 } else {
2506 mMasterMute = muted;
2507 }
2508}
2509
2510void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2511{
2512 Mutex::Autolock _l(mLock);
2513 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002514 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002515}
2516
2517void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2518{
2519 Mutex::Autolock _l(mLock);
2520 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002521 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002522}
2523
2524float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2525{
2526 Mutex::Autolock _l(mLock);
2527 return mStreamTypes[stream].volume;
2528}
2529
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002530void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2531{
2532 mOutput->stream->setVolume(left, right);
2533}
2534
Eric Laurent81784c32012-11-19 14:55:58 -08002535// addTrack_l() must be called with ThreadBase::mLock held
2536status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2537{
2538 status_t status = ALREADY_EXISTS;
2539
Eric Laurent81784c32012-11-19 14:55:58 -08002540 if (mActiveTracks.indexOf(track) < 0) {
2541 // the track is newly added, make sure it fills up all its
2542 // buffers before playing. This is to ensure the client will
2543 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002544 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002545 TrackBase::track_state state = track->mState;
2546 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002547 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002548 mLock.lock();
2549 // abort track was stopped/paused while we released the lock
2550 if (state != track->mState) {
2551 if (status == NO_ERROR) {
2552 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002553 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002554 mLock.lock();
2555 }
2556 return INVALID_OPERATION;
2557 }
2558 // abort if start is rejected by audio policy manager
2559 if (status != NO_ERROR) {
2560 return PERMISSION_DENIED;
2561 }
2562#ifdef ADD_BATTERY_DATA
2563 // to track the speaker usage
2564 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2565#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002566 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002567 }
2568
Eric Laurent51716182016-02-29 18:00:56 -08002569 // set retry count for buffer fill
2570 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002571 if (track->isStopping_1()) {
2572 track->mRetryCount = kMaxTrackStopRetriesOffload;
2573 } else {
2574 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2575 }
2576 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002577 } else {
2578 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002579 track->mFillingUpStatus =
2580 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002581 }
2582
jiabineb3bda02020-06-30 14:07:03 -07002583 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2584 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2585 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2586 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002587 // Unlock due to VibratorService will lock for this call and will
2588 // call Tracks.mute/unmute which also require thread's lock.
2589 mLock.unlock();
2590 const int intensity = AudioFlinger::onExternalVibrationStart(
2591 track->getExternalVibration());
2592 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002593 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002594 // Haptic playback should be enabled by vibrator service.
2595 if (track->getHapticPlaybackEnabled()) {
2596 // Disable haptic playback of all active track to ensure only
2597 // one track playing haptic if current track should play haptic.
2598 for (const auto &t : mActiveTracks) {
2599 t->setHapticPlaybackEnabled(false);
2600 }
jiabin245cdd92018-12-07 17:55:15 -08002601 }
jiabine70bc7f2020-06-30 22:07:55 -07002602
2603 // Set haptic intensity for effect
2604 if (chain != nullptr) {
2605 chain->setHapticIntensity_l(track->id(), intensity);
2606 }
jiabin245cdd92018-12-07 17:55:15 -08002607 }
2608
Eric Laurent81784c32012-11-19 14:55:58 -08002609 track->mResetDone = false;
2610 track->mPresentationCompleteFrames = 0;
2611 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002612 if (chain != 0) {
2613 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2614 track->sessionId());
2615 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002616 }
2617
Andy Hungc2b11cb2020-04-22 09:04:01 -07002618 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002619 status = NO_ERROR;
2620 }
2621
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002622 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002623 return status;
2624}
2625
Eric Laurentbfb1b832013-01-07 09:53:42 -08002626bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002627{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002628 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002629 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002630 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2631 track->mState = TrackBase::STOPPED;
2632 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002633 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002634 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002635 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002636 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002637
2638 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002639}
2640
2641void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2642{
2643 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002644
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002645 String8 result;
2646 track->appendDump(result, false /* active */);
2647 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002648
Eric Laurent81784c32012-11-19 14:55:58 -08002649 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002650 {
2651 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2652 mAudioTrackCallbacks.erase(track);
2653 }
Eric Laurent81784c32012-11-19 14:55:58 -08002654 if (track->isFastTrack()) {
2655 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002656 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002657 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2658 mFastTrackAvailMask |= 1 << index;
2659 // redundant as track is about to be destroyed, for dumpsys only
2660 track->mFastIndex = -1;
2661 }
2662 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2663 if (chain != 0) {
2664 chain->decTrackCnt();
2665 }
2666}
2667
2668String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2669{
Eric Laurent81784c32012-11-19 14:55:58 -08002670 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002671 String8 out_s8;
2672 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2673 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002674 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002675 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002676}
2677
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002678status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2679 Mutex::Autolock _l(mLock);
2680 if (mOutput == nullptr || mOutput->stream == nullptr) {
2681 return NO_INIT;
2682 }
2683 return mOutput->stream->selectPresentation(presentationId, programId);
2684}
2685
Eric Laurent09f1ed22019-04-24 17:45:17 -07002686void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2687 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002688 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2689 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002690
Eric Laurent73e26b62015-04-27 16:55:58 -07002691 desc->mIoHandle = mId;
Eric Laurent74c38dc2020-12-23 18:19:44 +01002692 struct audio_patch patch = mPatch;
2693 if (isMsdDevice()) {
2694 patch = mDownStreamPatch;
2695 }
Eric Laurent81784c32012-11-19 14:55:58 -08002696
2697 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002698 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002699 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002700 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002701 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002702 desc->mChannelMask = mChannelMask;
2703 desc->mSamplingRate = mSampleRate;
2704 desc->mFormat = mFormat;
2705 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002706 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002707 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002708 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002709 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002710 case AUDIO_CLIENT_STARTED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002711 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002712 desc->mPortId = portId;
2713 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002714 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002715 default:
2716 break;
2717 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002718 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002719}
2720
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002721void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002722{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002723 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002724}
2725
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002726void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002728 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002729}
2730
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002731void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002732{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002733 mCallbackThread->setAsyncError();
2734}
2735
jiabinf6eb4c32020-02-25 14:06:25 -08002736void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2737 const std::basic_string<uint8_t>& metadataBs)
2738{
2739 std::thread([this, metadataBs]() {
2740 audio_utils::metadata::Data metadata =
2741 audio_utils::metadata::dataFromByteString(metadataBs);
2742 if (metadata.empty()) {
2743 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2744 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2745 (int)metadataBs.size());
2746 return;
2747 }
2748
2749 audio_utils::metadata::ByteString metaDataStr =
2750 audio_utils::metadata::byteStringFromData(metadata);
2751 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2752 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002753 for (const auto& callbackPair : mAudioTrackCallbacks) {
2754 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002755 }
2756 }).detach();
2757}
2758
Eric Laurent3b4529e2013-09-05 18:09:19 -07002759void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002760{
2761 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002762 // reject out of sequence requests
2763 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2764 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002765 mWaitWorkCV.signal();
2766 }
2767}
2768
Eric Laurent3b4529e2013-09-05 18:09:19 -07002769void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002770{
2771 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002772 // reject out of sequence requests
2773 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002774 // Register discontinuity when HW drain is completed because that can cause
2775 // the timestamp frame position to reset to 0 for direct and offload threads.
2776 // (Out of sequence requests are ignored, since the discontinuity would be handled
2777 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002778 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002779 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002780 mWaitWorkCV.signal();
2781 }
2782}
2783
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002784void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002785{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002786 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002787 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2788 mSampleRate = audioConfig.sample_rate;
2789 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002790 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002791 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002792 }
Andy Hung9a592762014-07-21 21:56:01 -07002793 if ((mType == MIXER || mType == DUPLICATING)
2794 && !isValidPcmSinkChannelMask(mChannelMask)) {
2795 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2796 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002797 }
Andy Hunge5412692014-05-16 11:25:07 -07002798 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002799 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002800
2801 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002802 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002803 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002804 // Get format from the shim, which will be different than the HAL format
2805 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002806 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002807 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002808 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002809 }
Andy Hung6146c082014-03-18 11:56:15 -07002810 if ((mType == MIXER || mType == DUPLICATING)
2811 && !isValidPcmSinkFormat(mFormat)) {
2812 LOG_FATAL("HAL format %#x not supported for mixed output",
2813 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002814 }
Phil Burk062e67a2015-02-11 13:40:50 -08002815 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002816 result = mOutput->stream->getBufferSize(&mBufferSize);
2817 LOG_ALWAYS_FATAL_IF(result != OK,
2818 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002819 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002820 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002821 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002822 mFrameCount);
2823 }
2824
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002825 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2826 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002827 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002828 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002829 }
2830 }
2831
Eric Laurentd1f69b02014-12-15 14:33:13 -08002832 mHwSupportsPause = false;
2833 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002834 bool supportsPause = false, supportsResume = false;
2835 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2836 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002837 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002838 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002839 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002840 } else if (supportsResume) {
2841 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002842 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002843 }
2844 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002845 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2846 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2847 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002848
Andy Hungfbfc3952015-01-15 13:33:51 -08002849 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2850 // For best precision, we use float instead of the associated output
2851 // device format (typically PCM 16 bit).
2852
2853 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2854 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2855 mBufferSize = mFrameSize * mFrameCount;
2856
2857 // TODO: We currently use the associated output device channel mask and sample rate.
2858 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2859 // (if a valid mask) to avoid premature downmix.
2860 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2861 // instead of the output device sample rate to avoid loss of high frequency information.
2862 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2863 }
2864
Andy Hung09a50072014-02-27 14:30:47 -08002865 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002866 double multiplier = 1.0;
2867 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2868 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002869 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2870 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002871
Eric Laurent81784c32012-11-19 14:55:58 -08002872 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2873 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2874 maxNormalFrameCount = maxNormalFrameCount & ~15;
2875 if (maxNormalFrameCount < minNormalFrameCount) {
2876 maxNormalFrameCount = minNormalFrameCount;
2877 }
2878 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2879 if (multiplier <= 1.0) {
2880 multiplier = 1.0;
2881 } else if (multiplier <= 2.0) {
2882 if (2 * mFrameCount <= maxNormalFrameCount) {
2883 multiplier = 2.0;
2884 } else {
2885 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2886 }
2887 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002888 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002889 }
2890 }
2891 mNormalFrameCount = multiplier * mFrameCount;
2892 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002893 if (mType == MIXER || mType == DUPLICATING) {
2894 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2895 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002896 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002897 mNormalFrameCount);
2898
Andy Hung08fb1742015-05-31 23:22:10 -07002899 // Check if we want to throttle the processing to no more than 2x normal rate
2900 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002901 mThreadThrottleTimeMs = 0;
2902 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002903 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2904
Andy Hung010a1a12014-03-13 13:57:33 -07002905 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2906 // Originally this was int16_t[] array, need to remove legacy implications.
2907 free(mSinkBuffer);
2908 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002909 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2910 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2911 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002912 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002913
Andy Hung69aed5f2014-02-25 17:24:40 -08002914 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2915 // drives the output.
2916 free(mMixerBuffer);
2917 mMixerBuffer = NULL;
2918 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002919 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002920 mMixerBufferSize = mNormalFrameCount * mChannelCount
2921 * audio_bytes_per_sample(mMixerBufferFormat);
2922 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2923 }
Andy Hung98ef9782014-03-04 14:46:50 -08002924 free(mEffectBuffer);
2925 mEffectBuffer = NULL;
2926 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002927 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002928 mEffectBufferSize = mNormalFrameCount * mChannelCount
2929 * audio_bytes_per_sample(mEffectBufferFormat);
2930 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2931 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002932
Mikhail Naganov55773032020-10-01 15:08:13 -07002933 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2934 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002935 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2936 mChannelCount -= mHapticChannelCount;
2937
Eric Laurent81784c32012-11-19 14:55:58 -08002938 // force reconfiguration of effect chains and engines to take new buffer size and audio
2939 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002940 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002941 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2942 // matter.
2943 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2944 Vector< sp<EffectChain> > effectChains = mEffectChains;
2945 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002946 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2947 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002948 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002949
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002950 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002951 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002952 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2953 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2954 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2955 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2956 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2957 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2958 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2959 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2960 (int32_t)mHapticChannelMask)
2961 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2962 (int32_t)mHapticChannelCount)
2963 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2964 formatToString(mHALFormat).c_str())
2965 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2966 (int32_t)mFrameCount) // sic - added HAL
2967 ;
2968 uint32_t latencyMs;
2969 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2970 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2971 }
2972 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08002973}
2974
Kevin Rocard069c2712018-03-29 19:09:14 -07002975void AudioFlinger::PlaybackThread::updateMetadata_l()
2976{
Kevin Rocard12381092018-04-11 09:19:59 -07002977 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2978 return; // That should not happen
2979 }
2980 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2981 for (const sp<Track> &track : mActiveTracks) {
2982 // Do not short-circuit as all hasChanged states must be reset
2983 // as all the metadata are going to be sent
2984 hasChanged |= track->readAndClearHasChanged();
2985 }
2986 if (!hasChanged) {
2987 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002988 }
2989 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002990 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002991 for (const sp<Track> &track : mActiveTracks) {
2992 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01002993 // Do not forward metadata for PatchTrack with unspecified stream type
2994 if (track->streamType() != AUDIO_STREAM_PATCH) {
2995 track->copyMetadataTo(backInserter);
2996 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002997 }
Kevin Rocard12381092018-04-11 09:19:59 -07002998 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002999}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003000
Kevin Rocard12381092018-04-11 09:19:59 -07003001void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3002 const StreamOutHalInterface::SourceMetadata& metadata)
3003{
3004 mOutput->stream->updateSourceMetadata(metadata);
3005};
3006
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003007status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003008{
3009 if (halFrames == NULL || dspFrames == NULL) {
3010 return BAD_VALUE;
3011 }
3012 Mutex::Autolock _l(mLock);
3013 if (initCheck() != NO_ERROR) {
3014 return INVALID_OPERATION;
3015 }
Andy Hung818e7a32016-02-16 18:08:07 -08003016 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003017 *halFrames = framesWritten;
3018
3019 if (isSuspended()) {
3020 // return an estimation of rendered frames when the output is suspended
3021 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003022 *dspFrames = (uint32_t)
3023 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003024 return NO_ERROR;
3025 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003026 status_t status;
3027 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003028 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003029 *dspFrames = (size_t)frames;
3030 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003031 }
3032}
3033
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003034product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003035{
3036 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3037 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3038 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3039 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3040 }
3041 for (size_t i = 0; i < mTracks.size(); i++) {
3042 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003043 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003044 return AudioSystem::getStrategyForStream(track->streamType());
3045 }
3046 }
3047 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3048}
3049
3050
Phil Burk062e67a2015-02-11 13:40:50 -08003051AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003052{
3053 Mutex::Autolock _l(mLock);
3054 return mOutput;
3055}
3056
Phil Burk062e67a2015-02-11 13:40:50 -08003057AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003058{
3059 Mutex::Autolock _l(mLock);
3060 AudioStreamOut *output = mOutput;
3061 mOutput = NULL;
3062 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3063 // must push a NULL and wait for ack
3064 mOutputSink.clear();
3065 mPipeSink.clear();
3066 mNormalSink.clear();
3067 return output;
3068}
3069
3070// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003071sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003072{
3073 if (mOutput == NULL) {
3074 return NULL;
3075 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003076 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003077}
3078
3079uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3080{
3081 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3082}
3083
3084status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3085{
3086 if (!isValidSyncEvent(event)) {
3087 return BAD_VALUE;
3088 }
3089
3090 Mutex::Autolock _l(mLock);
3091
3092 for (size_t i = 0; i < mTracks.size(); ++i) {
3093 sp<Track> track = mTracks[i];
3094 if (event->triggerSession() == track->sessionId()) {
3095 (void) track->setSyncEvent(event);
3096 return NO_ERROR;
3097 }
3098 }
3099
3100 return NAME_NOT_FOUND;
3101}
3102
3103bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3104{
3105 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3106}
3107
3108void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3109 const Vector< sp<Track> >& tracksToRemove)
3110{
Andy Hungfe726a62018-09-27 15:17:25 -07003111 // Miscellaneous track cleanup when removed from the active list,
3112 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003113#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003114 for (const auto& track : tracksToRemove) {
3115 if (track->isExternalTrack()) {
3116 // to track the speaker usage
3117 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003118 }
3119 }
Andy Hungfe726a62018-09-27 15:17:25 -07003120#else
3121 (void)tracksToRemove; // suppress unused warning
3122#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003123}
3124
3125void AudioFlinger::PlaybackThread::checkSilentMode_l()
3126{
3127 if (!mMasterMute) {
3128 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003129 if (mOutDeviceTypeAddrs.empty()) {
3130 ALOGD("ro.audio.silent is ignored since no output device is set");
3131 return;
3132 }
jiabinc52b1ff2019-10-31 17:20:42 -07003133 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003134 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3135 return;
3136 }
Eric Laurent81784c32012-11-19 14:55:58 -08003137 if (property_get("ro.audio.silent", value, "0") > 0) {
3138 char *endptr;
3139 unsigned long ul = strtoul(value, &endptr, 0);
3140 if (*endptr == '\0' && ul != 0) {
3141 ALOGD("Silence is golden");
3142 // The setprop command will not allow a property to be changed after
3143 // the first time it is set, so we don't have to worry about un-muting.
3144 setMasterMute_l(true);
3145 }
3146 }
3147 }
3148}
3149
3150// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003151ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003152{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003153 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003154 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003155 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003156 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003157
3158 // If an NBAIO sink is present, use it to write the normal mixer's submix
3159 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003160
Andy Hung010a1a12014-03-13 13:57:33 -07003161 const size_t count = mBytesRemaining / mFrameSize;
3162
Simon Wilson2d590962012-11-29 15:18:50 -08003163 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003164 // update the setpoint when AudioFlinger::mScreenState changes
3165 uint32_t screenState = AudioFlinger::mScreenState;
3166 if (screenState != mScreenState) {
3167 mScreenState = screenState;
3168 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3169 if (pipe != NULL) {
3170 pipe->setAvgFrames((mScreenState & 1) ?
3171 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3172 }
3173 }
Andy Hung010a1a12014-03-13 13:57:33 -07003174 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003175 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003176 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003177 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003178#ifdef TEE_SINK
3179 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3180#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003181 } else {
3182 bytesWritten = framesWritten;
3183 }
3184 // otherwise use the HAL / AudioStreamOut directly
3185 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003186 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003187
Eric Laurentbfb1b832013-01-07 09:53:42 -08003188 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003189 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3190 mWriteAckSequence += 2;
3191 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003192 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003193 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003194 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003195 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003196 // FIXME We should have an implementation of timestamps for direct output threads.
3197 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003198 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003199 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003200
Eric Laurentbfb1b832013-01-07 09:53:42 -08003201 if (mUseAsyncWrite &&
3202 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3203 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003204 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003205 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003206 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003207 }
Eric Laurent81784c32012-11-19 14:55:58 -08003208 }
3209
Eric Laurent81784c32012-11-19 14:55:58 -08003210 mNumWrites++;
3211 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003212 if (mStandby) {
3213 mThreadMetrics.logBeginInterval();
3214 mStandby = false;
3215 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003216 return bytesWritten;
3217}
3218
3219void AudioFlinger::PlaybackThread::threadLoop_drain()
3220{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003221 bool supportsDrain = false;
3222 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003223 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3224 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003225 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3226 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003227 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003228 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003229 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003230 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003231 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003232 }
3233}
3234
3235void AudioFlinger::PlaybackThread::threadLoop_exit()
3236{
Eric Laurent275e8e92014-11-30 15:14:47 -08003237 {
3238 Mutex::Autolock _l(mLock);
3239 for (size_t i = 0; i < mTracks.size(); i++) {
3240 sp<Track> track = mTracks[i];
3241 track->invalidate();
3242 }
Andy Hungdae27702016-10-31 14:01:16 -07003243 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3244 // After we exit there are no more track changes sent to BatteryNotifier
3245 // because that requires an active threadLoop.
3246 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3247 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003248 }
Eric Laurent81784c32012-11-19 14:55:58 -08003249}
3250
3251/*
3252The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003253 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003254 - mActiveSleepTimeUs from activeSleepTimeUs()
3255 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003256 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3257 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003258 - maxPeriod from frame count and sample rate (MIXER only)
3259
3260The parameters that affect these derived values are:
3261 - frame count
3262 - frame size
3263 - sample rate
3264 - device type: A2DP or not
3265 - device latency
3266 - format: PCM or not
3267 - active sleep time
3268 - idle sleep time
3269*/
3270
3271void AudioFlinger::PlaybackThread::cacheParameters_l()
3272{
Andy Hung25c2dac2014-02-27 14:56:00 -08003273 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003274 mActiveSleepTimeUs = activeSleepTimeUs();
3275 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003276
3277 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3278 // truncating audio when going to standby.
3279 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003280 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003281 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3282 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3283 }
3284 }
Eric Laurent81784c32012-11-19 14:55:58 -08003285}
3286
Eric Laurent13084622016-05-17 10:51:49 -07003287bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003288{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003289 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003290 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003291 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003292 size_t size = mTracks.size();
3293 for (size_t i = 0; i < size; i++) {
3294 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003295 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003296 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003297 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003298 }
3299 }
Eric Laurent13084622016-05-17 10:51:49 -07003300 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003301}
3302
Haynes Mathew George05317d22016-05-03 16:34:26 -07003303void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3304{
3305 Mutex::Autolock _l(mLock);
3306 invalidateTracks_l(streamType);
3307}
3308
Eric Laurent81784c32012-11-19 14:55:58 -08003309status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3310{
Glenn Kastend848eb42016-03-08 13:42:11 -08003311 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003312 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003313 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003314 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3315 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3316 &halInBuffer);
3317 if (result != OK) return result;
3318 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003319 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003320 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003321 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003322 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003323 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003324 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003325 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003326 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003327 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003328 &halInBuffer);
3329 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003330#ifdef FLOAT_EFFECT_CHAIN
3331 buffer = halInBuffer->audioBuffer()->f32;
3332#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003333 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003334#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003335 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3336 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003337 }
3338
3339 // Attach all tracks with same session ID to this chain.
3340 for (size_t i = 0; i < mTracks.size(); ++i) {
3341 sp<Track> track = mTracks[i];
3342 if (session == track->sessionId()) {
3343 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3344 buffer);
3345 track->setMainBuffer(buffer);
3346 chain->incTrackCnt();
3347 }
3348 }
3349
3350 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003351 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003352 if (session == track->sessionId()) {
3353 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3354 chain->incActiveTrackCnt();
3355 }
3356 }
3357 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003358 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003359 chain->setInBuffer(halInBuffer);
3360 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003361 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3362 // chains list in order to be processed last as it contains output device effects.
3363 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3364 // processing effects specific to an output stream before effects applied to all streams
3365 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003366 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3367 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003368 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003369 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003370 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003371 // Effect chain for other sessions are inserted at beginning of effect
3372 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003373 // sessions is not important.
3374 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003375 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3376 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003377 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003378 size_t size = mEffectChains.size();
3379 size_t i = 0;
3380 for (i = 0; i < size; i++) {
3381 if (mEffectChains[i]->sessionId() < session) {
3382 break;
3383 }
3384 }
3385 mEffectChains.insertAt(chain, i);
3386 checkSuspendOnAddEffectChain_l(chain);
3387
3388 return NO_ERROR;
3389}
3390
3391size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3392{
Glenn Kastend848eb42016-03-08 13:42:11 -08003393 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003394
3395 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3396
3397 for (size_t i = 0; i < mEffectChains.size(); i++) {
3398 if (chain == mEffectChains[i]) {
3399 mEffectChains.removeAt(i);
3400 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003401 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003402 if (session == track->sessionId()) {
3403 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3404 chain.get(), session);
3405 chain->decActiveTrackCnt();
3406 }
3407 }
3408
3409 // detach all tracks with same session ID from this chain
3410 for (size_t i = 0; i < mTracks.size(); ++i) {
3411 sp<Track> track = mTracks[i];
3412 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003413 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003414 chain->decTrackCnt();
3415 }
3416 }
3417 break;
3418 }
3419 }
3420 return mEffectChains.size();
3421}
3422
3423status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003424 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003425{
3426 Mutex::Autolock _l(mLock);
3427 return attachAuxEffect_l(track, EffectId);
3428}
3429
3430status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003431 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003432{
3433 status_t status = NO_ERROR;
3434
3435 if (EffectId == 0) {
3436 track->setAuxBuffer(0, NULL);
3437 } else {
3438 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3439 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3440 if (effect != 0) {
3441 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3442 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3443 } else {
3444 status = INVALID_OPERATION;
3445 }
3446 } else {
3447 status = BAD_VALUE;
3448 }
3449 }
3450 return status;
3451}
3452
3453void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3454{
3455 for (size_t i = 0; i < mTracks.size(); ++i) {
3456 sp<Track> track = mTracks[i];
3457 if (track->auxEffectId() == effectId) {
3458 attachAuxEffect_l(track, 0);
3459 }
3460 }
3461}
3462
3463bool AudioFlinger::PlaybackThread::threadLoop()
3464{
Glenn Kasten388d5712017-04-07 14:38:41 -07003465 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003466
Eric Laurent81784c32012-11-19 14:55:58 -08003467 Vector< sp<Track> > tracksToRemove;
3468
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003469 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003470 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003471
3472 // MIXER
3473 nsecs_t lastWarning = 0;
3474
3475 // DUPLICATING
3476 // FIXME could this be made local to while loop?
3477 writeFrames = 0;
3478
3479 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003480 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003481
3482 if (mType == MIXER) {
3483 sleepTimeShift = 0;
3484 }
3485
3486 CpuStats cpuStats;
3487 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3488
3489 acquireWakeLock();
3490
Glenn Kasteneef598c2017-04-03 14:41:13 -07003491 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3492 // thread associated with this PlaybackThread.
3493 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3494 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003495 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3496 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003497 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003498 const char *logString = NULL;
3499
rago1bb90822017-05-02 18:31:48 -07003500 // Estimated time for next buffer to be written to hal. This is used only on
3501 // suspended mode (for now) to help schedule the wait time until next iteration.
3502 nsecs_t timeLoopNextNs = 0;
3503
Eric Laurent664539d2013-09-23 18:24:31 -07003504 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003505
Andy Hung2dbffc22018-08-08 18:50:41 -07003506 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003507
Andy Hung446f4df2019-02-21 12:26:41 -08003508 // loopCount is used for statistics and diagnostics.
3509 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003510 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003511 // Log merge requests are performed during AudioFlinger binder transactions, but
3512 // that does not cover audio playback. It's requested here for that reason.
3513 mAudioFlinger->requestLogMerge();
3514
Eric Laurent81784c32012-11-19 14:55:58 -08003515 cpuStats.sample(myName);
3516
3517 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003518 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003519 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003520
Andy Hung2dbffc22018-08-08 18:50:41 -07003521 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3522 //
jiabinc52b1ff2019-10-31 17:20:42 -07003523 // Note: we access outDeviceTypes() outside of mLock.
3524 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003525 // Here, we try for the AF lock, but do not block on it as the latency
3526 // is more informational.
3527 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3528 std::vector<PatchPanel::SoftwarePatch> swPatches;
3529 double latencyMs;
3530 status_t status = INVALID_OPERATION;
3531 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3532 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3533 && swPatches.size() > 0) {
3534 status = swPatches[0].getLatencyMs_l(&latencyMs);
3535 downstreamPatchHandle = swPatches[0].getPatchHandle();
3536 }
3537 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003538 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003539 lastDownstreamPatchHandle = downstreamPatchHandle;
3540 }
3541 if (status == OK) {
3542 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003543 // latency of 5 seconds).
3544 const double minLatency = 0., maxLatency = 5000.;
3545 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003546 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003547 } else {
3548 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003549 if (latencyMs < minLatency) latencyMs = minLatency;
3550 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003551 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003552 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003553 }
3554 mAudioFlinger->mLock.unlock();
3555 }
3556 } else {
3557 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3558 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003559 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003560 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3561 }
3562 }
3563
Eric Laurent81784c32012-11-19 14:55:58 -08003564 { // scope for mLock
3565
3566 Mutex::Autolock _l(mLock);
3567
Eric Laurent021cf962014-05-13 10:18:14 -07003568 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003569
Glenn Kasteneef598c2017-04-03 14:41:13 -07003570 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003571 if (logString != NULL) {
3572 mNBLogWriter->logTimestamp();
3573 mNBLogWriter->log(logString);
3574 logString = NULL;
3575 }
3576
Dean Wheatley12473e92021-03-18 23:00:55 +11003577 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003578
Eric Laurent81784c32012-11-19 14:55:58 -08003579 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580 if (mSignalPending) {
3581 // A signal was raised while we were unlocked
3582 mSignalPending = false;
3583 } else if (waitingAsyncCallback_l()) {
3584 if (exitPending()) {
3585 break;
3586 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003587 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003588 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003589 releaseWakeLock_l();
3590 released = true;
3591 }
Andy Hung10cbff12017-02-21 17:30:14 -08003592
3593 const int64_t waitNs = computeWaitTimeNs_l();
3594 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3595 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3596 if (status == TIMED_OUT) {
3597 mSignalPending = true; // if timeout recheck everything
3598 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003599 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003600 if (released) {
3601 acquireWakeLock_l();
3602 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003603 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3604 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003605
3606 continue;
3607 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003608 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003609 isSuspended()) {
3610 // put audio hardware into standby after short delay
3611 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003612
3613 threadLoop_standby();
3614
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003615 // This is where we go into standby
3616 if (!mStandby) {
3617 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003618 mThreadMetrics.logEndInterval();
3619 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003620 }
Andy Hungd0979812019-02-21 15:51:44 -08003621 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003622 }
3623
Eric Tan39ec8d62018-07-24 09:49:29 -07003624 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003625 // we're about to wait, flush the binder command buffer
3626 IPCThreadState::self()->flushCommands();
3627
3628 clearOutputTracks();
3629
3630 if (exitPending()) {
3631 break;
3632 }
3633
3634 releaseWakeLock_l();
3635 // wait until we have something to do...
3636 ALOGV("%s going to sleep", myName.string());
3637 mWaitWorkCV.wait(mLock);
3638 ALOGV("%s waking up", myName.string());
3639 acquireWakeLock_l();
3640
3641 mMixerStatus = MIXER_IDLE;
3642 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3643 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003644 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003645 checkSilentMode_l();
3646
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003647 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3648 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003649 if (mType == MIXER) {
3650 sleepTimeShift = 0;
3651 }
3652
3653 continue;
3654 }
3655 }
Eric Laurent81784c32012-11-19 14:55:58 -08003656 // mMixerStatusIgnoringFastTracks is also updated internally
3657 mMixerStatus = prepareTracks_l(&tracksToRemove);
3658
Andy Hungdae27702016-10-31 14:01:16 -07003659 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003660
Kevin Rocard069c2712018-03-29 19:09:14 -07003661 updateMetadata_l();
3662
Eric Laurent81784c32012-11-19 14:55:58 -08003663 // prevent any changes in effect chain list and in each effect chain
3664 // during mixing and effect process as the audio buffers could be deleted
3665 // or modified if an effect is created or deleted
3666 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003667
3668 // Determine which session to pick up haptic data.
3669 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003670 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003671 // TODO: Write haptic data directly to sink buffer when mixing.
3672 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3673 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003674 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3675 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3676 activeHapticSessionId = track->sessionId();
3677 break;
3678 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003679 if (track->getHapticPlaybackEnabled()) {
3680 activeHapticSessionId = track->sessionId();
3681 break;
3682 }
3683 }
3684 }
3685
Andy Hungc1646382019-04-30 16:12:10 -07003686 // Acquire a local copy of active tracks with lock (release w/o lock).
3687 //
3688 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3689 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3690 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3691 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003692 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003693
Eric Laurentbfb1b832013-01-07 09:53:42 -08003694 if (mBytesRemaining == 0) {
3695 mCurrentWriteLength = 0;
3696 if (mMixerStatus == MIXER_TRACKS_READY) {
3697 // threadLoop_mix() sets mCurrentWriteLength
3698 threadLoop_mix();
3699 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3700 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003701 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003702 // must be written to HAL
3703 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003704 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003705 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003706
3707 // Tally underrun frames as we are inserting 0s here.
3708 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003709 if (track->mFillingUpStatus == Track::FS_ACTIVE
3710 && !track->isStopped()
3711 && !track->isPaused()
3712 && !track->isTerminated()) {
3713 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3714 __func__, track->id(), track->getTrackStateAsString(),
3715 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003716 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3717 }
3718 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003719 }
3720 }
Andy Hung98ef9782014-03-04 14:46:50 -08003721 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003722 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003723 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3724 // or mSinkBuffer (if there are no effects).
3725 //
3726 // This is done pre-effects computation; if effects change to
3727 // support higher precision, this needs to move.
3728 //
3729 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003730 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003731 if (mMixerBufferValid) {
3732 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3733 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3734
Andy Hung2ddee192015-12-18 17:34:44 -08003735 // mono blend occurs for mixer threads only (not direct or offloaded)
3736 // and is handled here if we're going directly to the sink.
3737 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003738 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3739 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003740 }
3741
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003742 if (!hasFastMixer()) {
3743 // Balance must take effect after mono conversion.
3744 // We do it here if there is no FastMixer.
3745 // mBalance detects zero balance within the class for speed (not needed here).
3746 mBalance.setBalance(mMasterBalance.load());
3747 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3748 }
3749
Andy Hung98ef9782014-03-04 14:46:50 -08003750 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003751 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3752
3753 // If we're going directly to the sink and there are haptic channels,
3754 // we should adjust channels as the sample data is partially interleaved
3755 // in this case.
3756 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3757 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3758 mChannelCount + mHapticChannelCount,
3759 audio_bytes_per_sample(format),
3760 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3761 }
Andy Hung98ef9782014-03-04 14:46:50 -08003762 }
3763
Eric Laurentbfb1b832013-01-07 09:53:42 -08003764 mBytesRemaining = mCurrentWriteLength;
3765 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003766 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3767 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3768 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3769 mBytesWritten += mBytesRemaining;
3770 mFramesWritten += framesRemaining;
3771 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003772 mBytesRemaining = 0;
3773 }
Eric Laurent81784c32012-11-19 14:55:58 -08003774
Eric Laurentbfb1b832013-01-07 09:53:42 -08003775 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003776 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003777 for (size_t i = 0; i < effectChains.size(); i ++) {
3778 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003779 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003780 if (activeHapticSessionId != AUDIO_SESSION_NONE
3781 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003782 // Haptic data is active in this case, copy it directly from
3783 // in buffer to out buffer.
3784 const size_t audioBufferSize = mNormalFrameCount
3785 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3786 memcpy_by_audio_format(
3787 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3788 EFFECT_BUFFER_FORMAT,
3789 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3790 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3791 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003792 }
Eric Laurent81784c32012-11-19 14:55:58 -08003793 }
3794 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003795 // Process effect chains for offloaded thread even if no audio
3796 // was read from audio track: process only updates effect state
3797 // and thus does have to be synchronized with audio writes but may have
3798 // to be called while waiting for async write callback
3799 if (mType == OFFLOAD) {
3800 for (size_t i = 0; i < effectChains.size(); i ++) {
3801 effectChains[i]->process_l();
3802 }
3803 }
Eric Laurent81784c32012-11-19 14:55:58 -08003804
Andy Hung98ef9782014-03-04 14:46:50 -08003805 // Only if the Effects buffer is enabled and there is data in the
3806 // Effects buffer (buffer valid), we need to
3807 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003808 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003809 if (mEffectBufferValid) {
3810 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003811
3812 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003813 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3814 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003815 }
3816
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003817 if (!hasFastMixer()) {
3818 // Balance must take effect after mono conversion.
3819 // We do it here if there is no FastMixer.
3820 // mBalance detects zero balance within the class for speed (not needed here).
3821 mBalance.setBalance(mMasterBalance.load());
3822 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3823 }
3824
Andy Hung98ef9782014-03-04 14:46:50 -08003825 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003826 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3827 // The sample data is partially interleaved when haptic channels exist,
3828 // we need to adjust channels here.
3829 if (mHapticChannelCount > 0) {
3830 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3831 mChannelCount + mHapticChannelCount,
3832 audio_bytes_per_sample(mFormat),
3833 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3834 }
Andy Hung98ef9782014-03-04 14:46:50 -08003835 }
3836
Eric Laurent81784c32012-11-19 14:55:58 -08003837 // enable changes in effect chain
3838 unlockEffectChains(effectChains);
3839
Eric Laurentbfb1b832013-01-07 09:53:42 -08003840 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003841 // mSleepTimeUs == 0 means we must write to audio hardware
3842 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003843 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003844 // writePeriodNs is updated >= 0 when ret > 0.
3845 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003846 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003847 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003848 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003849 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003850 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003851 if (ret < 0) {
3852 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003853 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003854 mBytesWritten += ret;
3855 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003856 const int64_t frames = ret / mFrameSize;
3857 mFramesWritten += frames;
3858
3859 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3860 // process information relating to write time.
3861 if (audio_has_proportional_frames(mFormat)) {
3862 // we are in a continuous mixing cycle
3863 if (mMixerStatus == MIXER_TRACKS_READY &&
3864 loopCount == lastLoopCountWritten + 1) {
3865
3866 const double jitterMs =
3867 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3868 {frames, writePeriodNs},
3869 {0, 0} /* lastTimestamp */, mSampleRate);
3870 const double processMs =
3871 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3872
3873 Mutex::Autolock _l(mLock);
3874 mIoJitterMs.add(jitterMs);
3875 mProcessTimeMs.add(processMs);
3876 }
3877
3878 // write blocked detection
3879 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3880 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3881 mNumDelayedWrites++;
3882 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3883 ATRACE_NAME("underrun");
3884 ALOGW("write blocked for %lld msecs, "
3885 "%d delayed writes, thread %d",
3886 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3887 mNumDelayedWrites, mId);
3888 lastWarning = lastIoEndNs;
3889 }
3890 }
3891 }
3892 // update timing info.
3893 mLastIoBeginNs = lastIoBeginNs;
3894 mLastIoEndNs = lastIoEndNs;
3895 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003896 }
3897 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3898 (mMixerStatus == MIXER_DRAIN_ALL)) {
3899 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003900 }
Andy Hung08fb1742015-05-31 23:22:10 -07003901 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003902
3903 if (mThreadThrottle
3904 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003905 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003906 // Limit MixerThread data processing to no more than twice the
3907 // expected processing rate.
3908 //
3909 // This helps prevent underruns with NuPlayer and other applications
3910 // which may set up buffers that are close to the minimum size, or use
3911 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3912 //
3913 // The throttle smooths out sudden large data drains from the device,
3914 // e.g. when it comes out of standby, which often causes problems with
3915 // (1) mixer threads without a fast mixer (which has its own warm-up)
3916 // (2) minimum buffer sized tracks (even if the track is full,
3917 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003918 //
3919 // Total time spent in last processing cycle equals time spent in
3920 // 1. threadLoop_write, as well as time spent in
3921 // 2. threadLoop_mix (significant for heavy mixing, especially
3922 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003923
Andy Hung446f4df2019-02-21 12:26:41 -08003924 // it's OK if deltaMs is an overestimate.
3925
3926 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003927
Ivan Lozanoea04d392017-11-07 14:37:07 -08003928 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003929 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07003930 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08003931
Andy Hung08fb1742015-05-31 23:22:10 -07003932 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003933 // notify of throttle start on verbose log
3934 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3935 "mixer(%p) throttle begin:"
3936 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003937 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003938 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003939 // Throttle must be attributed to the previous mixer loop's write time
3940 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003941 // This also ensures proper timing statistics.
3942 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003943 } else {
3944 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3945 if (diff > 0) {
3946 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003947 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07003948 ALOGD_IF(!isSingleDeviceType(
3949 outDeviceTypes(), audio_is_a2dp_out_device) &&
3950 !isSingleDeviceType(
3951 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003952 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003953 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3954 }
Andy Hung08fb1742015-05-31 23:22:10 -07003955 }
3956 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003957 }
Eric Laurent81784c32012-11-19 14:55:58 -08003958
Eric Laurentbfb1b832013-01-07 09:53:42 -08003959 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003960 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003961 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003962 // suspended requires accurate metering of sleep time.
3963 if (isSuspended()) {
3964 // advance by expected sleepTime
3965 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3966 const nsecs_t nowNs = systemTime();
3967
3968 // compute expected next time vs current time.
3969 // (negative deltas are treated as delays).
3970 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3971 if (deltaNs < -kMaxNextBufferDelayNs) {
3972 // Delays longer than the max allowed trigger a reset.
3973 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3974 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3975 timeLoopNextNs = nowNs + deltaNs;
3976 } else if (deltaNs < 0) {
3977 // Delays within the max delay allowed: zero the delta/sleepTime
3978 // to help the system catch up in the next iteration(s)
3979 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3980 deltaNs = 0;
3981 }
3982 // update sleep time (which is >= 0)
3983 mSleepTimeUs = deltaNs / 1000;
3984 }
Eric Laurente93cc032016-05-05 10:15:10 -07003985 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3986 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003987 }
Glenn Kastene7754022014-10-31 12:11:26 -07003988 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003989 }
Eric Laurent81784c32012-11-19 14:55:58 -08003990 }
3991
3992 // Finally let go of removed track(s), without the lock held
3993 // since we can't guarantee the destructors won't acquire that
3994 // same lock. This will also mutate and push a new fast mixer state.
3995 threadLoop_removeTracks(tracksToRemove);
3996 tracksToRemove.clear();
3997
3998 // FIXME I don't understand the need for this here;
3999 // it was in the original code but maybe the
4000 // assignment in saveOutputTracks() makes this unnecessary?
4001 clearOutputTracks();
4002
4003 // Effect chains will be actually deleted here if they were removed from
4004 // mEffectChains list during mixing or effects processing
4005 effectChains.clear();
4006
4007 // FIXME Note that the above .clear() is no longer necessary since effectChains
4008 // is now local to this block, but will keep it for now (at least until merge done).
4009 }
4010
Eric Laurentbfb1b832013-01-07 09:53:42 -08004011 threadLoop_exit();
4012
Eric Laurentcf817a22014-08-04 20:36:31 -07004013 if (!mStandby) {
4014 threadLoop_standby();
4015 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004016 }
4017
4018 releaseWakeLock();
4019
4020 ALOGV("Thread %p type %d exiting", this, mType);
4021 return false;
4022}
4023
Dean Wheatley12473e92021-03-18 23:00:55 +11004024void AudioFlinger::PlaybackThread::collectTimestamps_l()
4025{
4026 // Collect timestamp statistics for the Playback Thread types that support it.
4027 if (mType != MIXER
4028 && mType != DUPLICATING
4029 && mType != DIRECT
4030 && mType != OFFLOAD) {
4031 return;
4032 }
4033 if (mStandby) {
4034 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4035 return;
4036 } else if (mHwPaused) {
4037 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4038 return;
4039 }
4040
4041 // Gather the framesReleased counters for all active tracks,
4042 // and associate with the sink frames written out. We need
4043 // this to convert the sink timestamp to the track timestamp.
4044 bool kernelLocationUpdate = false;
4045 ExtendedTimestamp timestamp; // use private copy to fetch
4046
4047 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4048 // HAL may be draining some small duration buffered data for fade out.
4049 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4050 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4051 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4052 mSampleRate);
4053
4054 if (isTimestampCorrectionEnabled()) {
4055 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4056 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4057 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4058 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4059 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4060 = correctedTimestamp.mFrames;
4061 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4062 = correctedTimestamp.mTimeNs;
4063 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4064 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4065 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4066
4067 // Note: Downstream latency only added if timestamp correction enabled.
4068 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4069 const int64_t newPosition =
4070 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4071 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4072 // prevent retrograde
4073 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4074 newPosition,
4075 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4076 - mSuspendedFrames));
4077 }
4078 }
4079
4080 // We always fetch the timestamp here because often the downstream
4081 // sink will block while writing.
4082
4083 // We keep track of the last valid kernel position in case we are in underrun
4084 // and the normal mixer period is the same as the fast mixer period, or there
4085 // is some error from the HAL.
4086 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4087 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4088 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4089 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4090 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4091
4092 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4093 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4094 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4095 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4096 }
4097
4098 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4099 kernelLocationUpdate = true;
4100 } else {
4101 ALOGVV("getTimestamp error - no valid kernel position");
4102 }
4103
4104 // copy over kernel info
4105 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4106 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4107 + mSuspendedFrames; // add frames discarded when suspended
4108 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4109 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4110 } else {
4111 mTimestampVerifier.error();
4112 }
4113
4114 // mFramesWritten for non-offloaded tracks are contiguous
4115 // even after standby() is called. This is useful for the track frame
4116 // to sink frame mapping.
4117 bool serverLocationUpdate = false;
4118 if (mFramesWritten != mLastFramesWritten) {
4119 serverLocationUpdate = true;
4120 mLastFramesWritten = mFramesWritten;
4121 }
4122 // Only update timestamps if there is a meaningful change.
4123 // Either the kernel timestamp must be valid or we have written something.
4124 if (kernelLocationUpdate || serverLocationUpdate) {
4125 if (serverLocationUpdate) {
4126 // use the time before we called the HAL write - it is a bit more accurate
4127 // to when the server last read data than the current time here.
4128 //
4129 // If we haven't written anything, mLastIoBeginNs will be -1
4130 // and we use systemTime().
4131 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4132 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4133 ? systemTime() : mLastIoBeginNs;
4134 }
4135
4136 for (const sp<Track> &t : mActiveTracks) {
4137 if (!t->isFastTrack()) {
4138 t->updateTrackFrameInfo(
4139 t->mAudioTrackServerProxy->framesReleased(),
4140 mFramesWritten,
4141 mSampleRate,
4142 mTimestamp);
4143 }
4144 }
4145 }
4146
4147 if (audio_has_proportional_frames(mFormat)) {
4148 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4149 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4150 mLatencyMs.add(latencyMs);
4151 }
4152 }
4153#if 0
4154 // logFormat example
4155 if (z % 100 == 0) {
4156 timespec ts;
4157 clock_gettime(CLOCK_MONOTONIC, &ts);
4158 LOGT("This is an integer %d, this is a float %f, this is my "
4159 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4160 LOGT("A deceptive null-terminated string %\0");
4161 }
4162 ++z;
4163#endif
4164}
4165
Eric Laurentbfb1b832013-01-07 09:53:42 -08004166// removeTracks_l() must be called with ThreadBase::mLock held
4167void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4168{
Andy Hungfe726a62018-09-27 15:17:25 -07004169 for (const auto& track : tracksToRemove) {
4170 mActiveTracks.remove(track);
4171 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4172 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4173 if (chain != 0) {
4174 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4175 __func__, track->id(), chain.get(), track->sessionId());
4176 chain->decActiveTrackCnt();
4177 }
4178 // If an external client track, inform APM we're no longer active, and remove if needed.
4179 // We do this under lock so that the state is consistent if the Track is destroyed.
4180 if (track->isExternalTrack()) {
4181 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004182 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004183 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004184 }
4185 }
Andy Hungfe726a62018-09-27 15:17:25 -07004186 if (track->isTerminated()) {
4187 // remove from our tracks vector
4188 removeTrack_l(track);
4189 }
jiabineb3bda02020-06-30 14:07:03 -07004190 if (mHapticChannelCount > 0 &&
4191 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4192 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004193 mLock.unlock();
4194 // Unlock due to VibratorService will lock for this call and will
4195 // call Tracks.mute/unmute which also require thread's lock.
4196 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4197 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004198
4199 // When the track is stop, set the haptic intensity as MUTE
4200 // for the HapticGenerator effect.
4201 if (chain != nullptr) {
4202 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4203 }
jiabin245cdd92018-12-07 17:55:15 -08004204 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004205 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004206}
Eric Laurent81784c32012-11-19 14:55:58 -08004207
Eric Laurentaccc1472013-09-20 09:36:34 -07004208status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4209{
4210 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004211 ExtendedTimestamp ets;
4212 status_t status = mNormalSink->getTimestamp(ets);
4213 if (status == NO_ERROR) {
4214 status = ets.getBestTimestamp(&timestamp);
4215 }
4216 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004217 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004218 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004219 collectTimestamps_l();
4220 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4221 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004222 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004223 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4224 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4225 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4226 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4227 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004228 }
4229 return INVALID_OPERATION;
4230}
Eric Laurent1c333e22014-05-20 10:48:17 -07004231
Eric Laurenteab90452019-06-24 15:17:46 -07004232// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4233// still applied by the mixer.
4234// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4235// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4236// if more than one track are active
4237status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4238{
4239 status_t result = NO_ERROR;
4240 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4241 if (*volume != mLeftVolFloat) {
4242 result = mOutput->stream->setVolume(*volume, *volume);
4243 ALOGE_IF(result != OK,
4244 "Error when setting output stream volume: %d", result);
4245 if (result == NO_ERROR) {
4246 mLeftVolFloat = *volume;
4247 }
4248 }
4249 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4250 // remove stream volume contribution from software volume.
4251 if (mLeftVolFloat == *volume) {
4252 *volume = 1.0f;
4253 }
4254 }
4255 return result;
4256}
4257
Eric Laurent054d9d32015-04-24 08:48:48 -07004258status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4259 audio_patch_handle_t *handle)
4260{
Andy Hungf60abce2016-08-26 11:37:54 -07004261 status_t status;
4262 if (property_get_bool("af.patch_park", false /* default_value */)) {
4263 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4264 // or if HAL does not properly lock against access.
4265 AutoPark<FastMixer> park(mFastMixer);
4266 status = PlaybackThread::createAudioPatch_l(patch, handle);
4267 } else {
4268 status = PlaybackThread::createAudioPatch_l(patch, handle);
4269 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004270 return status;
4271}
4272
Eric Laurent1c333e22014-05-20 10:48:17 -07004273status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4274 audio_patch_handle_t *handle)
4275{
4276 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004277
4278 // store new device and send to effects
4279 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004280 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004281 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004282 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4283 && !mOutput->audioHwDev->supportsAudioPatches(),
4284 "Enumerated device type(%#x) must not be used "
4285 "as it does not support audio patches",
4286 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004287 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004288 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4289 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004290 }
4291
François Gaffie0c280aa2018-07-25 10:02:15 +02004292 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004293#ifdef ADD_BATTERY_DATA
4294 // when changing the audio output device, call addBatteryData to notify
4295 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004296 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004297 uint32_t params = 0;
4298 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004299 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004300 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004301 }
4302
Eric Laurent054d9d32015-04-24 08:48:48 -07004303 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004304 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004305 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4306 }
4307
4308 if (params != 0) {
4309 addBatteryData(params);
4310 }
4311 }
4312#endif
4313
4314 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004315 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004316 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004317
jiabinc52b1ff2019-10-31 17:20:42 -07004318 // mPatch.num_sinks is not set when the thread is created so that
4319 // the first patch creation triggers an ioConfigChanged callback
4320 bool configChanged = (mPatch.num_sinks == 0) ||
4321 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004322 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004323 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004324 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004325
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004326 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004327 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4328 status = hwDevice->createAudioPatch(patch->num_sources,
4329 patch->sources,
4330 patch->num_sinks,
4331 patch->sinks,
4332 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004333 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004334 char *address;
4335 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4336 //FIXME: we only support address on first sink with HAL version < 3.0
4337 address = audio_device_address_to_parameter(
4338 patch->sinks[0].ext.device.type,
4339 patch->sinks[0].ext.device.address);
4340 } else {
4341 address = (char *)calloc(1, 1);
4342 }
4343 AudioParameter param = AudioParameter(String8(address));
4344 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004345 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004346 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004347 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004348 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004349 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004350
4351 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004352 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004353 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004354 // also dispatch to active AudioTracks for MediaMetrics
4355 for (const auto &track : mActiveTracks) {
4356 track->logEndInterval();
4357 track->logBeginInterval(patchSinksAsString);
4358 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004359
Eric Laurente8726fe2015-06-26 09:39:24 -07004360 if (configChanged) {
4361 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4362 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004363 return status;
4364}
4365
Eric Laurent054d9d32015-04-24 08:48:48 -07004366status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4367{
Andy Hungf60abce2016-08-26 11:37:54 -07004368 status_t status;
4369 if (property_get_bool("af.patch_park", false /* default_value */)) {
4370 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4371 // or if HAL does not properly lock against access.
4372 AutoPark<FastMixer> park(mFastMixer);
4373 status = PlaybackThread::releaseAudioPatch_l(handle);
4374 } else {
4375 status = PlaybackThread::releaseAudioPatch_l(handle);
4376 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004377 return status;
4378}
4379
Eric Laurent1c333e22014-05-20 10:48:17 -07004380status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4381{
4382 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004383
jiabinc52b1ff2019-10-31 17:20:42 -07004384 mPatch = audio_patch{};
4385 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004386
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004387 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004388 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4389 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004390 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004391 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004392 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004393 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004394 }
4395 return status;
4396}
4397
Eric Laurent83b88082014-06-20 18:31:16 -07004398void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4399{
4400 Mutex::Autolock _l(mLock);
4401 mTracks.add(track);
4402}
4403
4404void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4405{
4406 Mutex::Autolock _l(mLock);
4407 destroyTrack_l(track);
4408}
4409
Mikhail Naganovdc769682018-05-04 15:34:08 -07004410void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004411{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004412 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004413 config->role = AUDIO_PORT_ROLE_SOURCE;
4414 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4415 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004416 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4417 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4418 config->flags.output = mOutput->flags;
4419 }
Eric Laurent83b88082014-06-20 18:31:16 -07004420}
4421
Eric Laurent81784c32012-11-19 14:55:58 -08004422// ----------------------------------------------------------------------------
4423
4424AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004425 audio_io_handle_t id, bool systemReady, type_t type)
4426 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004427 // mAudioMixer below
4428 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004429 mFastMixerFutex(0),
4430 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004431 // mOutputSink below
4432 // mPipeSink below
4433 // mNormalSink below
4434{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004435 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004436 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004437 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004438 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004439 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4440 mNormalFrameCount);
4441 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4442
Andy Hungfbfc3952015-01-15 13:33:51 -08004443 if (type == DUPLICATING) {
4444 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4445 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4446 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4447 return;
4448 }
Eric Laurent81784c32012-11-19 14:55:58 -08004449 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004450 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004451 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004452 const NBAIO_Format offers[1] = {Format_from_SR_C(
4453 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004454#if !LOG_NDEBUG
4455 ssize_t index =
4456#else
4457 (void)
4458#endif
4459 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004460 ALOG_ASSERT(index == 0);
4461
4462 // initialize fast mixer depending on configuration
4463 bool initFastMixer;
4464 switch (kUseFastMixer) {
4465 case FastMixer_Never:
4466 initFastMixer = false;
4467 break;
4468 case FastMixer_Always:
4469 initFastMixer = true;
4470 break;
4471 case FastMixer_Static:
4472 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004473 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4474 // where the period is less than an experimentally determined threshold that can be
4475 // scheduled reliably with CFS. However, the BT A2DP HAL is
4476 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4477 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004478 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004479 break;
4480 }
Andy Hungfda69402017-02-15 14:33:12 -08004481 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4482 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4483 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004484 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004485 audio_format_t fastMixerFormat;
4486 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4487 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4488 } else {
4489 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4490 }
4491 if (mFormat != fastMixerFormat) {
4492 // change our Sink format to accept our intermediate precision
4493 mFormat = fastMixerFormat;
4494 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004495 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004496 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4497 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4498 }
Eric Laurent81784c32012-11-19 14:55:58 -08004499
4500 // create a MonoPipe to connect our submix to FastMixer
4501 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004502
Andy Hung1258c1a2014-05-23 21:22:17 -07004503 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004504 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004505 format.mFormat = fastMixerFormat;
4506 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4507
Eric Laurent81784c32012-11-19 14:55:58 -08004508 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4509 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4510 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4511 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4512 const NBAIO_Format offers[1] = {format};
4513 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004514#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004515 ssize_t index =
4516#else
4517 (void)
4518#endif
4519 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004520 ALOG_ASSERT(index == 0);
4521 monoPipe->setAvgFrames((mScreenState & 1) ?
4522 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4523 mPipeSink = monoPipe;
4524
Eric Laurent81784c32012-11-19 14:55:58 -08004525 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004526 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004527 FastMixerStateQueue *sq = mFastMixer->sq();
4528#ifdef STATE_QUEUE_DUMP
4529 sq->setObserverDump(&mStateQueueObserverDump);
4530 sq->setMutatorDump(&mStateQueueMutatorDump);
4531#endif
4532 FastMixerState *state = sq->begin();
4533 FastTrack *fastTrack = &state->mFastTracks[0];
4534 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4535 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4536 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004537 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4538 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4539 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004540 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004541 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004542 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004543 fastTrack->mGeneration++;
4544 state->mFastTracksGen++;
4545 state->mTrackMask = 1;
4546 // fast mixer will use the HAL output sink
4547 state->mOutputSink = mOutputSink.get();
4548 state->mOutputSinkGen++;
4549 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004550 // specify sink channel mask when haptic channel mask present as it can not
4551 // be calculated directly from channel count
4552 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004553 ? AUDIO_CHANNEL_NONE
4554 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004555 state->mCommand = FastMixerState::COLD_IDLE;
4556 // already done in constructor initialization list
4557 //mFastMixerFutex = 0;
4558 state->mColdFutexAddr = &mFastMixerFutex;
4559 state->mColdGen++;
4560 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004561 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4562 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004563 sq->end();
4564 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4565
Eric Tan0513b5d2018-09-17 10:32:48 -07004566 NBLog::thread_info_t info;
4567 info.id = mId;
4568 info.type = NBLog::FASTMIXER;
4569 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4570
Eric Laurent81784c32012-11-19 14:55:58 -08004571 // start the fast mixer
4572 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4573 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004574 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004575 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004576
4577#ifdef AUDIO_WATCHDOG
4578 // create and start the watchdog
4579 mAudioWatchdog = new AudioWatchdog();
4580 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4581 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4582 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004583 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004584#endif
Andy Hung8946a282018-04-19 20:04:56 -07004585 } else {
4586#ifdef TEE_SINK
4587 // Only use the MixerThread tee if there is no FastMixer.
4588 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4589 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4590#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004591 }
4592
4593 switch (kUseFastMixer) {
4594 case FastMixer_Never:
4595 case FastMixer_Dynamic:
4596 mNormalSink = mOutputSink;
4597 break;
4598 case FastMixer_Always:
4599 mNormalSink = mPipeSink;
4600 break;
4601 case FastMixer_Static:
4602 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4603 break;
4604 }
4605}
4606
4607AudioFlinger::MixerThread::~MixerThread()
4608{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004609 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004610 FastMixerStateQueue *sq = mFastMixer->sq();
4611 FastMixerState *state = sq->begin();
4612 if (state->mCommand == FastMixerState::COLD_IDLE) {
4613 int32_t old = android_atomic_inc(&mFastMixerFutex);
4614 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004615 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004616 }
4617 }
4618 state->mCommand = FastMixerState::EXIT;
4619 sq->end();
4620 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4621 mFastMixer->join();
4622 // Though the fast mixer thread has exited, it's state queue is still valid.
4623 // We'll use that extract the final state which contains one remaining fast track
4624 // corresponding to our sub-mix.
4625 state = sq->begin();
4626 ALOG_ASSERT(state->mTrackMask == 1);
4627 FastTrack *fastTrack = &state->mFastTracks[0];
4628 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4629 delete fastTrack->mBufferProvider;
4630 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004631 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004632#ifdef AUDIO_WATCHDOG
4633 if (mAudioWatchdog != 0) {
4634 mAudioWatchdog->requestExit();
4635 mAudioWatchdog->requestExitAndWait();
4636 mAudioWatchdog.clear();
4637 }
4638#endif
4639 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004640 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004641 delete mAudioMixer;
4642}
4643
4644
4645uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4646{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004647 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004648 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4649 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4650 }
4651 return latency;
4652}
4653
Eric Laurentbfb1b832013-01-07 09:53:42 -08004654ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004655{
4656 // FIXME we should only do one push per cycle; confirm this is true
4657 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004658 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004659 FastMixerStateQueue *sq = mFastMixer->sq();
4660 FastMixerState *state = sq->begin();
4661 if (state->mCommand != FastMixerState::MIX_WRITE &&
4662 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4663 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004664
4665 // FIXME workaround for first HAL write being CPU bound on some devices
4666 ATRACE_BEGIN("write");
4667 mOutput->write((char *)mSinkBuffer, 0);
4668 ATRACE_END();
4669
Eric Laurent81784c32012-11-19 14:55:58 -08004670 int32_t old = android_atomic_inc(&mFastMixerFutex);
4671 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004672 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004673 }
4674#ifdef AUDIO_WATCHDOG
4675 if (mAudioWatchdog != 0) {
4676 mAudioWatchdog->resume();
4677 }
4678#endif
4679 }
4680 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004681#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004682 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004683 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004684#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004685 sq->end();
4686 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4687 if (kUseFastMixer == FastMixer_Dynamic) {
4688 mNormalSink = mPipeSink;
4689 }
4690 } else {
4691 sq->end(false /*didModify*/);
4692 }
4693 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004694 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004695}
4696
4697void AudioFlinger::MixerThread::threadLoop_standby()
4698{
4699 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004700 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004701 FastMixerStateQueue *sq = mFastMixer->sq();
4702 FastMixerState *state = sq->begin();
4703 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004704 // Report any frames trapped in the Monopipe
4705 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4706 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4707 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4708 "monoPipeWritten:%lld monoPipeLeft:%lld",
4709 (long long)mFramesWritten, (long long)mSuspendedFrames,
4710 (long long)mPipeSink->framesWritten(), pipeFrames);
4711 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4712
Eric Laurent81784c32012-11-19 14:55:58 -08004713 state->mCommand = FastMixerState::COLD_IDLE;
4714 state->mColdFutexAddr = &mFastMixerFutex;
4715 state->mColdGen++;
4716 mFastMixerFutex = 0;
4717 sq->end();
4718 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4719 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4720 if (kUseFastMixer == FastMixer_Dynamic) {
4721 mNormalSink = mOutputSink;
4722 }
4723#ifdef AUDIO_WATCHDOG
4724 if (mAudioWatchdog != 0) {
4725 mAudioWatchdog->pause();
4726 }
4727#endif
4728 } else {
4729 sq->end(false /*didModify*/);
4730 }
4731 }
4732 PlaybackThread::threadLoop_standby();
4733}
4734
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4736{
4737 return false;
4738}
4739
4740bool AudioFlinger::PlaybackThread::shouldStandby_l()
4741{
4742 return !mStandby;
4743}
4744
4745bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4746{
4747 Mutex::Autolock _l(mLock);
4748 return waitingAsyncCallback_l();
4749}
4750
Eric Laurent81784c32012-11-19 14:55:58 -08004751// shared by MIXER and DIRECT, overridden by DUPLICATING
4752void AudioFlinger::PlaybackThread::threadLoop_standby()
4753{
4754 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004755 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004756 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004757 // discard any pending drain or write ack by incrementing sequence
4758 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4759 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004760 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004761 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4762 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004763 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004764 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004765}
4766
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004767void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4768{
4769 ALOGV("signal playback thread");
4770 broadcast_l();
4771}
4772
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004773void AudioFlinger::PlaybackThread::onAsyncError()
4774{
4775 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4776 invalidateTracks((audio_stream_type_t)i);
4777 }
4778}
4779
Eric Laurent81784c32012-11-19 14:55:58 -08004780void AudioFlinger::MixerThread::threadLoop_mix()
4781{
Eric Laurent81784c32012-11-19 14:55:58 -08004782 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004783 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004784 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004785 // increase sleep time progressively when application underrun condition clears.
4786 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4787 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4788 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004789 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004790 sleepTimeShift--;
4791 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004792 mSleepTimeUs = 0;
4793 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004794 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004795
Eric Laurent81784c32012-11-19 14:55:58 -08004796}
4797
4798void AudioFlinger::MixerThread::threadLoop_sleepTime()
4799{
4800 // If no tracks are ready, sleep once for the duration of an output
4801 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004802 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004803 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004804 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4805 // Using the Monopipe availableToWrite, we estimate the
4806 // sleep time to retry for more data (before we underrun).
4807 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4808 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4809 const size_t pipeFrames = monoPipe->maxFrames();
4810 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4811 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4812 const size_t framesDelay = std::min(
4813 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4814 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4815 pipeFrames, framesLeft, framesDelay);
4816 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4817 } else {
4818 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4819 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4820 mSleepTimeUs = kMinThreadSleepTimeUs;
4821 }
4822 // reduce sleep time in case of consecutive application underruns to avoid
4823 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4824 // duration we would end up writing less data than needed by the audio HAL if
4825 // the condition persists.
4826 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4827 sleepTimeShift++;
4828 }
Eric Laurent81784c32012-11-19 14:55:58 -08004829 }
4830 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004831 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004832 }
4833 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004834 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4835 // before effects processing or output.
4836 if (mMixerBufferValid) {
4837 memset(mMixerBuffer, 0, mMixerBufferSize);
4838 } else {
4839 memset(mSinkBuffer, 0, mSinkBufferSize);
4840 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004841 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004842 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4843 "anticipated start");
4844 }
4845 // TODO add standby time extension fct of effect tail
4846}
4847
4848// prepareTracks_l() must be called with ThreadBase::mLock held
4849AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4850 Vector< sp<Track> > *tracksToRemove)
4851{
Andy Hungc0691382018-09-12 18:01:57 -07004852 // clean up deleted track ids in AudioMixer before allocating new tracks
4853 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4854 // for each trackId, destroy it in the AudioMixer
4855 if (mAudioMixer->exists(trackId)) {
4856 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004857 }
4858 });
Andy Hungc0691382018-09-12 18:01:57 -07004859 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004860
4861 mixer_state mixerStatus = MIXER_IDLE;
4862 // find out which tracks need to be processed
4863 size_t count = mActiveTracks.size();
4864 size_t mixedTracks = 0;
4865 size_t tracksWithEffect = 0;
4866 // counts only _active_ fast tracks
4867 size_t fastTracks = 0;
4868 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4869
4870 float masterVolume = mMasterVolume;
4871 bool masterMute = mMasterMute;
4872
4873 if (masterMute) {
4874 masterVolume = 0;
4875 }
4876 // Delegate master volume control to effect in output mix effect chain if needed
4877 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4878 if (chain != 0) {
4879 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4880 chain->setVolume_l(&v, &v);
4881 masterVolume = (float)((v + (1 << 23)) >> 24);
4882 chain.clear();
4883 }
4884
4885 // prepare a new state to push
4886 FastMixerStateQueue *sq = NULL;
4887 FastMixerState *state = NULL;
4888 bool didModify = false;
4889 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004890 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004891 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004892 sq = mFastMixer->sq();
4893 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004894 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004895 }
4896
Andy Hung69aed5f2014-02-25 17:24:40 -08004897 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004898 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004899
Andy Hungbd3b2b02018-05-21 10:53:11 -07004900 // DeferredOperations handles statistics after setting mixerStatus.
4901 class DeferredOperations {
4902 public:
Andy Hungea840382020-05-05 21:50:17 -07004903 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4904 : mMixerStatus(mixerStatus)
4905 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004906
4907 // when leaving scope, tally frames properly.
4908 ~DeferredOperations() {
4909 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4910 // because that is when the underrun occurs.
4911 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004912 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004913 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004914 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004915 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004916 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004917 }
4918 }
Andy Hungea840382020-05-05 21:50:17 -07004919 // send the max underrun frames for this mixer period
4920 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004921 }
4922
4923 // tallyUnderrunFrames() is called to update the track counters
4924 // with the number of underrun frames for a particular mixer period.
4925 // We defer tallying until we know the final mixer status.
4926 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4927 mUnderrunFrames.emplace_back(track, underrunFrames);
4928 }
4929
4930 private:
4931 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004932 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004933 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004934 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004935 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004936
jiabin245cdd92018-12-07 17:55:15 -08004937 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004938 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004939 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004940
4941 // this const just means the local variable doesn't change
4942 Track* const track = t.get();
4943
4944 // process fast tracks
4945 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004946 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4947 "%s(%d): FastTrack(%d) present without FastMixer",
4948 __func__, id(), track->id());
4949
jiabin245cdd92018-12-07 17:55:15 -08004950 if (track->getHapticPlaybackEnabled()) {
4951 noFastHapticTrack = false;
4952 }
Eric Laurent81784c32012-11-19 14:55:58 -08004953
4954 // It's theoretically possible (though unlikely) for a fast track to be created
4955 // and then removed within the same normal mix cycle. This is not a problem, as
4956 // the track never becomes active so it's fast mixer slot is never touched.
4957 // The converse, of removing an (active) track and then creating a new track
4958 // at the identical fast mixer slot within the same normal mix cycle,
4959 // is impossible because the slot isn't marked available until the end of each cycle.
4960 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004961 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004962 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4963 FastTrack *fastTrack = &state->mFastTracks[j];
4964
4965 // Determine whether the track is currently in underrun condition,
4966 // and whether it had a recent underrun.
4967 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4968 FastTrackUnderruns underruns = ftDump->mUnderruns;
4969 uint32_t recentFull = (underruns.mBitFields.mFull -
4970 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4971 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4972 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4973 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4974 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4975 uint32_t recentUnderruns = recentPartial + recentEmpty;
4976 track->mObservedUnderruns = underruns;
4977 // don't count underruns that occur while stopping or pausing
4978 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004979 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004980 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4981 recentUnderruns > 0) {
4982 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004983 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004984 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004985 // Immediately account for FastTrack underruns.
4986 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004987
4988 // This is similar to the state machine for normal tracks,
4989 // with a few modifications for fast tracks.
4990 bool isActive = true;
4991 switch (track->mState) {
4992 case TrackBase::STOPPING_1:
4993 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004994 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004995 track->mState = TrackBase::STOPPING_2;
4996 }
4997 break;
4998 case TrackBase::PAUSING:
4999 // ramp down is not yet implemented
5000 track->setPaused();
5001 break;
5002 case TrackBase::RESUMING:
5003 // ramp up is not yet implemented
5004 track->mState = TrackBase::ACTIVE;
5005 break;
5006 case TrackBase::ACTIVE:
5007 if (recentFull > 0 || recentPartial > 0) {
5008 // track has provided at least some frames recently: reset retry count
5009 track->mRetryCount = kMaxTrackRetries;
5010 }
5011 if (recentUnderruns == 0) {
5012 // no recent underruns: stay active
5013 break;
5014 }
5015 // there has recently been an underrun of some kind
5016 if (track->sharedBuffer() == 0) {
5017 // were any of the recent underruns "empty" (no frames available)?
5018 if (recentEmpty == 0) {
5019 // no, then ignore the partial underruns as they are allowed indefinitely
5020 break;
5021 }
5022 // there has recently been an "empty" underrun: decrement the retry counter
5023 if (--(track->mRetryCount) > 0) {
5024 break;
5025 }
5026 // indicate to client process that the track was disabled because of underrun;
5027 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005028 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005029 // remove from active list, but state remains ACTIVE [confusing but true]
5030 isActive = false;
5031 break;
5032 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005033 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005034 case TrackBase::STOPPING_2:
5035 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005036 case TrackBase::STOPPED:
5037 case TrackBase::FLUSHED: // flush() while active
5038 // Check for presentation complete if track is inactive
5039 // We have consumed all the buffers of this track.
5040 // This would be incomplete if we auto-paused on underrun
5041 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005042 uint32_t latency = 0;
5043 status_t result = mOutput->stream->getLatency(&latency);
5044 ALOGE_IF(result != OK,
5045 "Error when retrieving output stream latency: %d", result);
5046 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005047 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005048 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5049 // track stays in active list until presentation is complete
5050 break;
5051 }
5052 }
5053 if (track->isStopping_2()) {
5054 track->mState = TrackBase::STOPPED;
5055 }
5056 if (track->isStopped()) {
5057 // Can't reset directly, as fast mixer is still polling this track
5058 // track->reset();
5059 // So instead mark this track as needing to be reset after push with ack
5060 resetMask |= 1 << i;
5061 }
5062 isActive = false;
5063 break;
5064 case TrackBase::IDLE:
5065 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005066 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005067 }
5068
5069 if (isActive) {
5070 // was it previously inactive?
5071 if (!(state->mTrackMask & (1 << j))) {
5072 ExtendedAudioBufferProvider *eabp = track;
5073 VolumeProvider *vp = track;
5074 fastTrack->mBufferProvider = eabp;
5075 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005076 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005077 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005078 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005079 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005080 fastTrack->mGeneration++;
5081 state->mTrackMask |= 1 << j;
5082 didModify = true;
5083 // no acknowledgement required for newly active tracks
5084 }
Kevin Rocard12381092018-04-11 09:19:59 -07005085 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005086 float volume;
5087 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5088 volume = 0.f;
5089 } else {
5090 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5091 }
5092
5093 handleVoipVolume_l(&volume);
5094
Eric Laurent81784c32012-11-19 14:55:58 -08005095 // cache the combined master volume and stream type volume for fast mixer; this
5096 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005097 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005098 proxy->framesReleased()).first;
5099 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005100 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005101 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5102 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5103 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005104
Kevin Rocard12381092018-04-11 09:19:59 -07005105 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005106 ++fastTracks;
5107 } else {
5108 // was it previously active?
5109 if (state->mTrackMask & (1 << j)) {
5110 fastTrack->mBufferProvider = NULL;
5111 fastTrack->mGeneration++;
5112 state->mTrackMask &= ~(1 << j);
5113 didModify = true;
5114 // If any fast tracks were removed, we must wait for acknowledgement
5115 // because we're about to decrement the last sp<> on those tracks.
5116 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5117 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005118 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5119 // AudioTrack may start (which may not be with a start() but with a write()
5120 // after underrun) and immediately paused or released. In that case the
5121 // FastTrack state hasn't had time to update.
5122 // TODO Remove the ALOGW when this theory is confirmed.
5123 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005124 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5125 j, track->mState, state->mTrackMask, recentUnderruns,
5126 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005127 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005128 }
5129 tracksToRemove->add(track);
5130 // Avoids a misleading display in dumpsys
5131 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5132 }
jiabin245cdd92018-12-07 17:55:15 -08005133 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5134 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5135 didModify = true;
5136 }
Eric Laurent81784c32012-11-19 14:55:58 -08005137 continue;
5138 }
5139
5140 { // local variable scope to avoid goto warning
5141
5142 audio_track_cblk_t* cblk = track->cblk();
5143
5144 // The first time a track is added we wait
5145 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005146 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005147
5148 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005149 // use the trackId as the AudioMixer name.
5150 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005151 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005152 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005153 track->mChannelMask,
5154 track->mFormat,
5155 track->mSessionId);
5156 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005157 ALOGW("%s(): AudioMixer cannot create track(%d)"
5158 " mask %#x, format %#x, sessionId %d",
5159 __func__, trackId,
5160 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005161 tracksToRemove->add(track);
5162 track->invalidate(); // consider it dead.
5163 continue;
5164 }
5165 }
5166
Eric Laurent81784c32012-11-19 14:55:58 -08005167 // make sure that we have enough frames to mix one full buffer.
5168 // enforce this condition only once to enable draining the buffer in case the client
5169 // app does not call stop() and relies on underrun to stop:
5170 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5171 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005172 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005173 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005174 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005175
5176 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005177 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005178 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5179 // add frames already consumed but not yet released by the resampler
5180 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005181 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005182
Eric Laurent81784c32012-11-19 14:55:58 -08005183 uint32_t minFrames = 1;
5184 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5185 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005186 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005187 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005188
5189 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005190 if (ATRACE_ENABLED()) {
5191 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005192 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005193 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005194 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005195 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005196 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005197 !track->isPaused() && !track->isTerminated())
5198 {
Andy Hungc0691382018-09-12 18:01:57 -07005199 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005200
5201 mixedTracks++;
5202
Andy Hung69aed5f2014-02-25 17:24:40 -08005203 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5204 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005205 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005206 if (track->mainBuffer() != mSinkBuffer &&
5207 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005208 if (mEffectBufferEnabled) {
5209 mEffectBufferValid = true; // Later can set directly.
5210 }
Eric Laurent81784c32012-11-19 14:55:58 -08005211 chain = getEffectChain_l(track->sessionId());
5212 // Delegate volume control to effect in track effect chain if needed
5213 if (chain != 0) {
5214 tracksWithEffect++;
5215 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005216 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005217 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005218 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005219 }
5220 }
5221
5222
5223 int param = AudioMixer::VOLUME;
5224 if (track->mFillingUpStatus == Track::FS_FILLED) {
5225 // no ramp for the first volume setting
5226 track->mFillingUpStatus = Track::FS_ACTIVE;
5227 if (track->mState == TrackBase::RESUMING) {
5228 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005229 // If a new track is paused immediately after start, do not ramp on resume.
5230 if (cblk->mServer != 0) {
5231 param = AudioMixer::RAMP_VOLUME;
5232 }
Eric Laurent81784c32012-11-19 14:55:58 -08005233 }
Andy Hungc0691382018-09-12 18:01:57 -07005234 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005235 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005236 // FIXME should not make a decision based on mServer
5237 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005238 // If the track is stopped before the first frame was mixed,
5239 // do not apply ramp
5240 param = AudioMixer::RAMP_VOLUME;
5241 }
5242
5243 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005244 uint32_t vl, vr; // in U8.24 integer format
5245 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005246 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005247 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005248 // Always fetch volumeshaper volume to ensure state is updated.
5249 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5250 const float vh = track->getVolumeHandler()->getVolume(
5251 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005252
Eric Laurenteab90452019-06-24 15:17:46 -07005253 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5254 v = 0;
5255 }
5256
5257 handleVoipVolume_l(&v);
5258
5259 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005260 vl = vr = 0;
5261 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005262 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005263 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005264 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005265 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5266 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005267 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005268 if (vlf > GAIN_FLOAT_UNITY) {
5269 ALOGV("Track left volume out of range: %.3g", vlf);
5270 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005271 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005272 if (vrf > GAIN_FLOAT_UNITY) {
5273 ALOGV("Track right volume out of range: %.3g", vrf);
5274 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005275 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005276 // now apply the master volume and stream type volume and shaper volume
5277 vlf *= v * vh;
5278 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005279 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005280 // then derive vl and vr as U8.24 versions for the effect chain
5281 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5282 vl = (uint32_t) (scaleto8_24 * vlf);
5283 vr = (uint32_t) (scaleto8_24 * vrf);
5284 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005285 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005286 // send level comes from shared memory and so may be corrupt
5287 if (sendLevel > MAX_GAIN_INT) {
5288 ALOGV("Track send level out of range: %04X", sendLevel);
5289 sendLevel = MAX_GAIN_INT;
5290 }
Andy Hung6be49402014-05-30 10:42:03 -07005291 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5292 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005293 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005294
Kevin Rocard12381092018-04-11 09:19:59 -07005295 track->setFinalVolume((vrf + vlf) / 2.f);
5296
Eric Laurent81784c32012-11-19 14:55:58 -08005297 // Delegate volume control to effect in track effect chain if needed
5298 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5299 // Do not ramp volume if volume is controlled by effect
5300 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005301 // Update remaining floating point volume levels
5302 vlf = (float)vl / (1 << 24);
5303 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005304 track->mHasVolumeController = true;
5305 } else {
5306 // force no volume ramp when volume controller was just disabled or removed
5307 // from effect chain to avoid volume spike
5308 if (track->mHasVolumeController) {
5309 param = AudioMixer::VOLUME;
5310 }
5311 track->mHasVolumeController = false;
5312 }
5313
Eric Laurent81784c32012-11-19 14:55:58 -08005314 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005315 mAudioMixer->setBufferProvider(trackId, track);
5316 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005317
Andy Hungc0691382018-09-12 18:01:57 -07005318 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5319 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5320 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005321 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005322 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005323 AudioMixer::TRACK,
5324 AudioMixer::FORMAT, (void *)track->format());
5325 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005326 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005327 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005328 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005329 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005330 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005331 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005332 AudioMixer::MIXER_CHANNEL_MASK,
5333 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005334 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005335 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005336 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005337 if (reqSampleRate == 0) {
5338 reqSampleRate = mSampleRate;
5339 } else if (reqSampleRate > maxSampleRate) {
5340 reqSampleRate = maxSampleRate;
5341 }
Eric Laurent81784c32012-11-19 14:55:58 -08005342 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005343 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005344 AudioMixer::RESAMPLE,
5345 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005346 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005347
Andy Hung333ab962019-05-28 20:23:35 -07005348 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005349 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005350 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005351 AudioMixer::TIMESTRETCH,
5352 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005353 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005354
Andy Hung69aed5f2014-02-25 17:24:40 -08005355 /*
5356 * Select the appropriate output buffer for the track.
5357 *
Andy Hung98ef9782014-03-04 14:46:50 -08005358 * Tracks with effects go into their own effects chain buffer
5359 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005360 *
5361 * Other tracks can use mMixerBuffer for higher precision
5362 * channel accumulation. If this buffer is enabled
5363 * (mMixerBufferEnabled true), then selected tracks will accumulate
5364 * into it.
5365 *
5366 */
5367 if (mMixerBufferEnabled
5368 && (track->mainBuffer() == mSinkBuffer
5369 || track->mainBuffer() == mMixerBuffer)) {
5370 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005371 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005372 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005373 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005374 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005375 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005376 AudioMixer::TRACK,
5377 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5378 // TODO: override track->mainBuffer()?
5379 mMixerBufferValid = true;
5380 } else {
5381 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005382 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005383 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005384 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005385 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005386 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005387 AudioMixer::TRACK,
5388 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5389 }
Eric Laurent81784c32012-11-19 14:55:58 -08005390 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005391 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005392 AudioMixer::TRACK,
5393 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005394 mAudioMixer->setParameter(
5395 trackId,
5396 AudioMixer::TRACK,
5397 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005398 mAudioMixer->setParameter(
5399 trackId,
5400 AudioMixer::TRACK,
5401 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005402
5403 // reset retry count
5404 track->mRetryCount = kMaxTrackRetries;
5405
5406 // If one track is ready, set the mixer ready if:
5407 // - the mixer was not ready during previous round OR
5408 // - no other track is not ready
5409 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5410 mixerStatus != MIXER_TRACKS_ENABLED) {
5411 mixerStatus = MIXER_TRACKS_READY;
5412 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005413
5414 // Enable the next few lines to instrument a test for underrun log handling.
5415 // TODO: Remove when we have a better way of testing the underrun log.
5416#if 0
5417 static int i;
5418 if ((++i & 0xf) == 0) {
5419 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5420 }
5421#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005422 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005423 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005424 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005425 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5426 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005427 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005428 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005429 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005430
Eric Laurent81784c32012-11-19 14:55:58 -08005431 // clear effect chain input buffer if an active track underruns to avoid sending
5432 // previous audio buffer again to effects
5433 chain = getEffectChain_l(track->sessionId());
5434 if (chain != 0) {
5435 chain->clearInputBuffer();
5436 }
5437
Andy Hungc0691382018-09-12 18:01:57 -07005438 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005439 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5440 track->isStopped() || track->isPaused()) {
5441 // We have consumed all the buffers of this track.
5442 // Remove it from the list of active tracks.
5443 // TODO: use actual buffer filling status instead of latency when available from
5444 // audio HAL
5445 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005446 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005447 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5448 if (track->isStopped()) {
5449 track->reset();
5450 }
5451 tracksToRemove->add(track);
5452 }
5453 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005454 // No buffers for this track. Give it a few chances to
5455 // fill a buffer, then remove it from active list.
5456 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005457 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5458 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005459 tracksToRemove->add(track);
5460 // indicate to client process that the track was disabled because of underrun;
5461 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005462 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005463 // If one track is not ready, mark the mixer also not ready if:
5464 // - the mixer was ready during previous round OR
5465 // - no other track is ready
5466 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5467 mixerStatus != MIXER_TRACKS_READY) {
5468 mixerStatus = MIXER_TRACKS_ENABLED;
5469 }
5470 }
Andy Hungc0691382018-09-12 18:01:57 -07005471 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005472 }
5473
5474 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005475
5476 }
5477
jiabin245cdd92018-12-07 17:55:15 -08005478 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5479 // When there is no fast track playing haptic and FastMixer exists,
5480 // enabling the first FastTrack, which provides mixed data from normal
5481 // tracks, to play haptic data.
5482 FastTrack *fastTrack = &state->mFastTracks[0];
5483 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5484 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5485 didModify = true;
5486 }
5487 }
5488
Eric Laurent81784c32012-11-19 14:55:58 -08005489 // Push the new FastMixer state if necessary
5490 bool pauseAudioWatchdog = false;
5491 if (didModify) {
5492 state->mFastTracksGen++;
5493 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5494 if (kUseFastMixer == FastMixer_Dynamic &&
5495 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5496 state->mCommand = FastMixerState::COLD_IDLE;
5497 state->mColdFutexAddr = &mFastMixerFutex;
5498 state->mColdGen++;
5499 mFastMixerFutex = 0;
5500 if (kUseFastMixer == FastMixer_Dynamic) {
5501 mNormalSink = mOutputSink;
5502 }
5503 // If we go into cold idle, need to wait for acknowledgement
5504 // so that fast mixer stops doing I/O.
5505 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5506 pauseAudioWatchdog = true;
5507 }
Eric Laurent81784c32012-11-19 14:55:58 -08005508 }
5509 if (sq != NULL) {
5510 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005511 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5512 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5513 // when bringing the output sink into standby.)
5514 //
5515 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5516 //
5517 // This occurs with BT suspend when we idle the FastMixer with
5518 // active tracks, which may be added or removed.
5519 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005520 }
5521#ifdef AUDIO_WATCHDOG
5522 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5523 mAudioWatchdog->pause();
5524 }
5525#endif
5526
5527 // Now perform the deferred reset on fast tracks that have stopped
5528 while (resetMask != 0) {
5529 size_t i = __builtin_ctz(resetMask);
5530 ALOG_ASSERT(i < count);
5531 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005532 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005533 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5534 track->reset();
5535 }
5536
Andy Hung80d03d22018-04-10 10:32:11 -07005537 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5538 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5539 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5540 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5541 // See also the implementation of destroyTrack_l().
5542 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005543 const int trackId = track->id();
5544 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5545 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005546 }
5547 }
5548
Eric Laurent81784c32012-11-19 14:55:58 -08005549 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005550 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005551
Eric Laurent97d547d2014-09-02 14:45:53 -07005552 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5553 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005554 }
5555
5556 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005557 // as long as there are effects we should clear the effects buffer, to avoid
5558 // passing a non-clean buffer to the effect chain
5559 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005560 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005561 // sink or mix buffer must be cleared if all tracks are connected to an
5562 // effect chain as in this case the mixer will not write to the sink or mix buffer
5563 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005564 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5565 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005566 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005567 if (mMixerBufferValid) {
5568 memset(mMixerBuffer, 0, mMixerBufferSize);
5569 // TODO: In testing, mSinkBuffer below need not be cleared because
5570 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5571 // after mixing.
5572 //
5573 // To enforce this guarantee:
5574 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5575 // (mixedTracks == 0 && fastTracks > 0))
5576 // must imply MIXER_TRACKS_READY.
5577 // Later, we may clear buffers regardless, and skip much of this logic.
5578 }
Andy Hung98ef9782014-03-04 14:46:50 -08005579 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005580 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005581 }
5582
5583 // if any fast tracks, then status is ready
5584 mMixerStatusIgnoringFastTracks = mixerStatus;
5585 if (fastTracks > 0) {
5586 mixerStatus = MIXER_TRACKS_READY;
5587 }
5588 return mixerStatus;
5589}
5590
Eric Laurentad7dd962016-09-22 12:38:37 -07005591// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005592uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005593{
5594 uint32_t trackCount = 0;
5595 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005596 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005597 trackCount++;
5598 }
5599 }
5600 return trackCount;
5601}
5602
Andy Hung1bc088a2018-02-09 15:57:31 -08005603// isTrackAllowed_l() must be called with ThreadBase::mLock held
5604bool AudioFlinger::MixerThread::isTrackAllowed_l(
5605 audio_channel_mask_t channelMask, audio_format_t format,
5606 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005607{
Andy Hung1bc088a2018-02-09 15:57:31 -08005608 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5609 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005610 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005611 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005612 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005613 ALOGW("%s: invalid format: %#x", __func__, format);
5614 return false;
5615 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005616 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005617 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5618 return false;
5619 }
5620 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005621}
5622
Eric Laurent10351942014-05-08 18:49:52 -07005623// checkForNewParameter_l() must be called with ThreadBase::mLock held
5624bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5625 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005626{
Eric Laurent81784c32012-11-19 14:55:58 -08005627 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005628 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005629
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005630 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005631
Eric Laurent10351942014-05-08 18:49:52 -07005632 AudioParameter param = AudioParameter(keyValuePair);
5633 int value;
5634 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5635 reconfig = true;
5636 }
5637 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005638 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005639 status = BAD_VALUE;
5640 } else {
5641 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005642 reconfig = true;
5643 }
Eric Laurent10351942014-05-08 18:49:52 -07005644 }
5645 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005646 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005647 status = BAD_VALUE;
5648 } else {
5649 // no need to save value, since it's constant
5650 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005651 }
Eric Laurent10351942014-05-08 18:49:52 -07005652 }
5653 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5654 // do not accept frame count changes if tracks are open as the track buffer
5655 // size depends on frame count and correct behavior would not be guaranteed
5656 // if frame count is changed after track creation
5657 if (!mTracks.isEmpty()) {
5658 status = INVALID_OPERATION;
5659 } else {
5660 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005661 }
Eric Laurent10351942014-05-08 18:49:52 -07005662 }
5663 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005664 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005665 }
Eric Laurent81784c32012-11-19 14:55:58 -08005666
Eric Laurent10351942014-05-08 18:49:52 -07005667 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005668 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005669 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005670 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005671 if (!mStandby) {
5672 mThreadMetrics.logEndInterval();
5673 mStandby = true;
5674 }
Eric Laurent10351942014-05-08 18:49:52 -07005675 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005676 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005677 }
Eric Laurent10351942014-05-08 18:49:52 -07005678 if (status == NO_ERROR && reconfig) {
5679 readOutputParameters_l();
5680 delete mAudioMixer;
5681 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005682 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005683 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005684 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005685 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005686 track->mChannelMask,
5687 track->mFormat,
5688 track->mSessionId);
5689 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005690 "%s(): AudioMixer cannot create track(%d)"
5691 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005692 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005693 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005694 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005695 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005696 }
Eric Laurent81784c32012-11-19 14:55:58 -08005697 }
5698
Dean Wheatley68918102021-03-19 22:09:19 +11005699 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005700}
5701
5702
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005703void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005704{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005705 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005706 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005707 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005708 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005709 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5710 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5711 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005712 if (hasFastMixer()) {
5713 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5714
5715 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5716 // while we are dumping it. It may be inconsistent, but it won't mutate!
5717 // This is a large object so we place it on the heap.
5718 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005719 const std::unique_ptr<FastMixerDumpState> copy =
5720 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005721 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005722
5723#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005724 // Similar for state queue
5725 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5726 observerCopy.dump(fd);
5727 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5728 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005729#endif
5730
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005731#ifdef AUDIO_WATCHDOG
5732 if (mAudioWatchdog != 0) {
5733 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5734 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5735 wdCopy.dump(fd);
5736 }
5737#endif
5738
5739 } else {
5740 dprintf(fd, " No FastMixer\n");
5741 }
Eric Laurent81784c32012-11-19 14:55:58 -08005742}
5743
5744uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5745{
5746 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5747}
5748
5749uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5750{
5751 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5752}
5753
5754void AudioFlinger::MixerThread::cacheParameters_l()
5755{
5756 PlaybackThread::cacheParameters_l();
5757
5758 // FIXME: Relaxed timing because of a certain device that can't meet latency
5759 // Should be reduced to 2x after the vendor fixes the driver issue
5760 // increase threshold again due to low power audio mode. The way this warning
5761 // threshold is calculated and its usefulness should be reconsidered anyway.
5762 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5763}
5764
5765// ----------------------------------------------------------------------------
5766
5767AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005768 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5769 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005770{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005771 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005772}
5773
Eric Laurent81784c32012-11-19 14:55:58 -08005774AudioFlinger::DirectOutputThread::~DirectOutputThread()
5775{
5776}
5777
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005778void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005779{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005780 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005781 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5782 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5783}
5784
5785void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5786{
5787 Mutex::Autolock _l(mLock);
5788 if (mMasterBalance != balance) {
5789 mMasterBalance.store(balance);
5790 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5791 broadcast_l();
5792 }
5793}
5794
Eric Laurent5850c4c2016-11-10 13:04:31 -08005795void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005796{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005797 float left, right;
5798
Andy Hung333ab962019-05-28 20:23:35 -07005799 // Ensure volumeshaper state always advances even when muted.
5800 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5801 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5802 proxy->framesReleased());
5803 mVolumeShaperActive = shaperActive;
5804
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005805 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005806 left = right = 0;
5807 } else {
5808 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005809 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005810
Glenn Kastenc56f3422014-03-21 17:53:17 -07005811 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5812 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5813 if (left > GAIN_FLOAT_UNITY) {
5814 left = GAIN_FLOAT_UNITY;
5815 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005816 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005817 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5818 if (right > GAIN_FLOAT_UNITY) {
5819 right = GAIN_FLOAT_UNITY;
5820 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005821 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005822 }
5823
5824 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005825 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005826 if (left != mLeftVolFloat || right != mRightVolFloat) {
5827 mLeftVolFloat = left;
5828 mRightVolFloat = right;
5829
Eric Laurentbfb1b832013-01-07 09:53:42 -08005830 // Delegate volume control to effect in track effect chain if needed
5831 // only one effect chain can be present on DirectOutputThread, so if
5832 // there is one, the track is connected to it
5833 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005834 // if effect chain exists, volume is handled by it.
5835 // Convert volumes from float to 8.24
5836 uint32_t vl = (uint32_t)(left * (1 << 24));
5837 uint32_t vr = (uint32_t)(right * (1 << 24));
5838 // Direct/Offload effect chains set output volume in setVolume_l().
5839 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5840 } else {
5841 // otherwise we directly set the volume.
5842 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005843 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005844 }
5845 }
5846}
5847
Phil Burk43b4dcc2015-06-09 16:53:44 -07005848void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5849{
5850 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005851 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005852
Eric Laurent0f0631e2015-07-06 18:01:25 -07005853 if (previousTrack != 0 && latestTrack != 0) {
5854 if (mType == DIRECT) {
5855 if (previousTrack.get() != latestTrack.get()) {
5856 mFlushPending = true;
5857 }
5858 } else /* mType == OFFLOAD */ {
5859 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5860 mFlushPending = true;
5861 }
5862 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005863 } else if (previousTrack == 0) {
5864 // there could be an old track added back during track transition for direct
5865 // output, so always issues flush to flush data of the previous track if it
5866 // was already destroyed with HAL paused, then flush can resume the playback
5867 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005868 }
5869 PlaybackThread::onAddNewTrack_l();
5870}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005871
Eric Laurent81784c32012-11-19 14:55:58 -08005872AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5873 Vector< sp<Track> > *tracksToRemove
5874)
5875{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005876 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005877 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005878 bool doHwPause = false;
5879 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005880
5881 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005882 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005883 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005884 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005885 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005886 continue;
5887 }
5888
Eric Laurent5850c4c2016-11-10 13:04:31 -08005889 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005890#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005891 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005892#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005893 // Only consider last track started for volume and mixer state control.
5894 // In theory an older track could underrun and restart after the new one starts
5895 // but as we only care about the transition phase between two tracks on a
5896 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005897 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005898 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005899
Kuowei Li23666472021-01-20 10:23:25 +08005900 if (track->isPausePending()) {
5901 track->pauseAck();
5902 // It is possible a track might have been flushed or stopped.
5903 // Other operations such as flush pending might occur on the next prepare.
5904 if (track->isPausing()) {
5905 track->setPaused();
5906 }
5907 // Always perform pause, as an immediate flush will change
5908 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005909 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005910 doHwPause = true;
5911 mHwPaused = true;
5912 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005913 } else if (track->isFlushPending()) {
5914 track->flushAck();
5915 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005916 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005917 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005918 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005919 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005920 if (last) {
5921 mLeftVolFloat = mRightVolFloat = -1.0;
5922 if (mHwPaused) {
5923 doHwResume = true;
5924 mHwPaused = false;
5925 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005926 }
5927 }
5928
Eric Laurent81784c32012-11-19 14:55:58 -08005929 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005930 // for all its buffers to be filled before processing it.
5931 // Allow draining the buffer in case the client
5932 // app does not call stop() and relies on underrun to stop:
5933 // hence the test on (track->mRetryCount > 1).
5934 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005935 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005936 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005937 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005938 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005939 minFrames = mNormalFrameCount;
5940 } else {
5941 minFrames = 1;
5942 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005943
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005944 const size_t framesReady = track->framesReady();
5945 const int trackId = track->id();
5946 if (ATRACE_ENABLED()) {
5947 std::string traceName("nRdy");
5948 traceName += std::to_string(trackId);
5949 ATRACE_INT(traceName.c_str(), framesReady);
5950 }
5951 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005952 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005953 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005954 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005955
5956 if (track->mFillingUpStatus == Track::FS_FILLED) {
5957 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005958 if (last) {
5959 // make sure processVolume_l() will apply new volume even if 0
5960 mLeftVolFloat = mRightVolFloat = -1.0;
5961 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005962 if (!mHwSupportsPause) {
5963 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005964 }
5965 }
5966
5967 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005968 processVolume_l(track, last);
5969 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005970 sp<Track> previousTrack = mPreviousTrack.promote();
5971 if (previousTrack != 0) {
5972 if (track != previousTrack.get()) {
5973 // Flush any data still being written from last track
5974 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005975 // Invalidate previous track to force a seek when resuming.
5976 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005977 }
5978 }
5979 mPreviousTrack = track;
5980
Eric Laurentd595b7c2013-04-03 17:27:56 -07005981 // reset retry count
5982 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005983 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005984 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005985 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005986 doHwResume = true;
5987 mHwPaused = false;
5988 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005989 }
Eric Laurent81784c32012-11-19 14:55:58 -08005990 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005991 // clear effect chain input buffer if the last active track started underruns
5992 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005993 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005994 mEffectChains[0]->clearInputBuffer();
5995 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005996 if (track->isStopping_1()) {
5997 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005998 if (last && mHwPaused) {
5999 doHwResume = true;
6000 mHwPaused = false;
6001 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006002 }
6003 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6004 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006005 // We have consumed all the buffers of this track.
6006 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07006007 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08006008 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006009 audioHALFrames = (latency_l() * mSampleRate) / 1000;
6010 } else {
6011 audioHALFrames = 0;
6012 }
6013
Andy Hung818e7a32016-02-16 18:08:07 -08006014 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07006015 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08006016 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08006017 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006018 if (track->isStopping_2()) {
6019 track->mState = TrackBase::STOPPED;
6020 }
Eric Laurent81784c32012-11-19 14:55:58 -08006021 if (track->isStopped()) {
6022 track->reset();
6023 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006024 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006025 }
6026 } else {
6027 // No buffers for this track. Give it a few chances to
6028 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006029 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006030 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006031 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006032 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006033 // indicate to client process that the track was disabled because of underrun;
6034 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006035 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006036 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6037 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006038 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6039 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006040 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006041 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006042 doHwPause = true;
6043 mHwPaused = true;
6044 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006045 } else if (last) {
6046 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006047 }
6048 }
6049 }
6050 }
6051
Eric Laurentd1f69b02014-12-15 14:33:13 -08006052 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006053 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006054 for (size_t i = 0; i < mTracks.size(); i++) {
6055 if (mTracks[i]->isFlushPending()) {
6056 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006057 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006058 }
6059 }
6060 }
6061
6062 // make sure the pause/flush/resume sequence is executed in the right order.
6063 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6064 // before flush and then resume HW. This can happen in case of pause/flush/resume
6065 // if resume is received before pause is executed.
6066 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006067 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006068 status_t result = mOutput->stream->pause();
6069 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006070 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006071 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006072 flushHw_l();
6073 }
6074 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006075 status_t result = mOutput->stream->resume();
6076 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006077 }
Eric Laurent81784c32012-11-19 14:55:58 -08006078 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006079 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006080
6081 return mixerStatus;
6082}
6083
6084void AudioFlinger::DirectOutputThread::threadLoop_mix()
6085{
Eric Laurent81784c32012-11-19 14:55:58 -08006086 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006087 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006088 // output audio to hardware
6089 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006090 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006091 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006092 status_t status = mActiveTrack->getNextBuffer(&buffer);
6093 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006094 // no need to pad with 0 for compressed audio
6095 if (audio_has_proportional_frames(mFormat)) {
6096 memset(curBuf, 0, frameCount * mFrameSize);
6097 }
Eric Laurent81784c32012-11-19 14:55:58 -08006098 break;
6099 }
6100 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6101 frameCount -= buffer.frameCount;
6102 curBuf += buffer.frameCount * mFrameSize;
6103 mActiveTrack->releaseBuffer(&buffer);
6104 }
Andy Hung2098f272014-02-27 14:00:06 -08006105 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006106 mSleepTimeUs = 0;
6107 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006108 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006109}
6110
6111void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6112{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006113 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006114 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006115 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006116 return;
6117 }
Andy Hung85ba3332021-04-27 17:40:26 -07006118 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6119 mSleepTimeUs = mActiveSleepTimeUs;
6120 } else {
6121 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006122 }
Andy Hung85ba3332021-04-27 17:40:26 -07006123 // Note: In S or later, we do not write zeroes for
6124 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006125}
6126
Eric Laurentd1f69b02014-12-15 14:33:13 -08006127void AudioFlinger::DirectOutputThread::threadLoop_exit()
6128{
6129 {
6130 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006131 for (size_t i = 0; i < mTracks.size(); i++) {
6132 if (mTracks[i]->isFlushPending()) {
6133 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006134 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006135 }
6136 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006137 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006138 flushHw_l();
6139 }
6140 }
6141 PlaybackThread::threadLoop_exit();
6142}
6143
6144// must be called with thread mutex locked
6145bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6146{
6147 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006148 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006149
6150 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6151 // after a timeout and we will enter standby then.
6152 if (mTracks.size() > 0) {
6153 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006154 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6155 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006156 }
6157
Eric Laurent5cff4032015-05-26 13:49:58 -07006158 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006159}
6160
Eric Laurent10351942014-05-08 18:49:52 -07006161// checkForNewParameter_l() must be called with ThreadBase::mLock held
6162bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6163 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006164{
6165 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006166 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006167
Eric Laurent10351942014-05-08 18:49:52 -07006168 AudioParameter param = AudioParameter(keyValuePair);
6169 int value;
6170 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006171 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006172 }
Eric Laurent10351942014-05-08 18:49:52 -07006173 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6174 // do not accept frame count changes if tracks are open as the track buffer
6175 // size depends on frame count and correct behavior would not be garantied
6176 // if frame count is changed after track creation
6177 if (!mTracks.isEmpty()) {
6178 status = INVALID_OPERATION;
6179 } else {
6180 reconfig = true;
6181 }
6182 }
6183 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006184 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006185 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006186 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006187 if (!mStandby) {
6188 mThreadMetrics.logEndInterval();
6189 mStandby = true;
6190 }
Eric Laurent10351942014-05-08 18:49:52 -07006191 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006192 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006193 }
6194 if (status == NO_ERROR && reconfig) {
6195 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006196 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006197 }
6198 }
6199
Dean Wheatley68918102021-03-19 22:09:19 +11006200 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006201}
6202
6203uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6204{
6205 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006206 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006207 time = PlaybackThread::activeSleepTimeUs();
6208 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006209 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006210 }
6211 return time;
6212}
6213
6214uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6215{
6216 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006217 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006218 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6219 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006220 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006221 }
6222 return time;
6223}
6224
6225uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6226{
6227 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006228 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006229 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6230 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006231 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006232 }
6233 return time;
6234}
6235
6236void AudioFlinger::DirectOutputThread::cacheParameters_l()
6237{
6238 PlaybackThread::cacheParameters_l();
6239
6240 // use shorter standby delay as on normal output to release
6241 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006242 // no delay on outputs with HW A/V sync
6243 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006244 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006245 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006246 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006247 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006248 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006249 }
Eric Laurent81784c32012-11-19 14:55:58 -08006250}
6251
Eric Laurente659ef42014-09-29 13:06:46 -07006252void AudioFlinger::DirectOutputThread::flushHw_l()
6253{
Phil Burk062e67a2015-02-11 13:40:50 -08006254 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006255 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006256 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006257 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006258 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006259}
6260
Andy Hung10cbff12017-02-21 17:30:14 -08006261int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6262 // If a VolumeShaper is active, we must wake up periodically to update volume.
6263 const int64_t NS_PER_MS = 1000000;
6264 return mVolumeShaperActive ?
6265 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6266}
6267
Eric Laurent81784c32012-11-19 14:55:58 -08006268// ----------------------------------------------------------------------------
6269
Eric Laurentbfb1b832013-01-07 09:53:42 -08006270AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006271 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006272 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006273 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006274 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006275 mDrainSequence(0),
6276 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006277{
6278}
6279
6280AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6281{
6282}
6283
6284void AudioFlinger::AsyncCallbackThread::onFirstRef()
6285{
6286 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6287}
6288
6289bool AudioFlinger::AsyncCallbackThread::threadLoop()
6290{
6291 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006292 uint32_t writeAckSequence;
6293 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006294 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006295
6296 {
6297 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006298 while (!((mWriteAckSequence & 1) ||
6299 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006300 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006301 exitPending())) {
6302 mWaitWorkCV.wait(mLock);
6303 }
6304
Eric Laurentbfb1b832013-01-07 09:53:42 -08006305 if (exitPending()) {
6306 break;
6307 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006308 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6309 mWriteAckSequence, mDrainSequence);
6310 writeAckSequence = mWriteAckSequence;
6311 mWriteAckSequence &= ~1;
6312 drainSequence = mDrainSequence;
6313 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006314 asyncError = mAsyncError;
6315 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006316 }
6317 {
Eric Laurent4de95592013-09-26 15:28:21 -07006318 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6319 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006320 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006321 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006322 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006323 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006324 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006325 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006326 if (asyncError) {
6327 playbackThread->onAsyncError();
6328 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006329 }
6330 }
6331 }
6332 return false;
6333}
6334
6335void AudioFlinger::AsyncCallbackThread::exit()
6336{
6337 ALOGV("AsyncCallbackThread::exit");
6338 Mutex::Autolock _l(mLock);
6339 requestExit();
6340 mWaitWorkCV.broadcast();
6341}
6342
Eric Laurent3b4529e2013-09-05 18:09:19 -07006343void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006344{
6345 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006346 // bit 0 is cleared
6347 mWriteAckSequence = sequence << 1;
6348}
6349
6350void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6351{
6352 Mutex::Autolock _l(mLock);
6353 // ignore unexpected callbacks
6354 if (mWriteAckSequence & 2) {
6355 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006356 mWaitWorkCV.signal();
6357 }
6358}
6359
Eric Laurent3b4529e2013-09-05 18:09:19 -07006360void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006361{
6362 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006363 // bit 0 is cleared
6364 mDrainSequence = sequence << 1;
6365}
6366
6367void AudioFlinger::AsyncCallbackThread::resetDraining()
6368{
6369 Mutex::Autolock _l(mLock);
6370 // ignore unexpected callbacks
6371 if (mDrainSequence & 2) {
6372 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006373 mWaitWorkCV.signal();
6374 }
6375}
6376
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006377void AudioFlinger::AsyncCallbackThread::setAsyncError()
6378{
6379 Mutex::Autolock _l(mLock);
6380 mAsyncError = true;
6381 mWaitWorkCV.signal();
6382}
6383
Eric Laurentbfb1b832013-01-07 09:53:42 -08006384
6385// ----------------------------------------------------------------------------
6386AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006387 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6388 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006389 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6390 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006391{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006392 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006393 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006394 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006395}
6396
Eric Laurentbfb1b832013-01-07 09:53:42 -08006397void AudioFlinger::OffloadThread::threadLoop_exit()
6398{
6399 if (mFlushPending || mHwPaused) {
6400 // If a flush is pending or track was paused, just discard buffered data
6401 flushHw_l();
6402 } else {
6403 mMixerStatus = MIXER_DRAIN_ALL;
6404 threadLoop_drain();
6405 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006406 if (mUseAsyncWrite) {
6407 ALOG_ASSERT(mCallbackThread != 0);
6408 mCallbackThread->exit();
6409 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006410 PlaybackThread::threadLoop_exit();
6411}
6412
6413AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6414 Vector< sp<Track> > *tracksToRemove
6415)
6416{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006417 size_t count = mActiveTracks.size();
6418
6419 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006420 bool doHwPause = false;
6421 bool doHwResume = false;
6422
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006423 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006424
Eric Laurentbfb1b832013-01-07 09:53:42 -08006425 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006426 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006427 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006428#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006429 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006430#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006431 // Only consider last track started for volume and mixer state control.
6432 // In theory an older track could underrun and restart after the new one starts
6433 // but as we only care about the transition phase between two tracks on a
6434 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006435 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006436 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006437
Haynes Mathew George7844f672014-01-15 12:32:55 -08006438 if (track->isInvalid()) {
6439 ALOGW("An invalidated track shouldn't be in active list");
6440 tracksToRemove->add(track);
6441 continue;
6442 }
6443
6444 if (track->mState == TrackBase::IDLE) {
6445 ALOGW("An idle track shouldn't be in active list");
6446 continue;
6447 }
6448
Kuowei Li23666472021-01-20 10:23:25 +08006449 if (track->isPausePending()) {
6450 track->pauseAck();
6451 // It is possible a track might have been flushed or stopped.
6452 // Other operations such as flush pending might occur on the next prepare.
6453 if (track->isPausing()) {
6454 track->setPaused();
6455 }
6456 // Always perform pause if last, as an immediate flush will change
6457 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006458 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006459 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006460 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006461 mHwPaused = true;
6462 }
6463 // If we were part way through writing the mixbuffer to
6464 // the HAL we must save this until we resume
6465 // BUG - this will be wrong if a different track is made active,
6466 // in that case we want to discard the pending data in the
6467 // mixbuffer and tell the client to present it again when the
6468 // track is resumed
6469 mPausedWriteLength = mCurrentWriteLength;
6470 mPausedBytesRemaining = mBytesRemaining;
6471 mBytesRemaining = 0; // stop writing
6472 }
6473 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006474 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006475 if (track->isStopping_1()) {
6476 track->mRetryCount = kMaxTrackStopRetriesOffload;
6477 } else {
6478 track->mRetryCount = kMaxTrackRetriesOffload;
6479 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006480 track->flushAck();
6481 if (last) {
6482 mFlushPending = true;
6483 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006484 } else if (track->isResumePending()){
6485 track->resumeAck();
6486 if (last) {
6487 if (mPausedBytesRemaining) {
6488 // Need to continue write that was interrupted
6489 mCurrentWriteLength = mPausedWriteLength;
6490 mBytesRemaining = mPausedBytesRemaining;
6491 mPausedBytesRemaining = 0;
6492 }
6493 if (mHwPaused) {
6494 doHwResume = true;
6495 mHwPaused = false;
6496 // threadLoop_mix() will handle the case that we need to
6497 // resume an interrupted write
6498 }
6499 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006500 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006501
Eric Laurent3df841a2016-07-15 15:15:40 -07006502 mLeftVolFloat = mRightVolFloat = -1.0;
6503
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006504 // Do not handle new data in this iteration even if track->framesReady()
6505 mixerStatus = MIXER_TRACKS_ENABLED;
6506 }
6507 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006508 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006509 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006510 if (track->mFillingUpStatus == Track::FS_FILLED) {
6511 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006512 if (last) {
6513 // make sure processVolume_l() will apply new volume even if 0
6514 mLeftVolFloat = mRightVolFloat = -1.0;
6515 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006516 }
6517
6518 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006519 sp<Track> previousTrack = mPreviousTrack.promote();
6520 if (previousTrack != 0) {
6521 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006522 // Flush any data still being written from last track
6523 mBytesRemaining = 0;
6524 if (mPausedBytesRemaining) {
6525 // Last track was paused so we also need to flush saved
6526 // mixbuffer state and invalidate track so that it will
6527 // re-submit that unwritten data when it is next resumed
6528 mPausedBytesRemaining = 0;
6529 // Invalidate is a bit drastic - would be more efficient
6530 // to have a flag to tell client that some of the
6531 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006532 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006533 }
6534 // flush data already sent to the DSP if changing audio session as audio
6535 // comes from a different source. Also invalidate previous track to force a
6536 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006537 if (previousTrack->sessionId() != track->sessionId()) {
6538 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006539 }
6540 }
6541 }
6542 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006543 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006544 if (track->isStopping_1()) {
6545 track->mRetryCount = kMaxTrackStopRetriesOffload;
6546 } else {
6547 track->mRetryCount = kMaxTrackRetriesOffload;
6548 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006549 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006550 mixerStatus = MIXER_TRACKS_READY;
6551 }
6552 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006553 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006554 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006555 if (--(track->mRetryCount) <= 0) {
6556 // Hardware buffer can hold a large amount of audio so we must
6557 // wait for all current track's data to drain before we say
6558 // that the track is stopped.
6559 if (mBytesRemaining == 0) {
6560 // Only start draining when all data in mixbuffer
6561 // has been written
6562 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6563 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6564 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6565 if (last && !mStandby) {
6566 // do not modify drain sequence if we are already draining. This happens
6567 // when resuming from pause after drain.
6568 if ((mDrainSequence & 1) == 0) {
6569 mSleepTimeUs = 0;
6570 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6571 mixerStatus = MIXER_DRAIN_TRACK;
6572 mDrainSequence += 2;
6573 }
6574 if (mHwPaused) {
6575 // It is possible to move from PAUSED to STOPPING_1 without
6576 // a resume so we must ensure hardware is running
6577 doHwResume = true;
6578 mHwPaused = false;
6579 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006580 }
6581 }
Eric Laurente93cc032016-05-05 10:15:10 -07006582 } else if (last) {
6583 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6584 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006585 }
6586 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006587 // Drain has completed or we are in standby, signal presentation complete
6588 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006589 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006590 uint32_t latency = 0;
6591 status_t result = mOutput->stream->getLatency(&latency);
6592 ALOGE_IF(result != OK,
6593 "Error when retrieving output stream latency: %d", result);
6594 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006595 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006596 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006597 track->presentationComplete(framesWritten, audioHALFrames);
6598 track->reset();
6599 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006600 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006601 if (!mUseAsyncWrite) {
6602 // If we don't get explicit drain notification we must
6603 // register discontinuity regardless of whether this is
6604 // the previous (!last) or the upcoming (last) track
6605 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006606 mTimestampVerifier.discontinuity(
6607 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006608 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006609 }
6610 } else {
6611 // No buffers for this track. Give it a few chances to
6612 // fill a buffer, then remove it from active list.
6613 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006614 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006615 uint64_t position = 0;
6616 struct timespec unused;
6617 // The running check restarts the retry counter at least once.
6618 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6619 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6620 running = true;
6621 mOffloadUnderrunPosition = position;
6622 }
6623 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006624 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6625 (long long)position, (long long)mOffloadUnderrunPosition);
6626 }
6627 if (running) { // still running, give us more time.
6628 track->mRetryCount = kMaxTrackRetriesOffload;
6629 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006630 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6631 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006632 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006633 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006634 // it will then automatically call start() when data is available
6635 track->disable();
6636 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006637 } else if (last){
6638 mixerStatus = MIXER_TRACKS_ENABLED;
6639 }
6640 }
6641 }
6642 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006643 if (track->isReady()) { // check ready to prevent premature start.
6644 processVolume_l(track, last);
6645 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006646 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006647
Eric Laurentea0fade2013-10-04 16:23:48 -07006648 // make sure the pause/flush/resume sequence is executed in the right order.
6649 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6650 // before flush and then resume HW. This can happen in case of pause/flush/resume
6651 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006652 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006653 status_t result = mOutput->stream->pause();
6654 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006655 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006656 if (mFlushPending) {
6657 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006658 }
Eric Laurentfd477972013-10-25 18:10:40 -07006659 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006660 status_t result = mOutput->stream->resume();
6661 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006662 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006663
Eric Laurentbfb1b832013-01-07 09:53:42 -08006664 // remove all the tracks that need to be...
6665 removeTracks_l(*tracksToRemove);
6666
6667 return mixerStatus;
6668}
6669
Eric Laurentbfb1b832013-01-07 09:53:42 -08006670// must be called with thread mutex locked
6671bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6672{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006673 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6674 mWriteAckSequence, mDrainSequence);
6675 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006676 return true;
6677 }
6678 return false;
6679}
6680
Eric Laurentbfb1b832013-01-07 09:53:42 -08006681bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6682{
6683 Mutex::Autolock _l(mLock);
6684 return waitingAsyncCallback_l();
6685}
6686
6687void AudioFlinger::OffloadThread::flushHw_l()
6688{
Eric Laurente659ef42014-09-29 13:06:46 -07006689 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006690 // Flush anything still waiting in the mixbuffer
6691 mCurrentWriteLength = 0;
6692 mBytesRemaining = 0;
6693 mPausedWriteLength = 0;
6694 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006695 // reset bytes written count to reflect that DSP buffers are empty after flush.
6696 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006697 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006698
Eric Laurentbfb1b832013-01-07 09:53:42 -08006699 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006700 // discard any pending drain or write ack by incrementing sequence
6701 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6702 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006703 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006704 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6705 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006706 }
6707}
6708
Haynes Mathew George05317d22016-05-03 16:34:26 -07006709void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6710{
6711 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006712 if (PlaybackThread::invalidateTracks_l(streamType)) {
6713 mFlushPending = true;
6714 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006715}
6716
Eric Laurentbfb1b832013-01-07 09:53:42 -08006717// ----------------------------------------------------------------------------
6718
Eric Laurent81784c32012-11-19 14:55:58 -08006719AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006720 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006721 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006722 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006723 mWaitTimeMs(UINT_MAX)
6724{
6725 addOutputTrack(mainThread);
6726}
6727
6728AudioFlinger::DuplicatingThread::~DuplicatingThread()
6729{
6730 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6731 mOutputTracks[i]->destroy();
6732 }
6733}
6734
6735void AudioFlinger::DuplicatingThread::threadLoop_mix()
6736{
6737 // mix buffers...
6738 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006739 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006740 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006741 if (mMixerBufferValid) {
6742 memset(mMixerBuffer, 0, mMixerBufferSize);
6743 } else {
6744 memset(mSinkBuffer, 0, mSinkBufferSize);
6745 }
Eric Laurent81784c32012-11-19 14:55:58 -08006746 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006747 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006748 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006749 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006750 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006751}
6752
6753void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6754{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006755 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006756 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006757 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006758 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006759 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006760 }
6761 } else if (mBytesWritten != 0) {
6762 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6763 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006764 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006765 } else {
6766 // flush remaining overflow buffers in output tracks
6767 writeFrames = 0;
6768 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006769 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006770 }
6771}
6772
Eric Laurentbfb1b832013-01-07 09:53:42 -08006773ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006774{
6775 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006776 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6777
6778 // Consider the first OutputTrack for timestamp and frame counting.
6779
6780 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6781 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6782 // we always claim success.
6783 if (i == 0) {
6784 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6785 ALOGD_IF(correction != 0 && writeFrames != 0,
6786 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6787 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6788 mFramesWritten -= correction;
6789 }
6790
6791 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006792 }
Andy Hungcf10d742020-04-28 15:38:24 -07006793 if (mStandby) {
6794 mThreadMetrics.logBeginInterval();
6795 mStandby = false;
6796 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006797 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006798}
6799
6800void AudioFlinger::DuplicatingThread::threadLoop_standby()
6801{
6802 // DuplicatingThread implements standby by stopping all tracks
6803 for (size_t i = 0; i < outputTracks.size(); i++) {
6804 outputTracks[i]->stop();
6805 }
6806}
6807
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006808void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006809{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006810 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006811
6812 std::stringstream ss;
6813 const size_t numTracks = mOutputTracks.size();
6814 ss << " " << numTracks << " OutputTracks";
6815 if (numTracks > 0) {
6816 ss << ":";
6817 for (const auto &track : mOutputTracks) {
6818 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006819 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006820 if (thread.get() != nullptr) {
6821 ss << thread.get() << ", " << thread->id();
6822 } else {
6823 ss << "null";
6824 }
6825 ss << ")";
6826 }
6827 }
6828 ss << "\n";
6829 std::string result = ss.str();
6830 write(fd, result.c_str(), result.size());
6831}
6832
Eric Laurent81784c32012-11-19 14:55:58 -08006833void AudioFlinger::DuplicatingThread::saveOutputTracks()
6834{
6835 outputTracks = mOutputTracks;
6836}
6837
6838void AudioFlinger::DuplicatingThread::clearOutputTracks()
6839{
6840 outputTracks.clear();
6841}
6842
6843void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6844{
6845 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006846 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6847 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6848 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6849 const size_t frameCount =
6850 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6851 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6852 // from different OutputTracks and their associated MixerThreads (e.g. one may
6853 // nearly empty and the other may be dropping data).
6854
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006855 // TODO b/182392769: use identity util, move to server edge
6856 Identity identity = Identity();
6857 identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
6858 IPCThreadState::self()->getCallingUid()));
6859 identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
6860 IPCThreadState::self()->getCallingPid()));
Andy Hungc25b84a2015-01-14 19:04:10 -08006861 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006862 this,
6863 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006864 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006865 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006866 frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006867 identity);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006868 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6869 if (status != NO_ERROR) {
6870 ALOGE("addOutputTrack() initCheck failed %d", status);
6871 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006872 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006873 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6874 mOutputTracks.add(outputTrack);
6875 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6876 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006877}
6878
6879void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6880{
6881 Mutex::Autolock _l(mLock);
6882 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6883 if (mOutputTracks[i]->thread() == thread) {
6884 mOutputTracks[i]->destroy();
6885 mOutputTracks.removeAt(i);
6886 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006887 if (thread->getOutput() == mOutput) {
6888 mOutput = NULL;
6889 }
Eric Laurent81784c32012-11-19 14:55:58 -08006890 return;
6891 }
6892 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006893 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006894}
6895
6896// caller must hold mLock
6897void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6898{
6899 mWaitTimeMs = UINT_MAX;
6900 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6901 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6902 if (strong != 0) {
6903 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6904 if (waitTimeMs < mWaitTimeMs) {
6905 mWaitTimeMs = waitTimeMs;
6906 }
6907 }
6908 }
6909}
6910
6911
6912bool AudioFlinger::DuplicatingThread::outputsReady(
6913 const SortedVector< sp<OutputTrack> > &outputTracks)
6914{
6915 for (size_t i = 0; i < outputTracks.size(); i++) {
6916 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6917 if (thread == 0) {
6918 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6919 outputTracks[i].get());
6920 return false;
6921 }
6922 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6923 // see note at standby() declaration
6924 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6925 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6926 thread.get());
6927 return false;
6928 }
6929 }
6930 return true;
6931}
6932
Kevin Rocard12381092018-04-11 09:19:59 -07006933void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6934 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006935{
Kevin Rocard12381092018-04-11 09:19:59 -07006936 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6937 outputTrack->setMetadatas(metadata.tracks);
6938 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006939}
6940
Eric Laurent81784c32012-11-19 14:55:58 -08006941uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6942{
6943 return (mWaitTimeMs * 1000) / 2;
6944}
6945
6946void AudioFlinger::DuplicatingThread::cacheParameters_l()
6947{
6948 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6949 updateWaitTime_l();
6950
6951 MixerThread::cacheParameters_l();
6952}
6953
Eric Laurent6acd1d42017-01-04 14:23:29 -08006954
Eric Laurent81784c32012-11-19 14:55:58 -08006955// ----------------------------------------------------------------------------
6956// Record
6957// ----------------------------------------------------------------------------
6958
6959AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6960 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006961 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006962 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006963 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006964 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006965 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006966 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006967 mActiveTracks(&this->mLocalLog),
6968 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006969 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006970 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006971 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6972 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006973 // mFastCapture below
6974 , mFastCaptureFutex(0)
6975 // mInputSource
6976 // mPipeSink
6977 // mPipeSource
6978 , mPipeFramesP2(0)
6979 // mPipeMemory
6980 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006981 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006982 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006983{
Glenn Kastend7dca052015-03-05 16:05:54 -08006984 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6985 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006986
George Burgess IVa8f90c12020-05-14 11:27:19 -07006987 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07006988 mIsMsdDevice = strcmp(
6989 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6990 }
6991
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006992 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006993
Andy Hungc8fddf32018-08-08 18:32:37 -07006994 // TODO: We may also match on address as well as device type for
6995 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07006996 // TODO: This property should be ensure that only contains one single device type.
6997 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6998 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006999 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7000 : AUDIO_DEVICE_NONE));
7001
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007002 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007003 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007004 size_t numCounterOffers = 0;
7005 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007006#if !LOG_NDEBUG
7007 ssize_t index =
7008#else
7009 (void)
7010#endif
7011 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007012 ALOG_ASSERT(index == 0);
7013
7014 // initialize fast capture depending on configuration
7015 bool initFastCapture;
7016 switch (kUseFastCapture) {
7017 case FastCapture_Never:
7018 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007019 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007020 break;
7021 case FastCapture_Always:
7022 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007023 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007024 break;
7025 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007026 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007027 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7028 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7029 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007030 break;
7031 // case FastCapture_Dynamic:
7032 }
7033
7034 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007035 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007036 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007037 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7038 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007039 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007040 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007041 const sp<MemoryDealer> roHeap(readOnlyHeap());
7042 sp<IMemory> pipeMemory;
7043 if ((roHeap == 0) ||
7044 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007045 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007046 ALOGE("not enough memory for pipe buffer size=%zu; "
7047 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7048 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7049 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007050 goto failed;
7051 }
7052 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7053 memset(pipeBuffer, 0, pipeSize);
7054 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7055 const NBAIO_Format offers[1] = {format};
7056 size_t numCounterOffers = 0;
7057 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7058 ALOG_ASSERT(index == 0);
7059 mPipeSink = pipe;
7060 PipeReader *pipeReader = new PipeReader(*pipe);
7061 numCounterOffers = 0;
7062 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7063 ALOG_ASSERT(index == 0);
7064 mPipeSource = pipeReader;
7065 mPipeFramesP2 = pipeFramesP2;
7066 mPipeMemory = pipeMemory;
7067
7068 // create fast capture
7069 mFastCapture = new FastCapture();
7070 FastCaptureStateQueue *sq = mFastCapture->sq();
7071#ifdef STATE_QUEUE_DUMP
7072 // FIXME
7073#endif
7074 FastCaptureState *state = sq->begin();
7075 state->mCblk = NULL;
7076 state->mInputSource = mInputSource.get();
7077 state->mInputSourceGen++;
7078 state->mPipeSink = pipe;
7079 state->mPipeSinkGen++;
7080 state->mFrameCount = mFrameCount;
7081 state->mCommand = FastCaptureState::COLD_IDLE;
7082 // already done in constructor initialization list
7083 //mFastCaptureFutex = 0;
7084 state->mColdFutexAddr = &mFastCaptureFutex;
7085 state->mColdGen++;
7086 state->mDumpState = &mFastCaptureDumpState;
7087#ifdef TEE_SINK
7088 // FIXME
7089#endif
7090 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7091 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7092 sq->end();
7093 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7094
7095 // start the fast capture
7096 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7097 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007098 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007099 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007100#ifdef AUDIO_WATCHDOG
7101 // FIXME
7102#endif
7103
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007104 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007105 }
Andy Hung8946a282018-04-19 20:04:56 -07007106#ifdef TEE_SINK
7107 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7108 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7109#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007110failed: ;
7111
7112 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007113}
7114
Eric Laurent81784c32012-11-19 14:55:58 -08007115AudioFlinger::RecordThread::~RecordThread()
7116{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007117 if (mFastCapture != 0) {
7118 FastCaptureStateQueue *sq = mFastCapture->sq();
7119 FastCaptureState *state = sq->begin();
7120 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7121 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7122 if (old == -1) {
7123 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7124 }
7125 }
7126 state->mCommand = FastCaptureState::EXIT;
7127 sq->end();
7128 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7129 mFastCapture->join();
7130 mFastCapture.clear();
7131 }
7132 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007133 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007134 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007135}
7136
7137void AudioFlinger::RecordThread::onFirstRef()
7138{
Glenn Kastend7dca052015-03-05 16:05:54 -08007139 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007140}
7141
Eric Laurent555530a2017-02-07 18:17:24 -08007142void AudioFlinger::RecordThread::preExit()
7143{
7144 ALOGV(" preExit()");
7145 Mutex::Autolock _l(mLock);
7146 for (size_t i = 0; i < mTracks.size(); i++) {
7147 sp<RecordTrack> track = mTracks[i];
7148 track->invalidate();
7149 }
7150 mActiveTracks.clear();
7151 mStartStopCond.broadcast();
7152}
7153
Eric Laurent81784c32012-11-19 14:55:58 -08007154bool AudioFlinger::RecordThread::threadLoop()
7155{
Eric Laurent81784c32012-11-19 14:55:58 -08007156 nsecs_t lastWarning = 0;
7157
7158 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007159
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007160reacquire_wakelock:
7161 sp<RecordTrack> activeTrack;
7162 {
7163 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007164 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007165 }
7166
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007167 // used to request a deferred sleep, to be executed later while mutex is unlocked
7168 uint32_t sleepUs = 0;
7169
Andy Hung446f4df2019-02-21 12:26:41 -08007170 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7171
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007172 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007173 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007174 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007175
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007176 // activeTracks accumulates a copy of a subset of mActiveTracks
7177 Vector< sp<RecordTrack> > activeTracks;
7178
Glenn Kasten735f45f2014-08-18 15:51:59 -07007179 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007180 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007181
Glenn Kasten735f45f2014-08-18 15:51:59 -07007182 // reference to a fast track which is about to be removed
7183 sp<RecordTrack> fastTrackToRemove;
7184
Eric Laurent33403f02020-05-29 18:35:06 -07007185 bool silenceFastCapture = false;
7186
Eric Laurent81784c32012-11-19 14:55:58 -08007187 { // scope for mLock
7188 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007189
Eric Laurent021cf962014-05-13 10:18:14 -07007190 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007191
Eric Laurent000a4192014-01-29 15:17:32 -08007192 // check exitPending here because checkForNewParameters_l() and
7193 // checkForNewParameters_l() can temporarily release mLock
7194 if (exitPending()) {
7195 break;
7196 }
7197
Eric Laurent5c25d562016-07-13 17:17:45 -07007198 // sleep with mutex unlocked
7199 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007200 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007201 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7202 ATRACE_END();
7203 sleepUs = 0;
7204 continue;
7205 }
7206
Glenn Kasten2b806402013-11-20 16:37:38 -08007207 // if no active track(s), then standby and release wakelock
7208 size_t size = mActiveTracks.size();
7209 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007210 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007211 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007212 releaseWakeLock_l();
7213 ALOGV("RecordThread: loop stopping");
7214 // go to sleep
7215 mWaitWorkCV.wait(mLock);
7216 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007217 goto reacquire_wakelock;
7218 }
7219
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007220 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007221 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007222 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007223
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007224 activeTrack = mActiveTracks[i];
7225 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007226 if (activeTrack->isFastTrack()) {
7227 ALOG_ASSERT(fastTrackToRemove == 0);
7228 fastTrackToRemove = activeTrack;
7229 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007230 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007231 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007232 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007233 continue;
7234 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007235
7236 TrackBase::track_state activeTrackState = activeTrack->mState;
7237 switch (activeTrackState) {
7238
7239 case TrackBase::PAUSING:
7240 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007241 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007242 doBroadcast = true;
7243 size--;
7244 continue;
7245
7246 case TrackBase::STARTING_1:
7247 sleepUs = 10000;
7248 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007249 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007250 continue;
7251
7252 case TrackBase::STARTING_2:
7253 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007254 if (mStandby) {
7255 mThreadMetrics.logBeginInterval();
7256 mStandby = false;
7257 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007258 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007259 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007260 break;
7261
7262 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007263 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007264 break;
7265
Andy Hungce685402018-10-05 17:23:27 -07007266 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7267 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7268 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007269 default:
Andy Hungce685402018-10-05 17:23:27 -07007270 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7271 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007272 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007273
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007274 if (activeTrack->isFastTrack()) {
7275 ALOG_ASSERT(!mFastTrackAvail);
7276 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007277 // if the active fast track is silenced either:
7278 // 1) silence the whole capture from fast capture buffer if this is
7279 // the only active track
7280 // 2) invalidate this track: this will cause the client to reconnect and possibly
7281 // be invalidated again until unsilenced
7282 if (activeTrack->isSilenced()) {
7283 if (size > 1) {
7284 activeTrack->invalidate();
7285 ALOG_ASSERT(fastTrackToRemove == 0);
7286 fastTrackToRemove = activeTrack;
7287 removeTrack_l(activeTrack);
7288 mActiveTracks.remove(activeTrack);
7289 size--;
7290 continue;
7291 } else {
7292 silenceFastCapture = true;
7293 }
7294 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007295 fastTrack = activeTrack;
7296 }
Eric Laurent33403f02020-05-29 18:35:06 -07007297
7298 activeTracks.add(activeTrack);
7299 i++;
7300
Glenn Kasten9e982352013-08-14 14:39:50 -07007301 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007302
Andy Hungdae27702016-10-31 14:01:16 -07007303 mActiveTracks.updatePowerState(this);
7304
Kevin Rocard069c2712018-03-29 19:09:14 -07007305 updateMetadata_l();
7306
Eric Laurent5c25d562016-07-13 17:17:45 -07007307 if (allStopped) {
7308 standbyIfNotAlreadyInStandby();
7309 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007310 if (doBroadcast) {
7311 mStartStopCond.broadcast();
7312 }
7313
7314 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007315 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007316 if (sleepUs == 0) {
7317 sleepUs = kRecordThreadSleepUs;
7318 }
7319 continue;
7320 }
7321 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007322
Eric Laurent81784c32012-11-19 14:55:58 -08007323 lockEffectChains_l(effectChains);
7324 }
7325
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007326 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007327
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007328 size_t size = effectChains.size();
7329 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007330 // thread mutex is not locked, but effect chain is locked
7331 effectChains[i]->process_l();
7332 }
7333
Glenn Kasten735f45f2014-08-18 15:51:59 -07007334 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007335 if (mFastCapture != 0) {
7336 FastCaptureStateQueue *sq = mFastCapture->sq();
7337 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007338 bool didModify = false;
7339 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007340 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7341 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7342 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7343 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7344 if (old == -1) {
7345 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7346 }
7347 }
7348 state->mCommand = FastCaptureState::READ_WRITE;
7349#if 0 // FIXME
7350 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007351 FastThreadDumpState::kSamplingNforLowRamDevice :
7352 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007353#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007354 didModify = true;
7355 }
7356 audio_track_cblk_t *cblkOld = state->mCblk;
7357 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7358 if (cblkNew != cblkOld) {
7359 state->mCblk = cblkNew;
7360 // block until acked if removing a fast track
7361 if (cblkOld != NULL) {
7362 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7363 }
7364 didModify = true;
7365 }
jiabin01c8f562018-07-19 17:47:28 -07007366 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7367 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7368 if (state->mFastPatchRecordBufferProvider != abp) {
7369 state->mFastPatchRecordBufferProvider = abp;
7370 state->mFastPatchRecordFormat = fastTrack == 0 ?
7371 AUDIO_FORMAT_INVALID : fastTrack->format();
7372 didModify = true;
7373 }
Eric Laurent33403f02020-05-29 18:35:06 -07007374 if (state->mSilenceCapture != silenceFastCapture) {
7375 state->mSilenceCapture = silenceFastCapture;
7376 didModify = true;
7377 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007378 sq->end(didModify);
7379 if (didModify) {
7380 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007381#if 0
7382 if (kUseFastCapture == FastCapture_Dynamic) {
7383 mNormalSource = mPipeSource;
7384 }
7385#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007386 }
7387 }
7388
Glenn Kasten735f45f2014-08-18 15:51:59 -07007389 // now run the fast track destructor with thread mutex unlocked
7390 fastTrackToRemove.clear();
7391
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007392 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7393 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7394 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7395 // If destination is non-contiguous, first read past the nominal end of buffer, then
7396 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007397
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007398 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007399 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007400 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007401
7402 // If an NBAIO source is present, use it to read the normal capture's data
7403 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007404 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007405
7406 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7407 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7408 // we immediately retry the read() to get data and prevent another overflow.
7409 for (int retries = 0; retries <= 2; ++retries) {
7410 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7411 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7412 framesToRead);
7413 if (framesRead != OVERRUN) break;
7414 }
7415
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007416 const ssize_t availableToRead = mPipeSource->availableToRead();
7417 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007418 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007419 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7420 "more frames to read than fifo size, %zd > %zu",
7421 availableToRead, mPipeFramesP2);
7422 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7423 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7424 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7425 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007426 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7427 }
7428 if (framesRead < 0) {
7429 status_t status = (status_t) framesRead;
7430 switch (status) {
7431 case OVERRUN:
7432 ALOGW("overrun on read from pipe");
7433 framesRead = 0;
7434 break;
7435 case NEGOTIATE:
7436 ALOGE("re-negotiation is needed");
7437 framesRead = -1; // Will cause an attempt to recover.
7438 break;
7439 default:
7440 ALOGE("unknown error %d on read from pipe", status);
7441 break;
7442 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007443 }
7444 // otherwise use the HAL / AudioStreamIn directly
7445 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007446 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007447 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007448 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007449 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007450 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007451 if (result < 0) {
7452 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007453 } else {
7454 framesRead = bytesRead / mFrameSize;
7455 }
7456 }
7457
Andy Hung446f4df2019-02-21 12:26:41 -08007458 const int64_t lastIoEndNs = systemTime(); // end IO timing
7459
Andy Hung3f0c9022016-01-15 17:49:46 -08007460 // Update server timestamp with server stats
7461 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007462 if (framesRead >= 0) {
7463 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7464 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7465 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007466
7467 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007468 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007469 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007470 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007471 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7472 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7473 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007474 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007475 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7476
7477 mTimestampVerifier.add(position, time, mSampleRate);
7478
7479 // Correct timestamps
7480 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007481 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007482 id(), (long long)time, (long long)position);
7483 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7484 position = correctedTimestamp.mFrames;
7485 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007486 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007487 id(), (long long)time, (long long)position);
7488 }
7489
Andy Hung3f0c9022016-01-15 17:49:46 -08007490 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7491 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7492 // Note: In general record buffers should tend to be empty in
7493 // a properly running pipeline.
7494 //
7495 // Also, it is not advantageous to call get_presentation_position during the read
7496 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007497 } else {
7498 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007499 }
7500 }
Andy Hunge6c37112019-02-26 17:38:10 -08007501
7502 // From the timestamp, input read latency is negative output write latency.
7503 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7504 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7505 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7506 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7507 mLatencyMs.add(latencyMs);
7508 }
7509
Andy Hung3f0c9022016-01-15 17:49:46 -08007510 // Use this to track timestamp information
7511 // ALOGD("%s", mTimestamp.toString().c_str());
7512
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007513 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007514 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007515 // Force input into standby so that it tries to recover at next read attempt
7516 inputStandBy();
7517 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007518 }
7519 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007520 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007521 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007522 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007523 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007524
Andy Hung8946a282018-04-19 20:04:56 -07007525#ifdef TEE_SINK
7526 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7527#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007528 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007529 {
7530 size_t part1 = mRsmpInFramesP2 - rear;
7531 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007532 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007533 (framesRead - part1) * mFrameSize);
7534 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007535 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007536 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007537
7538 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007539
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007540 // loop over each active track
7541 for (size_t i = 0; i < size; i++) {
7542 activeTrack = activeTracks[i];
7543
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007544 // skip fast tracks, as those are handled directly by FastCapture
7545 if (activeTrack->isFastTrack()) {
7546 continue;
7547 }
7548
Andy Hung73c02e42015-03-29 01:13:58 -07007549 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007550 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7551
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007552 enum {
7553 OVERRUN_UNKNOWN,
7554 OVERRUN_TRUE,
7555 OVERRUN_FALSE
7556 } overrun = OVERRUN_UNKNOWN;
7557
7558 // loop over getNextBuffer to handle circular sink
7559 for (;;) {
7560
7561 activeTrack->mSink.frameCount = ~0;
7562 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7563 size_t framesOut = activeTrack->mSink.frameCount;
7564 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7565
Andy Hung73c02e42015-03-29 01:13:58 -07007566 // check available frames and handle overrun conditions
7567 // if the record track isn't draining fast enough.
7568 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007569 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007570 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7571 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007572 overrun = OVERRUN_TRUE;
7573 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007574 if (framesOut == 0 || framesIn == 0) {
7575 break;
7576 }
7577
Andy Hung6770c6f2015-04-07 13:43:36 -07007578 // Don't allow framesOut to be larger than what is possible with resampling
7579 // from framesIn.
7580 // This isn't strictly necessary but helps limit buffer resizing in
7581 // RecordBufferConverter. TODO: remove when no longer needed.
7582 framesOut = min(framesOut,
7583 destinationFramesPossible(
7584 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007585
7586 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007587 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007588 // straight from RecordThread buffer to RecordTrack buffer.
7589 AudioBufferProvider::Buffer buffer;
7590 buffer.frameCount = framesOut;
7591 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7592 if (status == OK && buffer.frameCount != 0) {
7593 ALOGV_IF(buffer.frameCount != framesOut,
7594 "%s() read less than expected (%zu vs %zu)",
7595 __func__, buffer.frameCount, framesOut);
7596 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007597 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007598 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7599 } else {
7600 framesOut = 0;
7601 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7602 __func__, status, buffer.frameCount);
7603 }
7604 } else {
7605 // process frames from the RecordThread buffer provider to the RecordTrack
7606 // buffer
7607 framesOut = activeTrack->mRecordBufferConverter->convert(
7608 activeTrack->mSink.raw,
7609 activeTrack->mResamplerBufferProvider,
7610 framesOut);
7611 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007612
7613 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7614 overrun = OVERRUN_FALSE;
7615 }
7616
7617 if (activeTrack->mFramesToDrop == 0) {
7618 if (framesOut > 0) {
7619 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007620 // Sanitize before releasing if the track has no access to the source data
7621 // An idle UID receives silence from non virtual devices until active
7622 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007623 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007624 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007625 activeTrack->releaseBuffer(&activeTrack->mSink);
7626 }
7627 } else {
7628 // FIXME could do a partial drop of framesOut
7629 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007630 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007631 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007632 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007633 }
7634 } else {
7635 activeTrack->mFramesToDrop += framesOut;
7636 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7637 activeTrack->mSyncStartEvent->isCancelled()) {
7638 ALOGW("Synced record %s, session %d, trigger session %d",
7639 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7640 activeTrack->sessionId(),
7641 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007642 activeTrack->mSyncStartEvent->triggerSession() :
7643 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007644 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007645 }
7646 }
7647 }
7648
7649 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007650 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007651 }
7652 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007653
7654 switch (overrun) {
7655 case OVERRUN_TRUE:
7656 // client isn't retrieving buffers fast enough
7657 if (!activeTrack->setOverflow()) {
7658 nsecs_t now = systemTime();
7659 // FIXME should lastWarning per track?
7660 if ((now - lastWarning) > kWarningThrottleNs) {
7661 ALOGW("RecordThread: buffer overflow");
7662 lastWarning = now;
7663 }
7664 }
7665 break;
7666 case OVERRUN_FALSE:
7667 activeTrack->clearOverflow();
7668 break;
7669 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007670 break;
7671 }
7672
Andy Hung3f0c9022016-01-15 17:49:46 -08007673 // update frame information and push timestamp out
7674 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007675 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007676 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7677 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007678 }
7679
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007680unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007681 // enable changes in effect chain
7682 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007683 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007684 if (audio_has_proportional_frames(mFormat)
7685 && loopCount == lastLoopCountRead + 1) {
7686 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7687 const double jitterMs =
7688 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7689 {framesRead, readPeriodNs},
7690 {0, 0} /* lastTimestamp */, mSampleRate);
7691 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7692
7693 Mutex::Autolock _l(mLock);
7694 mIoJitterMs.add(jitterMs);
7695 mProcessTimeMs.add(processMs);
7696 }
7697 // update timing info.
7698 mLastIoBeginNs = lastIoBeginNs;
7699 mLastIoEndNs = lastIoEndNs;
7700 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007701 }
7702
Glenn Kasten93e471f2013-08-19 08:40:07 -07007703 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007704
7705 {
7706 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007707 for (size_t i = 0; i < mTracks.size(); i++) {
7708 sp<RecordTrack> track = mTracks[i];
7709 track->invalidate();
7710 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007711 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007712 mStartStopCond.broadcast();
7713 }
7714
7715 releaseWakeLock();
7716
7717 ALOGV("RecordThread %p exiting", this);
7718 return false;
7719}
7720
Glenn Kasten93e471f2013-08-19 08:40:07 -07007721void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007722{
7723 if (!mStandby) {
7724 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007725 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007726 mStandby = true;
7727 }
7728}
7729
7730void AudioFlinger::RecordThread::inputStandBy()
7731{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007732 // Idle the fast capture if it's currently running
7733 if (mFastCapture != 0) {
7734 FastCaptureStateQueue *sq = mFastCapture->sq();
7735 FastCaptureState *state = sq->begin();
7736 if (!(state->mCommand & FastCaptureState::IDLE)) {
7737 state->mCommand = FastCaptureState::COLD_IDLE;
7738 state->mColdFutexAddr = &mFastCaptureFutex;
7739 state->mColdGen++;
7740 mFastCaptureFutex = 0;
7741 sq->end();
7742 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7743 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7744#if 0
7745 if (kUseFastCapture == FastCapture_Dynamic) {
7746 // FIXME
7747 }
7748#endif
7749#ifdef AUDIO_WATCHDOG
7750 // FIXME
7751#endif
7752 } else {
7753 sq->end(false /*didModify*/);
7754 }
7755 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007756 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007757 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007758
7759 // If going into standby, flush the pipe source.
7760 if (mPipeSource.get() != nullptr) {
7761 const ssize_t flushed = mPipeSource->flush();
7762 if (flushed > 0) {
7763 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7764 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7765 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7766 }
7767 }
Eric Laurent81784c32012-11-19 14:55:58 -08007768}
7769
Glenn Kasten05997e22014-03-13 15:08:33 -07007770// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007771sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007772 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007773 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007774 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007775 audio_format_t format,
7776 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007777 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007778 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007779 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007780 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007781 const Identity& identity,
Eric Laurent05067782016-06-01 18:27:28 -07007782 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007783 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007784 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02007785 audio_port_handle_t portId,
7786 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08007787{
Glenn Kasten74935e42013-12-19 08:56:45 -08007788 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007789 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007790 sp<RecordTrack> track;
7791 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007792 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007793 audio_input_flags_t requestedFlags = *flags;
7794 uint32_t sampleRate;
Eric Laurentec376dc2021-04-08 20:41:22 +02007795 Identity checkedIdentity = AudioFlinger::checkIdentityPackage(identity);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007796
7797 lStatus = initCheck();
7798 if (lStatus != NO_ERROR) {
7799 ALOGE("createRecordTrack_l() audio driver not initialized");
7800 goto Exit;
7801 }
7802
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007803 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7804 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7805 lStatus = BAD_VALUE;
7806 goto Exit;
7807 }
7808
Eric Laurentec376dc2021-04-08 20:41:22 +02007809 if (maxSharedAudioHistoryMs != 0) {
7810 if (!captureHotwordAllowed(checkedIdentity)) {
7811 lStatus = PERMISSION_DENIED;
7812 goto Exit;
7813 }
7814 //TODO: b/185972521 allow resampling buffer resizing on fast mixers by pausing
7815 // the fast mixer thread while resizing the buffer in the normal thread
7816 if (hasFastCapture()) {
7817 lStatus = BAD_VALUE;
7818 goto Exit;
7819 }
7820 if (maxSharedAudioHistoryMs < 0
7821 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
7822 lStatus = BAD_VALUE;
7823 goto Exit;
7824 }
7825 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08007826 if (*pSampleRate == 0) {
7827 *pSampleRate = mSampleRate;
7828 }
7829 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007830
7831 // special case for FAST flag considered OK if fast capture is present
7832 if (hasFastCapture()) {
7833 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7834 }
7835
Eric Laurentf14db3c2017-12-08 14:20:36 -08007836 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007837 if ((*flags & inputFlags) != *flags) {
7838 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7839 " input flags (%08x)",
7840 *flags, inputFlags);
7841 *flags = (audio_input_flags_t)(*flags & inputFlags);
7842 }
Eric Laurent81784c32012-11-19 14:55:58 -08007843
Glenn Kasten90e58b12013-07-31 16:16:02 -07007844 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007845 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007846 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007847 // we formerly checked for a callback handler (non-0 tid),
7848 // but that is no longer required for TRANSFER_OBTAIN mode
7849 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007850 // Frame count is not specified (0), or is less than or equal the pipe depth.
7851 // It is OK to provide a higher capacity than requested.
7852 // We will force it to mPipeFramesP2 below.
7853 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007854 // PCM data
7855 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007856 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007857 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007858 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007859 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007860 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007861 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007862 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007863 hasFastCapture() &&
7864 // there are sufficient fast track slots available
7865 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007866 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007867 // check compatibility with audio effects.
7868 Mutex::Autolock _l(mLock);
7869 // Do not accept FAST flag if the session has software effects
7870 sp<EffectChain> chain = getEffectChain_l(sessionId);
7871 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007872 audio_input_flags_t old = *flags;
7873 chain->checkInputFlagCompatibility(flags);
7874 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007875 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7876 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007877 }
7878 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007879 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007880 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7881 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007882 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007883 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7884 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007885 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007886 this, frameCount, mFrameCount, mPipeFramesP2,
7887 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007888 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007889 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007890 }
7891 }
7892
Eric Laurentf14db3c2017-12-08 14:20:36 -08007893 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7894 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7895 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7896 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7897 lStatus = BAD_TYPE;
7898 goto Exit;
7899 }
7900
Glenn Kasten74105912014-07-03 12:28:53 -07007901 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007902 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007903 // fast track: frame count is exactly the pipe depth
7904 frameCount = mPipeFramesP2;
7905 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007906 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007907 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007908 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7909 // or 20 ms if there is a fast capture
7910 // TODO This could be a roundupRatio inline, and const
7911 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7912 * sampleRate + mSampleRate - 1) / mSampleRate;
7913 // minimum number of notification periods is at least kMinNotifications,
7914 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7915 static const size_t kMinNotifications = 3;
7916 static const uint32_t kMinMs = 30;
7917 // TODO This could be a roundupRatio inline
7918 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7919 // TODO This could be a roundupRatio inline
7920 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7921 maxNotificationFrames;
7922 const size_t minFrameCount = maxNotificationFrames *
7923 max(kMinNotifications, minNotificationsByMs);
7924 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007925 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7926 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007927 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007928 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007929 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007930 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007931
7932 { // scope for mLock
7933 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02007934 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02007935 if (!mSharedAudioPackageName.empty()
7936 && mSharedAudioPackageName == checkedIdentity.packageName
7937 && mSharedAudioSessionId == sessionId
7938 && captureHotwordAllowed(checkedIdentity)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02007939 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02007940 }
Eric Laurent81784c32012-11-19 14:55:58 -08007941
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007942 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007943 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007944 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Eric Laurent2407ce32021-04-26 14:56:03 +02007945 checkedIdentity, *flags, TrackBase::TYPE_DEFAULT, portId, startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08007946
Glenn Kasten03003332013-08-06 15:40:54 -07007947 lStatus = track->initCheck();
7948 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007949 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007950 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007951 goto Exit;
7952 }
7953 mTracks.add(track);
7954
Eric Laurent05067782016-06-01 18:27:28 -07007955 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007956 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7957 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7958 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007959 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007960 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007961
7962 if (maxSharedAudioHistoryMs != 0) {
7963 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
7964 }
7965
Eric Laurent81784c32012-11-19 14:55:58 -08007966 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007967
Eric Laurent81784c32012-11-19 14:55:58 -08007968 lStatus = NO_ERROR;
7969
7970Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007971 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007972 return track;
7973}
7974
7975status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7976 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007977 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007978{
7979 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7980 sp<ThreadBase> strongMe = this;
7981 status_t status = NO_ERROR;
7982
7983 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007984 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007985 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007986 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007987 triggerSession,
7988 recordTrack->sessionId(),
7989 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007990 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007991 // Sync event can be cancelled by the trigger session if the track is not in a
7992 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007993 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007994 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007995 } else {
7996 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007997 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007998 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007999 }
8000 }
8001
8002 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008003 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008004 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008005 if (recordTrack->isInvalid()) {
8006 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008007 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8008 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008009 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008010 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8011 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008012 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8013 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008014 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008015 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008016 } else {
8017 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008018 }
8019 return status;
8020 }
8021
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008022 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8023 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8024 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008025 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008026 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008027 status_t status = NO_ERROR;
8028 if (recordTrack->isExternalTrack()) {
8029 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008030 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008031 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008032 if (recordTrack->isInvalid()) {
8033 recordTrack->clearSyncStartEvent();
8034 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8035 recordTrack->mState = TrackBase::STARTING_2;
8036 // STARTING_2 forces destroy to call stopInput.
8037 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008038 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8039 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008040 }
8041 if (recordTrack->mState != TrackBase::STARTING_1) {
8042 ALOGW("%s(%d): unsynchronized mState:%d change",
8043 __func__, recordTrack->id(), recordTrack->mState);
8044 // Someone else has changed state, let them take over,
8045 // leave mState in the new state.
8046 recordTrack->clearSyncStartEvent();
8047 return INVALID_OPERATION;
8048 }
8049 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008050 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008051 ALOGW("%s(%d): startInput failed, status %d",
8052 __func__, recordTrack->id(), status);
8053 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8054 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008055 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008056 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008057 return status;
8058 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008059 sendIoConfigEvent_l(
8060 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008061 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008062
8063 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8064
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008065 // Catch up with current buffer indices if thread is already running.
8066 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8067 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8068 // see previously buffered data before it called start(), but with greater risk of overrun.
8069
Andy Hung73c02e42015-03-29 01:13:58 -07008070 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008071 if (!recordTrack->isDirect()) {
8072 // clear any converter state as new data will be discontinuous
8073 recordTrack->mRecordBufferConverter->reset();
8074 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008075 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008076 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008077 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008078 return status;
8079 }
Eric Laurent81784c32012-11-19 14:55:58 -08008080}
8081
Eric Laurent81784c32012-11-19 14:55:58 -08008082void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8083{
8084 sp<SyncEvent> strongEvent = event.promote();
8085
8086 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008087 sp<RefBase> ptr = strongEvent->cookie().promote();
8088 if (ptr != 0) {
8089 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8090 recordTrack->handleSyncStartEvent(strongEvent);
8091 }
Eric Laurent81784c32012-11-19 14:55:58 -08008092 }
8093}
8094
Glenn Kastena8356f62013-07-25 14:37:52 -07008095bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008096 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008097 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008098 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008099 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008100 return false;
8101 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008102 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008103 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008104
Andy Hungabfab202019-03-07 19:45:54 -08008105 // NOTE: Waiting here is important to keep stop synchronous.
8106 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008107 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8108 mWaitWorkCV.broadcast(); // signal thread to stop
8109 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008110 }
Andy Hungce685402018-10-05 17:23:27 -07008111
8112 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008113 ALOGV("Record stopped OK");
8114 return true;
8115 }
Andy Hungce685402018-10-05 17:23:27 -07008116
8117 // don't handle anything - we've been invalidated or restarted and in a different state
8118 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8119 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008120 return false;
8121}
8122
Glenn Kasten0f11b512014-01-31 16:18:54 -08008123bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008124{
8125 return false;
8126}
8127
Glenn Kasten0f11b512014-01-31 16:18:54 -08008128status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008129{
8130#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8131 if (!isValidSyncEvent(event)) {
8132 return BAD_VALUE;
8133 }
8134
Glenn Kastend848eb42016-03-08 13:42:11 -08008135 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008136 status_t ret = NAME_NOT_FOUND;
8137
8138 Mutex::Autolock _l(mLock);
8139
8140 for (size_t i = 0; i < mTracks.size(); i++) {
8141 sp<RecordTrack> track = mTracks[i];
8142 if (eventSession == track->sessionId()) {
8143 (void) track->setSyncEvent(event);
8144 ret = NO_ERROR;
8145 }
8146 }
8147 return ret;
8148#else
8149 return BAD_VALUE;
8150#endif
8151}
8152
jiabin653cc0a2018-01-17 17:54:10 -08008153status_t AudioFlinger::RecordThread::getActiveMicrophones(
8154 std::vector<media::MicrophoneInfo>* activeMicrophones)
8155{
8156 ALOGV("RecordThread::getActiveMicrophones");
8157 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008158 if (mInput == nullptr || mInput->stream == nullptr) {
8159 return NO_INIT;
8160 }
jiabin9ff780e2018-03-19 18:19:52 -07008161 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8162 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008163}
8164
Paul McLean12340082019-03-19 09:35:05 -06008165status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8166 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008167{
Paul McLean12340082019-03-19 09:35:05 -06008168 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008169 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008170 if (mInput == nullptr || mInput->stream == nullptr) {
8171 return NO_INIT;
8172 }
Paul McLean12340082019-03-19 09:35:05 -06008173 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008174}
8175
Paul McLean12340082019-03-19 09:35:05 -06008176status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008177{
Paul McLean12340082019-03-19 09:35:05 -06008178 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008179 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008180 if (mInput == nullptr || mInput->stream == nullptr) {
8181 return NO_INIT;
8182 }
Paul McLean12340082019-03-19 09:35:05 -06008183 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008184}
8185
Eric Laurentec376dc2021-04-08 20:41:22 +02008186status_t AudioFlinger::RecordThread::shareAudioHistory(
8187 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8188 int64_t sharedAudioStartMs) {
8189 AutoMutex _l(mLock);
8190 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8191}
8192
8193status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8194 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8195 int64_t sharedAudioStartMs) {
8196 if (hasFastCapture()) {
8197 return BAD_VALUE;
8198 }
8199 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8200 return BAD_VALUE;
8201 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008202
8203 if (sharedAudioStartMs < 0
8204 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008205 return BAD_VALUE;
8206 }
8207
Eric Laurent2407ce32021-04-26 14:56:03 +02008208 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8209 // As we cannot detect more than one wraparound, only accept values up current write position
8210 // after one wraparound
8211 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8212 // app waits several hours after the start time was computed.
8213 const int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
8214 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8215 (int32_t)sharedAudioStartFrames);
8216 if (sharedOffset < 0
8217 || sharedOffset > mRsmpInFrames) {
8218 return BAD_VALUE;
8219 }
8220
Eric Laurentec376dc2021-04-08 20:41:22 +02008221 mSharedAudioPackageName = sharedAudioPackageName;
8222 if (mSharedAudioPackageName.empty()) {
8223 mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent2407ce32021-04-26 14:56:03 +02008224 mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008225 } else {
8226 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008227 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008228 }
8229 return NO_ERROR;
8230}
8231
Kevin Rocard069c2712018-03-29 19:09:14 -07008232void AudioFlinger::RecordThread::updateMetadata_l()
8233{
8234 if (mInput == nullptr || mInput->stream == nullptr ||
8235 !mActiveTracks.readAndClearHasChanged()) {
8236 return;
8237 }
8238 StreamInHalInterface::SinkMetadata metadata;
8239 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008240 // Do not forward PatchRecord metadata to audio HAL
8241 if (track->isPatchTrack()) {
8242 continue;
8243 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008244 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008245 record_track_metadata_v7_t trackMetadata;
8246 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008247 .source = track->attributes().source,
8248 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008249 };
8250 trackMetadata.channel_mask = track->channelMask(),
8251 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8252
8253 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008254 }
8255 mInput->stream->updateSinkMetadata(metadata);
8256}
8257
Eric Laurent81784c32012-11-19 14:55:58 -08008258// destroyTrack_l() must be called with ThreadBase::mLock held
8259void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8260{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008261 track->terminate();
8262 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008263
Eric Laurent81784c32012-11-19 14:55:58 -08008264 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008265 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008266 removeTrack_l(track);
8267 }
8268}
8269
8270void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8271{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008272 String8 result;
8273 track->appendDump(result, false /* active */);
8274 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8275
Eric Laurent81784c32012-11-19 14:55:58 -08008276 mTracks.remove(track);
8277 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008278 if (track->isFastTrack()) {
8279 ALOG_ASSERT(!mFastTrackAvail);
8280 mFastTrackAvail = true;
8281 }
Eric Laurent81784c32012-11-19 14:55:58 -08008282}
8283
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008284void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008285{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008286 AudioStreamIn *input = mInput;
8287 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8288 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008289 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008290 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008291 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008292 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008293 }
Andy Hungbfa64962017-06-12 14:43:19 -07008294
8295 if (input != nullptr) {
8296 dprintf(fd, " Hal stream dump:\n");
8297 (void)input->stream->dump(fd);
8298 }
8299
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008300 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008301 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008302
Glenn Kasten2f90c512015-12-02 11:40:09 -08008303 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8304 // while we are dumping it. It may be inconsistent, but it won't mutate!
8305 // This is a large object so we place it on the heap.
8306 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008307 const std::unique_ptr<FastCaptureDumpState> copy =
8308 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008309 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008310}
8311
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008312void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008313{
Eric Laurent81784c32012-11-19 14:55:58 -08008314 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008315 size_t numtracks = mTracks.size();
8316 size_t numactive = mActiveTracks.size();
8317 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008318 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008319 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008320 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008321 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008322 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008323 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008324 for (size_t i = 0; i < numtracks ; ++i) {
8325 sp<RecordTrack> track = mTracks[i];
8326 if (track != 0) {
8327 bool active = mActiveTracks.indexOf(track) >= 0;
8328 if (active) {
8329 numactiveseen++;
8330 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008331 result.append(prefix);
8332 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008333 }
Eric Laurent81784c32012-11-19 14:55:58 -08008334 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008335 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008336 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008337 }
8338
Marco Nelissenb2208842014-02-07 14:00:50 -08008339 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008340 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008341 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008342 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008343 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008344 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008345 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008346 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008347 result.append(prefix);
8348 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008349 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008350 }
Eric Laurent81784c32012-11-19 14:55:58 -08008351
8352 }
8353 write(fd, result.string(), result.size());
8354}
8355
Eric Laurent5ada82e2019-08-29 17:53:54 -07008356void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008357{
8358 Mutex::Autolock _l(mLock);
8359 for (size_t i = 0; i < mTracks.size() ; i++) {
8360 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008361 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008362 track->setSilenced(silenced);
8363 }
8364 }
8365}
Andy Hung73c02e42015-03-29 01:13:58 -07008366
8367void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8368{
8369 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8370 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008371 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008372 const int32_t rear = recordThread->mRsmpInRear;
8373 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008374 if (mRecordTrack->startFrames() >= 0) {
8375 int32_t startFrames = mRecordTrack->startFrames();
8376 // Accept a recent wraparound of mRsmpInRear
8377 if (startFrames <= rear) {
8378 deltaFrames = rear - startFrames;
8379 } else {
8380 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008381 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008382 // start frame cannot be further in the past than start of resampling buffer
8383 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8384 deltaFrames = recordThread->mRsmpInFrames;
8385 }
8386 }
8387 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008388}
8389
8390void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8391 size_t *framesAvailable, bool *hasOverrun)
8392{
8393 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8394 RecordThread *recordThread = (RecordThread *) threadBase.get();
8395 const int32_t rear = recordThread->mRsmpInRear;
8396 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008397 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008398
8399 size_t framesIn;
8400 bool overrun = false;
8401 if (filled < 0) {
8402 // should not happen, but treat like a massive overrun and re-sync
8403 framesIn = 0;
8404 mRsmpInFront = rear;
8405 overrun = true;
8406 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8407 framesIn = (size_t) filled;
8408 } else {
8409 // client is not keeping up with server, but give it latest data
8410 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008411 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8412 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008413 overrun = true;
8414 }
8415 if (framesAvailable != NULL) {
8416 *framesAvailable = framesIn;
8417 }
8418 if (hasOverrun != NULL) {
8419 *hasOverrun = overrun;
8420 }
8421}
8422
Eric Laurent81784c32012-11-19 14:55:58 -08008423// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008424status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008425 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008426{
Andy Hung73c02e42015-03-29 01:13:58 -07008427 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008428 if (threadBase == 0) {
8429 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008430 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008431 return NOT_ENOUGH_DATA;
8432 }
8433 RecordThread *recordThread = (RecordThread *) threadBase.get();
8434 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008435 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008436 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008437 // FIXME should not be P2 (don't want to increase latency)
8438 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008439 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008440 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008441 front &= recordThread->mRsmpInFramesP2 - 1;
8442 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008443 if (part1 > (size_t) filled) {
8444 part1 = filled;
8445 }
8446 size_t ask = buffer->frameCount;
8447 ALOG_ASSERT(ask > 0);
8448 if (part1 > ask) {
8449 part1 = ask;
8450 }
8451 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008452 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008453 buffer->raw = NULL;
8454 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008455 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008456 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008457 }
8458
Andy Hung57446612015-04-19 23:56:46 -07008459 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008460 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008461 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008462 return NO_ERROR;
8463}
8464
8465// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008466void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8467 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008468{
Hongwei Wang95e37682019-04-12 11:13:36 -07008469 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008470 if (stepCount == 0) {
8471 return;
8472 }
Andy Hung73c02e42015-03-29 01:13:58 -07008473 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8474 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008475 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008476 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008477 buffer->frameCount = 0;
8478}
8479
Eric Laurentd8365c52017-07-16 15:27:05 -07008480void AudioFlinger::RecordThread::checkBtNrec()
8481{
8482 Mutex::Autolock _l(mLock);
8483 checkBtNrec_l();
8484}
8485
8486void AudioFlinger::RecordThread::checkBtNrec_l()
8487{
8488 // disable AEC and NS if the device is a BT SCO headset supporting those
8489 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008490 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008491 mAudioFlinger->btNrecIsOff();
8492 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8493 for (size_t i = 0; i < mEffectChains.size(); i++) {
8494 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8495 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8496 }
8497 }
8498}
8499
Andy Hung97a893e2015-03-29 01:03:07 -07008500
Eric Laurent10351942014-05-08 18:49:52 -07008501bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8502 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008503{
8504 bool reconfig = false;
8505
Eric Laurent10351942014-05-08 18:49:52 -07008506 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008507
Eric Laurent10351942014-05-08 18:49:52 -07008508 audio_format_t reqFormat = mFormat;
8509 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008510 // 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 -07008511 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8512
8513 AudioParameter param = AudioParameter(keyValuePair);
8514 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008515
8516 // scope for AutoPark extends to end of method
8517 AutoPark<FastCapture> park(mFastCapture);
8518
Eric Laurent10351942014-05-08 18:49:52 -07008519 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8520 // channel count change can be requested. Do we mandate the first client defines the
8521 // HAL sampling rate and channel count or do we allow changes on the fly?
8522 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8523 samplingRate = value;
8524 reconfig = true;
8525 }
8526 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008527 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008528 status = BAD_VALUE;
8529 } else {
8530 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008531 reconfig = true;
8532 }
Eric Laurent10351942014-05-08 18:49:52 -07008533 }
8534 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8535 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008536 if (!audio_is_input_channel(mask) ||
8537 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008538 status = BAD_VALUE;
8539 } else {
8540 channelMask = mask;
8541 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008542 }
Eric Laurent10351942014-05-08 18:49:52 -07008543 }
8544 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8545 // do not accept frame count changes if tracks are open as the track buffer
8546 // size depends on frame count and correct behavior would not be guaranteed
8547 // if frame count is changed after track creation
8548 if (mActiveTracks.size() > 0) {
8549 status = INVALID_OPERATION;
8550 } else {
8551 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008552 }
Eric Laurent10351942014-05-08 18:49:52 -07008553 }
8554 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008555 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008556 }
8557 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8558 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008559 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008560 }
Glenn Kastene198c362013-08-13 09:13:36 -07008561
Eric Laurent10351942014-05-08 18:49:52 -07008562 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008563 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008564 if (status == INVALID_OPERATION) {
8565 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008566 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008567 }
8568 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008569 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008570 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8571 if (mInput->stream->getAudioProperties(&config) == OK &&
8572 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8573 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8574 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_8) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008575 status = NO_ERROR;
8576 }
Eric Laurent81784c32012-11-19 14:55:58 -08008577 }
Eric Laurent10351942014-05-08 18:49:52 -07008578 if (status == NO_ERROR) {
8579 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008580 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008581 }
8582 }
Eric Laurent81784c32012-11-19 14:55:58 -08008583 }
Eric Laurent10351942014-05-08 18:49:52 -07008584
Eric Laurent81784c32012-11-19 14:55:58 -08008585 return reconfig;
8586}
8587
8588String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8589{
Eric Laurent81784c32012-11-19 14:55:58 -08008590 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008591 if (initCheck() == NO_ERROR) {
8592 String8 out_s8;
8593 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8594 return out_s8;
8595 }
Eric Laurent81784c32012-11-19 14:55:58 -08008596 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008597 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008598}
8599
Eric Laurent09f1ed22019-04-24 17:45:17 -07008600void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8601 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008602 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8603
8604 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008605
8606 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008607 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008608 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008609 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008610 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008611 desc->mChannelMask = mChannelMask;
8612 desc->mSamplingRate = mSampleRate;
8613 desc->mFormat = mFormat;
8614 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008615 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008616 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008617 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008618 case AUDIO_CLIENT_STARTED:
8619 desc->mPatch = mPatch;
8620 desc->mPortId = portId;
8621 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008622 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008623 default:
8624 break;
8625 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008626 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008627}
8628
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008629void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008630{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008631 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8632 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008633 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008634 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8635 if (audio_is_linear_pcm(mFormat)) {
8636 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8637 mChannelCount, FCC_8);
8638 } else {
8639 // Can have more that FCC_8 channels in encoded streams.
8640 ALOGI("HAL format %#x is not linear pcm", mFormat);
8641 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008642 result = mInput->stream->getFrameSize(&mFrameSize);
8643 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008644 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8645 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008646 result = mInput->stream->getBufferSize(&mBufferSize);
8647 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008648 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008649 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8650 "mBufferSize=%zu, mFrameCount=%zu",
8651 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008652
Eric Laurentec376dc2021-04-08 20:41:22 +02008653 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8654 mRsmpInFrames = 0;
8655 resizeInputBuffer_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008656
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008657 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8658 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008659
8660 audio_input_flags_t flags = mInput->flags;
8661 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8662 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8663 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8664 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8665 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8666 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8667 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8668 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8669 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008670}
8671
Glenn Kasten5f972c02014-01-13 09:59:31 -08008672uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008673{
8674 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008675 uint32_t result;
8676 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8677 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008678 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008679 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008680}
8681
Glenn Kastend848eb42016-03-08 13:42:11 -08008682KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008683{
Glenn Kastend848eb42016-03-08 13:42:11 -08008684 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008685 Mutex::Autolock _l(mLock);
8686 for (size_t j = 0; j < mTracks.size(); ++j) {
8687 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008688 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008689 if (ids.indexOfKey(sessionId) < 0) {
8690 ids.add(sessionId, true);
8691 }
8692 }
8693 return ids;
8694}
8695
8696AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8697{
8698 Mutex::Autolock _l(mLock);
8699 AudioStreamIn *input = mInput;
8700 mInput = NULL;
8701 return input;
8702}
8703
8704// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008705sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008706{
8707 if (mInput == NULL) {
8708 return NULL;
8709 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008710 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008711}
8712
8713status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8714{
Eric Laurent81784c32012-11-19 14:55:58 -08008715 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008716 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008717 chain->setInBuffer(NULL);
8718 chain->setOutBuffer(NULL);
8719
8720 checkSuspendOnAddEffectChain_l(chain);
8721
Eric Laurent1b928682014-10-02 19:41:47 -07008722 // make sure enabled pre processing effects state is communicated to the HAL as we
8723 // just moved them to a new input stream.
8724 chain->syncHalEffectsState();
8725
Eric Laurent81784c32012-11-19 14:55:58 -08008726 mEffectChains.add(chain);
8727
8728 return NO_ERROR;
8729}
8730
8731size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8732{
8733 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008734
8735 for (size_t i = 0; i < mEffectChains.size(); i++) {
8736 if (chain == mEffectChains[i]) {
8737 mEffectChains.removeAt(i);
8738 break;
8739 }
Eric Laurent81784c32012-11-19 14:55:58 -08008740 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008741 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008742}
8743
Eric Laurent1c333e22014-05-20 10:48:17 -07008744status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8745 audio_patch_handle_t *handle)
8746{
8747 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008748
8749 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008750 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008751 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008752 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008753 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008754 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008755 }
8756
Eric Laurentd8365c52017-07-16 15:27:05 -07008757 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008758
8759 // store new source and send to effects
8760 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8761 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008762 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008763 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008764 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008765 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008766
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008767 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008768 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8769 status = hwDevice->createAudioPatch(patch->num_sources,
8770 patch->sources,
8771 patch->num_sinks,
8772 patch->sinks,
8773 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008774 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008775 char *address;
8776 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8777 address = audio_device_address_to_parameter(
8778 patch->sources[0].ext.device.type,
8779 patch->sources[0].ext.device.address);
8780 } else {
8781 address = (char *)calloc(1, 1);
8782 }
8783 AudioParameter param = AudioParameter(String8(address));
8784 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008785 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008786 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008787 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008788 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008789 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008790 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008791 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008792
jiabinc52b1ff2019-10-31 17:20:42 -07008793 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008794 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008795 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008796 }
Eric Laurent296fb132015-05-01 11:38:42 -07008797
Andy Hungc2b11cb2020-04-22 09:04:01 -07008798 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008799 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008800 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008801 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008802 // also dispatch to active AudioRecords
8803 for (const auto &track : mActiveTracks) {
8804 track->logEndInterval();
8805 track->logBeginInterval(pathSourcesAsString);
8806 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008807 return status;
8808}
8809
8810status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8811{
8812 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008813
jiabinc52b1ff2019-10-31 17:20:42 -07008814 mPatch = audio_patch{};
8815 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008816
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008817 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008818 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8819 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008820 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008821 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008822 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008823 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008824 }
8825 return status;
8826}
8827
jiabinc52b1ff2019-10-31 17:20:42 -07008828void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8829{
wendy lin56aa82b2020-12-02 15:19:55 +08008830 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07008831 mOutDevices = outDevices;
8832 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8833 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008834 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008835 }
8836}
8837
Eric Laurentec376dc2021-04-08 20:41:22 +02008838int32_t AudioFlinger::RecordThread::getOldestFront_l()
8839{
8840 if (mTracks.size() == 0) {
8841 return 0;
8842 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008843 int32_t oldestFront = mRsmpInRear;
8844 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008845 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008846 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8847 int32_t filled;
8848 if (front <= mRsmpInRear) {
8849 filled = mRsmpInRear - front;
8850 } else {
8851 filled = (int32_t)((int64_t)mRsmpInRear + UINT32_MAX + 1 - front);
8852 }
8853 if (filled > maxFilled) {
8854 oldestFront = front;
8855 maxFilled = filled;
8856 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008857 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008858 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02008859}
8860
8861void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
8862{
8863 if (offset == 0) {
8864 return;
8865 }
8866 for (size_t i = 0; i < mTracks.size(); i++) {
8867 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8868 front = audio_utils::safe_sub_overflow(front, offset);
8869 mTracks[i]->mResamplerBufferProvider->setFront(front);
8870 }
8871}
8872
8873void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
8874{
8875 // This is the formula for calculating the temporary buffer size.
8876 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
8877 // 1 full output buffer, regardless of the alignment of the available input.
8878 // The value is somewhat arbitrary, and could probably be even larger.
8879 // A larger value should allow more old data to be read after a track calls start(),
8880 // without increasing latency.
8881 //
8882 // Note this is independent of the maximum downsampling ratio permitted for capture.
8883 size_t minRsmpInFrames = mFrameCount * 7;
8884
8885 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
8886 // capture history available to another client using the same session ID:
8887 // dimension the resampler input buffer accordingly.
8888
8889 // Get oldest client read position: getOldestFront_l() must be called before altering
8890 // mRsmpInRear, or mRsmpInFrames
8891 int32_t previousFront = getOldestFront_l();
8892 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
8893 int32_t previousRear = mRsmpInRear;
8894 mRsmpInRear = 0;
8895
8896 if (maxSharedAudioHistoryMs != 0) {
8897 // resizeInputBuffer_l should never be called with a non zero shared history if the
8898 // buffer was not already allocated
8899 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
8900 "resizeInputBuffer_l() called with shared history and unallocated buffer");
8901 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
8902 // never reduce resampler input buffer size
8903 if (rsmpInFrames < mRsmpInFrames) {
8904 return;
8905 }
8906 mRsmpInFrames = rsmpInFrames;
8907 }
8908 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
8909 // initialized
8910 if (mRsmpInFrames < minRsmpInFrames) {
8911 mRsmpInFrames = minRsmpInFrames;
8912 }
8913 mRsmpInFramesP2 = roundup(mRsmpInFrames);
8914
8915 // TODO optimize audio capture buffer sizes ...
8916 // Here we calculate the size of the sliding buffer used as a source
8917 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8918 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8919 // be better to have it derived from the pipe depth in the long term.
8920 // The current value is higher than necessary. However it should not add to latency.
8921
8922 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
8923 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8924
8925 void *rsmpInBuffer;
8926 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
8927 // if posix_memalign fails, will segv here.
8928 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
8929
8930 // Copy audio history if any from old buffer before freeing it
8931 if (previousRear != 0) {
8932 ALOG_ASSERT(mRsmpInBuffer != nullptr,
8933 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
8934
8935 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
8936 previousFront &= previousRsmpInFramesP2 - 1;
8937 size_t part1 = previousRsmpInFramesP2 - previousFront;
8938 if (part1 > (size_t) unread) {
8939 part1 = unread;
8940 }
8941 if (part1 != 0) {
8942 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
8943 part1 * mFrameSize);
8944 mRsmpInRear = part1;
8945 part1 = unread - part1;
8946 if (part1 != 0) {
8947 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
8948 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
8949 mRsmpInRear += part1;
8950 }
8951 }
8952 // Update front for all clients according to new rear
8953 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
8954 } else {
8955 mRsmpInRear = 0;
8956 }
8957 free(mRsmpInBuffer);
8958 mRsmpInBuffer = rsmpInBuffer;
8959}
8960
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008961void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008962{
8963 Mutex::Autolock _l(mLock);
8964 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008965 if (record->getSource()) {
8966 mSource = record->getSource();
8967 }
Eric Laurent83b88082014-06-20 18:31:16 -07008968}
8969
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008970void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008971{
8972 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008973 if (mSource == record->getSource()) {
8974 mSource = mInput;
8975 }
Eric Laurent83b88082014-06-20 18:31:16 -07008976 destroyTrack_l(record);
8977}
8978
Mikhail Naganovdc769682018-05-04 15:34:08 -07008979void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008980{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008981 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008982 config->role = AUDIO_PORT_ROLE_SINK;
8983 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8984 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008985 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8986 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8987 config->flags.input = mInput->flags;
8988 }
Eric Laurent83b88082014-06-20 18:31:16 -07008989}
Eric Laurent1c333e22014-05-20 10:48:17 -07008990
Eric Laurent6acd1d42017-01-04 14:23:29 -08008991// ----------------------------------------------------------------------------
8992// Mmap
8993// ----------------------------------------------------------------------------
8994
8995AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8996 : mThread(thread)
8997{
Phil Burk9fabbf82017-08-03 12:02:00 -07008998 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008999}
9000
9001AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9002{
Phil Burk9fabbf82017-08-03 12:02:00 -07009003 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009004}
9005
9006status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9007 struct audio_mmap_buffer_info *info)
9008{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009009 return mThread->createMmapBuffer(minSizeFrames, info);
9010}
9011
9012status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9013{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009014 return mThread->getMmapPosition(position);
9015}
9016
jiabinb7d8c5a2020-08-26 17:24:52 -07009017status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9018 int64_t *timeNanos) {
9019 return mThread->getExternalPosition(position, timeNanos);
9020}
9021
Eric Laurenta54f1282017-07-01 19:39:32 -07009022status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009023 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009024
9025{
jiabind1f1cb62020-03-24 11:57:57 -07009026 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009027}
9028
9029status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9030{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009031 return mThread->stop(handle);
9032}
9033
Eric Laurent18b57012017-02-13 16:23:52 -08009034status_t AudioFlinger::MmapThreadHandle::standby()
9035{
Eric Laurent18b57012017-02-13 16:23:52 -08009036 return mThread->standby();
9037}
9038
Eric Laurent6acd1d42017-01-04 14:23:29 -08009039
9040AudioFlinger::MmapThread::MmapThread(
9041 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009042 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009043 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009044 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009045 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009046 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009047 mActiveTracks(&this->mLocalLog),
9048 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9049 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009050{
Eric Laurent18b57012017-02-13 16:23:52 -08009051 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009052 readHalParameters_l();
9053}
9054
9055AudioFlinger::MmapThread::~MmapThread()
9056{
9057}
9058
9059void AudioFlinger::MmapThread::onFirstRef()
9060{
9061 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9062}
9063
9064void AudioFlinger::MmapThread::disconnect()
9065{
Eric Laurent331679c2018-04-16 17:03:16 -07009066 ActiveTracks<MmapTrack> activeTracks;
9067 {
9068 Mutex::Autolock _l(mLock);
9069 for (const sp<MmapTrack> &t : mActiveTracks) {
9070 activeTracks.add(t);
9071 }
9072 }
9073 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009074 stop(t->portId());
9075 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009076 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009077 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009078 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009079 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009080 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009081 }
9082}
9083
9084
9085void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9086 audio_stream_type_t streamType __unused,
9087 audio_session_t sessionId,
9088 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009089 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009090 audio_port_handle_t portId)
9091{
9092 mAttr = *attr;
9093 mSessionId = sessionId;
9094 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009095 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009096 mPortId = portId;
9097}
9098
9099status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9100 struct audio_mmap_buffer_info *info)
9101{
9102 if (mHalStream == 0) {
9103 return NO_INIT;
9104 }
Eric Laurent18b57012017-02-13 16:23:52 -08009105 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009106 return mHalStream->createMmapBuffer(minSizeFrames, info);
9107}
9108
9109status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9110{
9111 if (mHalStream == 0) {
9112 return NO_INIT;
9113 }
9114 return mHalStream->getMmapPosition(position);
9115}
9116
Eric Laurent331679c2018-04-16 17:03:16 -07009117status_t AudioFlinger::MmapThread::exitStandby()
9118{
9119 status_t ret = mHalStream->start();
9120 if (ret != NO_ERROR) {
9121 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9122 return ret;
9123 }
Andy Hungcf10d742020-04-28 15:38:24 -07009124 if (mStandby) {
9125 mThreadMetrics.logBeginInterval();
9126 mStandby = false;
9127 }
Eric Laurent331679c2018-04-16 17:03:16 -07009128 return NO_ERROR;
9129}
9130
Eric Laurenta54f1282017-07-01 19:39:32 -07009131status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009132 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009133 audio_port_handle_t *handle)
9134{
Eric Laurenta54f1282017-07-01 19:39:32 -07009135 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009136 client.identity.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009137 if (mHalStream == 0) {
9138 return NO_INIT;
9139 }
9140
9141 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009142
Eric Laurenta54f1282017-07-01 19:39:32 -07009143 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009144 // For the first track, reuse portId and session allocated when the stream was opened.
9145 ret = exitStandby();
9146 if (ret == NO_ERROR) {
9147 acquireWakeLock();
9148 }
9149 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009150 }
9151
9152 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9153
9154 audio_io_handle_t io = mId;
9155 if (isOutput()) {
9156 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9157 config.sample_rate = mSampleRate;
9158 config.channel_mask = mChannelMask;
9159 config.format = mFormat;
9160 audio_stream_type_t stream = streamType();
9161 audio_output_flags_t flags =
9162 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009163 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009164 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009165 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9166 mSessionId,
9167 &stream,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009168 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07009169 &config,
9170 flags,
9171 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009172 &portId,
9173 &secondaryOutputs);
9174 ALOGD_IF(!secondaryOutputs.empty(),
9175 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009176 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009177 audio_config_base_t config;
9178 config.sample_rate = mSampleRate;
9179 config.channel_mask = mChannelMask;
9180 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009181 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009182 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009183 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009184 mSessionId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009185 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07009186 &config,
9187 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9188 &deviceId,
9189 &portId);
9190 }
9191 // APM should not chose a different input or output stream for the same set of attributes
9192 // and audo configuration
9193 if (ret != NO_ERROR || io != mId) {
9194 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9195 __FUNCTION__, ret, io, mId);
9196 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009197 }
9198
9199 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009200 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009201 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009202 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009203 }
9204
Eric Laurent331679c2018-04-16 17:03:16 -07009205 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009206 // abort if start is rejected by audio policy manager
9207 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009208 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009209 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009210 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009211 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009212 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009213 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009214 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009215 }
Eric Laurent331679c2018-04-16 17:03:16 -07009216 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009217 } else {
9218 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009219 }
9220 return PERMISSION_DENIED;
9221 }
9222
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009223 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009224 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009225 mChannelMask, mSessionId, isOutput(), client.identity,
9226 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009227
Eric Laurent4eb58f12018-12-07 16:41:02 -08009228 if (isOutput()) {
9229 // force volume update when a new track is added
9230 mHalVolFloat = -1.0f;
9231 } else if (!track->isSilenced_l()) {
9232 for (const sp<MmapTrack> &t : mActiveTracks) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009233 if (t->isSilenced_l() && t->uid() != client.identity.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009234 t->invalidate();
9235 }
9236 }
9237
9238
Eric Laurent6acd1d42017-01-04 14:23:29 -08009239 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009240 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009241 if (chain != 0) {
9242 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
9243 chain->incTrackCnt();
9244 chain->incActiveTrackCnt();
9245 }
9246
Andy Hungc2b11cb2020-04-22 09:04:01 -07009247 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009248 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009249 broadcast_l();
9250
Eric Laurenta54f1282017-07-01 19:39:32 -07009251 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009252
9253 return NO_ERROR;
9254}
9255
9256status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9257{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009258 ALOGV("%s handle %d", __FUNCTION__, handle);
9259
9260 if (mHalStream == 0) {
9261 return NO_INIT;
9262 }
9263
Eric Laurenta54f1282017-07-01 19:39:32 -07009264 if (handle == mPortId) {
9265 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009266 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009267 return NO_ERROR;
9268 }
9269
Eric Laurent331679c2018-04-16 17:03:16 -07009270 Mutex::Autolock _l(mLock);
9271
Eric Laurent6acd1d42017-01-04 14:23:29 -08009272 sp<MmapTrack> track;
9273 for (const sp<MmapTrack> &t : mActiveTracks) {
9274 if (handle == t->portId()) {
9275 track = t;
9276 break;
9277 }
9278 }
9279 if (track == 0) {
9280 return BAD_VALUE;
9281 }
9282
9283 mActiveTracks.remove(track);
9284
Eric Laurent331679c2018-04-16 17:03:16 -07009285 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009286 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009287 AudioSystem::stopOutput(track->portId());
9288 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009289 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009290 AudioSystem::stopInput(track->portId());
9291 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009292 }
Eric Laurent331679c2018-04-16 17:03:16 -07009293 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009294
9295 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9296 if (chain != 0) {
9297 chain->decActiveTrackCnt();
9298 chain->decTrackCnt();
9299 }
9300
9301 broadcast_l();
9302
Eric Laurent6acd1d42017-01-04 14:23:29 -08009303 return NO_ERROR;
9304}
9305
Eric Laurent18b57012017-02-13 16:23:52 -08009306status_t AudioFlinger::MmapThread::standby()
9307{
9308 ALOGV("%s", __FUNCTION__);
9309
9310 if (mHalStream == 0) {
9311 return NO_INIT;
9312 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009313 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009314 return INVALID_OPERATION;
9315 }
9316 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009317 if (!mStandby) {
9318 mThreadMetrics.logEndInterval();
9319 mStandby = true;
9320 }
Eric Laurent18b57012017-02-13 16:23:52 -08009321 releaseWakeLock();
9322 return NO_ERROR;
9323}
9324
Eric Laurent6acd1d42017-01-04 14:23:29 -08009325
9326void AudioFlinger::MmapThread::readHalParameters_l()
9327{
9328 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9329 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9330 mFormat = mHALFormat;
9331 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9332 result = mHalStream->getFrameSize(&mFrameSize);
9333 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009334 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9335 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009336 result = mHalStream->getBufferSize(&mBufferSize);
9337 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9338 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009339
Andy Hungcf10d742020-04-28 15:38:24 -07009340 // TODO: make a readHalParameters call?
9341 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009342 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9343 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9344 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9345 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9346 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9347 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9348 /*
9349 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9350 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9351 (int32_t)mHapticChannelMask)
9352 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9353 (int32_t)mHapticChannelCount)
9354 */
9355 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9356 formatToString(mHALFormat).c_str())
9357 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9358 (int32_t)mFrameCount) // sic - added HAL
9359 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009360}
9361
9362bool AudioFlinger::MmapThread::threadLoop()
9363{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009364 checkSilentMode_l();
9365
9366 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9367
9368 while (!exitPending())
9369 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009370 Vector< sp<EffectChain> > effectChains;
9371
Andy Hung13850be2019-03-14 11:33:09 -07009372 { // under Thread lock
9373 Mutex::Autolock _l(mLock);
9374
Eric Laurent6acd1d42017-01-04 14:23:29 -08009375 if (mSignalPending) {
9376 // A signal was raised while we were unlocked
9377 mSignalPending = false;
9378 } else {
9379 if (mConfigEvents.isEmpty()) {
9380 // we're about to wait, flush the binder command buffer
9381 IPCThreadState::self()->flushCommands();
9382
9383 if (exitPending()) {
9384 break;
9385 }
9386
Eric Laurent6acd1d42017-01-04 14:23:29 -08009387 // wait until we have something to do...
9388 ALOGV("%s going to sleep", myName.string());
9389 mWaitWorkCV.wait(mLock);
9390 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009391
9392 checkSilentMode_l();
9393
9394 continue;
9395 }
9396 }
9397
9398 processConfigEvents_l();
9399
9400 processVolume_l();
9401
9402 checkInvalidTracks_l();
9403
9404 mActiveTracks.updatePowerState(this);
9405
Kevin Rocard069c2712018-03-29 19:09:14 -07009406 updateMetadata_l();
9407
Eric Laurent6acd1d42017-01-04 14:23:29 -08009408 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009409 } // release Thread lock
9410
Eric Laurent6acd1d42017-01-04 14:23:29 -08009411 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009412 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009413 }
Andy Hung13850be2019-03-14 11:33:09 -07009414
9415 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009416 unlockEffectChains(effectChains);
9417 // Effect chains will be actually deleted here if they were removed from
9418 // mEffectChains list during mixing or effects processing
9419 }
9420
9421 threadLoop_exit();
9422
9423 if (!mStandby) {
9424 threadLoop_standby();
9425 mStandby = true;
9426 }
9427
Eric Laurent6acd1d42017-01-04 14:23:29 -08009428 ALOGV("Thread %p type %d exiting", this, mType);
9429 return false;
9430}
9431
9432// checkForNewParameter_l() must be called with ThreadBase::mLock held
9433bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9434 status_t& status)
9435{
9436 AudioParameter param = AudioParameter(keyValuePair);
9437 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009438 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009439 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009440 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009441 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009442 if (sendToHal) {
9443 status = mHalStream->setParameters(keyValuePair);
9444 } else {
9445 status = NO_ERROR;
9446 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009447
9448 return false;
9449}
9450
9451String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9452{
9453 Mutex::Autolock _l(mLock);
9454 String8 out_s8;
9455 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9456 return out_s8;
9457 }
9458 return String8();
9459}
9460
Eric Laurent09f1ed22019-04-24 17:45:17 -07009461void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9462 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009463 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9464
9465 desc->mIoHandle = mId;
9466
9467 switch (event) {
9468 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009469 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009470 case AUDIO_INPUT_CONFIG_CHANGED:
9471 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009472 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009473 case AUDIO_OUTPUT_CONFIG_CHANGED:
9474 desc->mPatch = mPatch;
9475 desc->mChannelMask = mChannelMask;
9476 desc->mSamplingRate = mSampleRate;
9477 desc->mFormat = mFormat;
9478 desc->mFrameCount = mFrameCount;
9479 desc->mFrameCountHAL = mFrameCount;
9480 desc->mLatency = 0;
9481 break;
9482
9483 case AUDIO_INPUT_CLOSED:
9484 case AUDIO_OUTPUT_CLOSED:
9485 default:
9486 break;
9487 }
9488 mAudioFlinger->ioConfigChanged(event, desc, pid);
9489}
9490
9491status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9492 audio_patch_handle_t *handle)
9493{
9494 status_t status = NO_ERROR;
9495
9496 // store new device and send to effects
9497 audio_devices_t type = AUDIO_DEVICE_NONE;
9498 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009499 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9500 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9501 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009502 if (isOutput()) {
9503 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009504 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9505 && !mAudioHwDev->supportsAudioPatches(),
9506 "Enumerated device type(%#x) must not be used "
9507 "as it does not support audio patches",
9508 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009509 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009510 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9511 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009512 }
9513 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009514 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009515 } else {
9516 type = patch->sources[0].ext.device.type;
9517 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009518 numDevices = mPatch.num_sources;
9519 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009520 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009521 }
9522
9523 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009524 if (isOutput()) {
9525 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9526 } else {
9527 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9528 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009529 }
9530
jiabinc52b1ff2019-10-31 17:20:42 -07009531 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009532 // store new source and send to effects
9533 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9534 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9535 for (size_t i = 0; i < mEffectChains.size(); i++) {
9536 mEffectChains[i]->setAudioSource_l(mAudioSource);
9537 }
9538 }
9539 }
9540
9541 if (mAudioHwDev->supportsAudioPatches()) {
9542 status = mHalDevice->createAudioPatch(patch->num_sources,
9543 patch->sources,
9544 patch->num_sinks,
9545 patch->sinks,
9546 handle);
9547 } else {
9548 char *address;
9549 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9550 //FIXME: we only support address on first sink with HAL version < 3.0
9551 address = audio_device_address_to_parameter(
9552 patch->sinks[0].ext.device.type,
9553 patch->sinks[0].ext.device.address);
9554 } else {
9555 address = (char *)calloc(1, 1);
9556 }
9557 AudioParameter param = AudioParameter(String8(address));
9558 free(address);
9559 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9560 if (!isOutput()) {
9561 param.addInt(String8(AudioParameter::keyInputSource),
9562 (int)patch->sinks[0].ext.mix.usecase.source);
9563 }
9564 status = mHalStream->setParameters(param.toString());
9565 *handle = AUDIO_PATCH_HANDLE_NONE;
9566 }
9567
jiabinc52b1ff2019-10-31 17:20:42 -07009568 if (numDevices == 0 || mDeviceId != deviceId) {
9569 if (isOutput()) {
9570 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9571 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009572 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009573 } else {
9574 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9575 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9576 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009577 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009578 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009579 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009580 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009581 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009582 }
jiabinc52b1ff2019-10-31 17:20:42 -07009583 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009584 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009585 }
9586 return status;
9587}
9588
9589status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9590{
9591 status_t status = NO_ERROR;
9592
jiabinc52b1ff2019-10-31 17:20:42 -07009593 mPatch = audio_patch{};
9594 mOutDeviceTypeAddrs.clear();
9595 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009596
9597 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9598 supportsAudioPatches : false;
9599
9600 if (supportsAudioPatches) {
9601 status = mHalDevice->releaseAudioPatch(handle);
9602 } else {
9603 AudioParameter param;
9604 param.addInt(String8(AudioParameter::keyRouting), 0);
9605 status = mHalStream->setParameters(param.toString());
9606 }
9607 return status;
9608}
9609
Mikhail Naganovdc769682018-05-04 15:34:08 -07009610void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009611{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009612 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009613 if (isOutput()) {
9614 config->role = AUDIO_PORT_ROLE_SOURCE;
9615 config->ext.mix.hw_module = mAudioHwDev->handle();
9616 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9617 } else {
9618 config->role = AUDIO_PORT_ROLE_SINK;
9619 config->ext.mix.hw_module = mAudioHwDev->handle();
9620 config->ext.mix.usecase.source = mAudioSource;
9621 }
9622}
9623
9624status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9625{
9626 audio_session_t session = chain->sessionId();
9627
9628 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9629 // Attach all tracks with same session ID to this chain.
9630 // indicate all active tracks in the chain
9631 for (const sp<MmapTrack> &track : mActiveTracks) {
9632 if (session == track->sessionId()) {
9633 chain->incTrackCnt();
9634 chain->incActiveTrackCnt();
9635 }
9636 }
9637
9638 chain->setThread(this);
9639 chain->setInBuffer(nullptr);
9640 chain->setOutBuffer(nullptr);
9641 chain->syncHalEffectsState();
9642
9643 mEffectChains.add(chain);
9644 checkSuspendOnAddEffectChain_l(chain);
9645 return NO_ERROR;
9646}
9647
9648size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9649{
9650 audio_session_t session = chain->sessionId();
9651
9652 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9653
9654 for (size_t i = 0; i < mEffectChains.size(); i++) {
9655 if (chain == mEffectChains[i]) {
9656 mEffectChains.removeAt(i);
9657 // detach all active tracks from the chain
9658 // detach all tracks with same session ID from this chain
9659 for (const sp<MmapTrack> &track : mActiveTracks) {
9660 if (session == track->sessionId()) {
9661 chain->decActiveTrackCnt();
9662 chain->decTrackCnt();
9663 }
9664 }
9665 break;
9666 }
9667 }
9668 return mEffectChains.size();
9669}
9670
Eric Laurent6acd1d42017-01-04 14:23:29 -08009671void AudioFlinger::MmapThread::threadLoop_standby()
9672{
9673 mHalStream->standby();
9674}
9675
9676void AudioFlinger::MmapThread::threadLoop_exit()
9677{
Phil Burk7dce7282017-09-27 13:51:41 -07009678 // Do not call callback->onTearDown() because it is redundant for thread exit
9679 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009680}
9681
9682status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9683{
9684 return BAD_VALUE;
9685}
9686
9687bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9688{
9689 return false;
9690}
9691
9692status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9693 const effect_descriptor_t *desc, audio_session_t sessionId)
9694{
9695 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009696 if (audio_is_global_session(sessionId)) {
9697 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009698 desc->name, mThreadName);
9699 return BAD_VALUE;
9700 }
9701
9702 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9703 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9704 desc->name);
9705 return BAD_VALUE;
9706 }
9707 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009708 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9709 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009710 return BAD_VALUE;
9711 }
9712
9713 // Only allow effects without processing load or latency
9714 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9715 return BAD_VALUE;
9716 }
9717
jiabineb3bda02020-06-30 14:07:03 -07009718 if (EffectModule::isHapticGenerator(&desc->type)) {
9719 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9720 return BAD_VALUE;
9721 }
9722
Eric Laurent6acd1d42017-01-04 14:23:29 -08009723 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009724}
9725
9726void AudioFlinger::MmapThread::checkInvalidTracks_l()
9727{
9728 for (const sp<MmapTrack> &track : mActiveTracks) {
9729 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009730 sp<MmapStreamCallback> callback = mCallback.promote();
9731 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009732 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009733 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009734 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009735 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9736 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9737 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009738 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009739 }
9740 }
9741}
9742
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009743void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009744{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009745 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9746 mAttr.content_type, mAttr.usage, mAttr.source);
9747 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009748 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009749 dprintf(fd, " No active clients\n");
9750 }
9751}
9752
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009753void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009754{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009755 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009756 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009757 dprintf(fd, " %zu Tracks\n", numtracks);
9758 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009759 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009760 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009761 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009762 for (size_t i = 0; i < numtracks ; ++i) {
9763 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009764 result.append(prefix);
9765 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009766 }
9767 } else {
9768 dprintf(fd, "\n");
9769 }
9770 write(fd, result.string(), result.size());
9771}
9772
9773AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9774 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009775 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009776 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009777 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009778 mStreamVolume(1.0),
9779 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009780 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009781{
9782 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9783 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9784 mMasterVolume = audioFlinger->masterVolume_l();
9785 mMasterMute = audioFlinger->masterMute_l();
9786 if (mAudioHwDev) {
9787 if (mAudioHwDev->canSetMasterVolume()) {
9788 mMasterVolume = 1.0;
9789 }
9790
9791 if (mAudioHwDev->canSetMasterMute()) {
9792 mMasterMute = false;
9793 }
9794 }
9795}
9796
9797void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9798 audio_stream_type_t streamType,
9799 audio_session_t sessionId,
9800 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009801 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009802 audio_port_handle_t portId)
9803{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009804 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009805 mStreamType = streamType;
9806}
9807
9808AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9809{
9810 Mutex::Autolock _l(mLock);
9811 AudioStreamOut *output = mOutput;
9812 mOutput = NULL;
9813 return output;
9814}
9815
9816void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9817{
9818 Mutex::Autolock _l(mLock);
9819 // Don't apply master volume in SW if our HAL can do it for us.
9820 if (mAudioHwDev &&
9821 mAudioHwDev->canSetMasterVolume()) {
9822 mMasterVolume = 1.0;
9823 } else {
9824 mMasterVolume = value;
9825 }
9826}
9827
9828void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9829{
9830 Mutex::Autolock _l(mLock);
9831 // Don't apply master mute in SW if our HAL can do it for us.
9832 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9833 mMasterMute = false;
9834 } else {
9835 mMasterMute = muted;
9836 }
9837}
9838
9839void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9840{
9841 Mutex::Autolock _l(mLock);
9842 if (stream == mStreamType) {
9843 mStreamVolume = value;
9844 broadcast_l();
9845 }
9846}
9847
9848float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9849{
9850 Mutex::Autolock _l(mLock);
9851 if (stream == mStreamType) {
9852 return mStreamVolume;
9853 }
9854 return 0.0f;
9855}
9856
9857void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9858{
9859 Mutex::Autolock _l(mLock);
9860 if (stream == mStreamType) {
9861 mStreamMute= muted;
9862 broadcast_l();
9863 }
9864}
9865
9866void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9867{
9868 Mutex::Autolock _l(mLock);
9869 if (streamType == mStreamType) {
9870 for (const sp<MmapTrack> &track : mActiveTracks) {
9871 track->invalidate();
9872 }
9873 broadcast_l();
9874 }
9875}
9876
9877void AudioFlinger::MmapPlaybackThread::processVolume_l()
9878{
9879 float volume;
9880
9881 if (mMasterMute || mStreamMute) {
9882 volume = 0;
9883 } else {
9884 volume = mMasterVolume * mStreamVolume;
9885 }
9886
9887 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009888
9889 // Convert volumes from float to 8.24
9890 uint32_t vol = (uint32_t)(volume * (1 << 24));
9891
9892 // Delegate volume control to effect in track effect chain if needed
9893 // only one effect chain can be present on DirectOutputThread, so if
9894 // there is one, the track is connected to it
9895 if (!mEffectChains.isEmpty()) {
9896 mEffectChains[0]->setVolume_l(&vol, &vol);
9897 volume = (float)vol / (1 << 24);
9898 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009899 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009900 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9901 mHalVolFloat = volume; // HW volume control worked, so update value.
9902 mNoCallbackWarningCount = 0;
9903 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009904 sp<MmapStreamCallback> callback = mCallback.promote();
9905 if (callback != 0) {
9906 int channelCount;
9907 if (isOutput()) {
9908 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9909 } else {
9910 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9911 }
9912 Vector<float> values;
9913 for (int i = 0; i < channelCount; i++) {
9914 values.add(volume);
9915 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009916 mHalVolFloat = volume; // SW volume control worked, so update value.
9917 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009918 mLock.unlock();
9919 callback->onVolumeChanged(mChannelMask, values);
9920 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009921 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009922 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9923 ALOGW("Could not set MMAP stream volume: no volume callback!");
9924 mNoCallbackWarningCount++;
9925 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009926 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009927 }
9928 }
9929}
9930
Kevin Rocard069c2712018-03-29 19:09:14 -07009931void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9932{
9933 if (mOutput == nullptr || mOutput->stream == nullptr ||
9934 !mActiveTracks.readAndClearHasChanged()) {
9935 return;
9936 }
9937 StreamOutHalInterface::SourceMetadata metadata;
9938 for (const sp<MmapTrack> &track : mActiveTracks) {
9939 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01009940 playback_track_metadata_v7_t trackMetadata;
9941 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009942 .usage = track->attributes().usage,
9943 .content_type = track->attributes().content_type,
9944 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +01009945 };
9946 trackMetadata.channel_mask = track->channelMask(),
9947 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9948 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009949 }
9950 mOutput->stream->updateSourceMetadata(metadata);
9951}
9952
Eric Laurent6acd1d42017-01-04 14:23:29 -08009953void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9954{
9955 if (!mMasterMute) {
9956 char value[PROPERTY_VALUE_MAX];
9957 if (property_get("ro.audio.silent", value, "0") > 0) {
9958 char *endptr;
9959 unsigned long ul = strtoul(value, &endptr, 0);
9960 if (*endptr == '\0' && ul != 0) {
9961 ALOGD("Silence is golden");
9962 // The setprop command will not allow a property to be changed after
9963 // the first time it is set, so we don't have to worry about un-muting.
9964 setMasterMute_l(true);
9965 }
9966 }
9967 }
9968}
9969
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009970void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9971{
9972 MmapThread::toAudioPortConfig(config);
9973 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9974 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9975 config->flags.output = mOutput->flags;
9976 }
9977}
9978
jiabinb7d8c5a2020-08-26 17:24:52 -07009979status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
9980 int64_t *timeNanos)
9981{
9982 if (mOutput == nullptr) {
9983 return NO_INIT;
9984 }
9985 struct timespec timestamp;
9986 status_t status = mOutput->getPresentationPosition(position, &timestamp);
9987 if (status == NO_ERROR) {
9988 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
9989 }
9990 return status;
9991}
9992
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009993void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009994{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009995 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009996
Glenn Kastend3bb6452016-12-05 18:14:37 -08009997 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9998 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009999 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10000}
10001
10002AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10003 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010004 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010005 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010006 mInput(input)
10007{
10008 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10009 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10010}
10011
Eric Laurent331679c2018-04-16 17:03:16 -070010012status_t AudioFlinger::MmapCaptureThread::exitStandby()
10013{
Phil Burkf054fc32018-12-06 09:45:59 -080010014 {
10015 // mInput might have been cleared by clearInput()
10016 Mutex::Autolock _l(mLock);
10017 if (mInput != nullptr && mInput->stream != nullptr) {
10018 mInput->stream->setGain(1.0f);
10019 }
10020 }
Eric Laurent331679c2018-04-16 17:03:16 -070010021 return MmapThread::exitStandby();
10022}
10023
Eric Laurent6acd1d42017-01-04 14:23:29 -080010024AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10025{
10026 Mutex::Autolock _l(mLock);
10027 AudioStreamIn *input = mInput;
10028 mInput = NULL;
10029 return input;
10030}
Kevin Rocard069c2712018-03-29 19:09:14 -070010031
Eric Laurent331679c2018-04-16 17:03:16 -070010032
10033void AudioFlinger::MmapCaptureThread::processVolume_l()
10034{
10035 bool changed = false;
10036 bool silenced = false;
10037
10038 sp<MmapStreamCallback> callback = mCallback.promote();
10039 if (callback == 0) {
10040 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10041 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10042 mNoCallbackWarningCount++;
10043 }
10044 }
10045
10046 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10047 // track is silenced and unmute otherwise
10048 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10049 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10050 changed = true;
10051 silenced = mActiveTracks[i]->isSilenced_l();
10052 }
10053 }
10054
10055 if (changed) {
10056 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10057 }
10058}
10059
Kevin Rocard069c2712018-03-29 19:09:14 -070010060void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10061{
10062 if (mInput == nullptr || mInput->stream == nullptr ||
10063 !mActiveTracks.readAndClearHasChanged()) {
10064 return;
10065 }
10066 StreamInHalInterface::SinkMetadata metadata;
10067 for (const sp<MmapTrack> &track : mActiveTracks) {
10068 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010069 record_track_metadata_v7_t trackMetadata;
10070 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010071 .source = track->attributes().source,
10072 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010073 };
10074 trackMetadata.channel_mask = track->channelMask(),
10075 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10076 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010077 }
10078 mInput->stream->updateSinkMetadata(metadata);
10079}
10080
Eric Laurent5ada82e2019-08-29 17:53:54 -070010081void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010082{
10083 Mutex::Autolock _l(mLock);
10084 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010085 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010086 mActiveTracks[i]->setSilenced_l(silenced);
10087 broadcast_l();
10088 }
10089 }
10090}
10091
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010092void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10093{
10094 MmapThread::toAudioPortConfig(config);
10095 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10096 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10097 config->flags.input = mInput->flags;
10098 }
10099}
10100
jiabinb7d8c5a2020-08-26 17:24:52 -070010101status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10102 uint64_t *position, int64_t *timeNanos)
10103{
10104 if (mInput == nullptr) {
10105 return NO_INIT;
10106 }
10107 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10108}
10109
Glenn Kasten63238ef2015-03-02 15:50:29 -080010110} // namespace android