blob: ef92492f62e9ece8cd511e8f9d18e4bc5f794752 [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 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006118 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006119 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07006120 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006121 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006122 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006123 }
Phil Burkfdb3c072016-02-09 10:47:02 -08006124 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08006125 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006126 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006127 }
6128}
6129
Eric Laurentd1f69b02014-12-15 14:33:13 -08006130void AudioFlinger::DirectOutputThread::threadLoop_exit()
6131{
6132 {
6133 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006134 for (size_t i = 0; i < mTracks.size(); i++) {
6135 if (mTracks[i]->isFlushPending()) {
6136 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006137 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006138 }
6139 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006140 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006141 flushHw_l();
6142 }
6143 }
6144 PlaybackThread::threadLoop_exit();
6145}
6146
6147// must be called with thread mutex locked
6148bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6149{
6150 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006151 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006152
6153 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6154 // after a timeout and we will enter standby then.
6155 if (mTracks.size() > 0) {
6156 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006157 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6158 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006159 }
6160
Eric Laurent5cff4032015-05-26 13:49:58 -07006161 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006162}
6163
Eric Laurent10351942014-05-08 18:49:52 -07006164// checkForNewParameter_l() must be called with ThreadBase::mLock held
6165bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6166 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006167{
6168 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006169 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006170
Eric Laurent10351942014-05-08 18:49:52 -07006171 AudioParameter param = AudioParameter(keyValuePair);
6172 int value;
6173 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006174 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006175 }
Eric Laurent10351942014-05-08 18:49:52 -07006176 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6177 // do not accept frame count changes if tracks are open as the track buffer
6178 // size depends on frame count and correct behavior would not be garantied
6179 // if frame count is changed after track creation
6180 if (!mTracks.isEmpty()) {
6181 status = INVALID_OPERATION;
6182 } else {
6183 reconfig = true;
6184 }
6185 }
6186 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006187 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006188 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006189 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006190 if (!mStandby) {
6191 mThreadMetrics.logEndInterval();
6192 mStandby = true;
6193 }
Eric Laurent10351942014-05-08 18:49:52 -07006194 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006195 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006196 }
6197 if (status == NO_ERROR && reconfig) {
6198 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006199 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006200 }
6201 }
6202
Dean Wheatley68918102021-03-19 22:09:19 +11006203 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006204}
6205
6206uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6207{
6208 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006209 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006210 time = PlaybackThread::activeSleepTimeUs();
6211 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006212 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006213 }
6214 return time;
6215}
6216
6217uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6218{
6219 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006220 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006221 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6222 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006223 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006224 }
6225 return time;
6226}
6227
6228uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6229{
6230 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006231 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006232 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6233 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006234 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006235 }
6236 return time;
6237}
6238
6239void AudioFlinger::DirectOutputThread::cacheParameters_l()
6240{
6241 PlaybackThread::cacheParameters_l();
6242
6243 // use shorter standby delay as on normal output to release
6244 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006245 // no delay on outputs with HW A/V sync
6246 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006247 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006248 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006249 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006250 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006251 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006252 }
Eric Laurent81784c32012-11-19 14:55:58 -08006253}
6254
Eric Laurente659ef42014-09-29 13:06:46 -07006255void AudioFlinger::DirectOutputThread::flushHw_l()
6256{
Phil Burk062e67a2015-02-11 13:40:50 -08006257 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006258 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006259 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006260 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006261 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006262}
6263
Andy Hung10cbff12017-02-21 17:30:14 -08006264int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6265 // If a VolumeShaper is active, we must wake up periodically to update volume.
6266 const int64_t NS_PER_MS = 1000000;
6267 return mVolumeShaperActive ?
6268 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6269}
6270
Eric Laurent81784c32012-11-19 14:55:58 -08006271// ----------------------------------------------------------------------------
6272
Eric Laurentbfb1b832013-01-07 09:53:42 -08006273AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006274 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006275 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006276 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006277 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006278 mDrainSequence(0),
6279 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006280{
6281}
6282
6283AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6284{
6285}
6286
6287void AudioFlinger::AsyncCallbackThread::onFirstRef()
6288{
6289 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6290}
6291
6292bool AudioFlinger::AsyncCallbackThread::threadLoop()
6293{
6294 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006295 uint32_t writeAckSequence;
6296 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006297 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006298
6299 {
6300 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006301 while (!((mWriteAckSequence & 1) ||
6302 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006303 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006304 exitPending())) {
6305 mWaitWorkCV.wait(mLock);
6306 }
6307
Eric Laurentbfb1b832013-01-07 09:53:42 -08006308 if (exitPending()) {
6309 break;
6310 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006311 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6312 mWriteAckSequence, mDrainSequence);
6313 writeAckSequence = mWriteAckSequence;
6314 mWriteAckSequence &= ~1;
6315 drainSequence = mDrainSequence;
6316 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006317 asyncError = mAsyncError;
6318 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006319 }
6320 {
Eric Laurent4de95592013-09-26 15:28:21 -07006321 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6322 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006323 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006324 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006325 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006326 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006327 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006328 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006329 if (asyncError) {
6330 playbackThread->onAsyncError();
6331 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006332 }
6333 }
6334 }
6335 return false;
6336}
6337
6338void AudioFlinger::AsyncCallbackThread::exit()
6339{
6340 ALOGV("AsyncCallbackThread::exit");
6341 Mutex::Autolock _l(mLock);
6342 requestExit();
6343 mWaitWorkCV.broadcast();
6344}
6345
Eric Laurent3b4529e2013-09-05 18:09:19 -07006346void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006347{
6348 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006349 // bit 0 is cleared
6350 mWriteAckSequence = sequence << 1;
6351}
6352
6353void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6354{
6355 Mutex::Autolock _l(mLock);
6356 // ignore unexpected callbacks
6357 if (mWriteAckSequence & 2) {
6358 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006359 mWaitWorkCV.signal();
6360 }
6361}
6362
Eric Laurent3b4529e2013-09-05 18:09:19 -07006363void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006364{
6365 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006366 // bit 0 is cleared
6367 mDrainSequence = sequence << 1;
6368}
6369
6370void AudioFlinger::AsyncCallbackThread::resetDraining()
6371{
6372 Mutex::Autolock _l(mLock);
6373 // ignore unexpected callbacks
6374 if (mDrainSequence & 2) {
6375 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006376 mWaitWorkCV.signal();
6377 }
6378}
6379
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006380void AudioFlinger::AsyncCallbackThread::setAsyncError()
6381{
6382 Mutex::Autolock _l(mLock);
6383 mAsyncError = true;
6384 mWaitWorkCV.signal();
6385}
6386
Eric Laurentbfb1b832013-01-07 09:53:42 -08006387
6388// ----------------------------------------------------------------------------
6389AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006390 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6391 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006392 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6393 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006394{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006395 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006396 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006397 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006398}
6399
Eric Laurentbfb1b832013-01-07 09:53:42 -08006400void AudioFlinger::OffloadThread::threadLoop_exit()
6401{
6402 if (mFlushPending || mHwPaused) {
6403 // If a flush is pending or track was paused, just discard buffered data
6404 flushHw_l();
6405 } else {
6406 mMixerStatus = MIXER_DRAIN_ALL;
6407 threadLoop_drain();
6408 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006409 if (mUseAsyncWrite) {
6410 ALOG_ASSERT(mCallbackThread != 0);
6411 mCallbackThread->exit();
6412 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006413 PlaybackThread::threadLoop_exit();
6414}
6415
6416AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6417 Vector< sp<Track> > *tracksToRemove
6418)
6419{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006420 size_t count = mActiveTracks.size();
6421
6422 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006423 bool doHwPause = false;
6424 bool doHwResume = false;
6425
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006426 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006427
Eric Laurentbfb1b832013-01-07 09:53:42 -08006428 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006429 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006430 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006431#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006432 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006433#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006434 // Only consider last track started for volume and mixer state control.
6435 // In theory an older track could underrun and restart after the new one starts
6436 // but as we only care about the transition phase between two tracks on a
6437 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006438 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006439 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006440
Haynes Mathew George7844f672014-01-15 12:32:55 -08006441 if (track->isInvalid()) {
6442 ALOGW("An invalidated track shouldn't be in active list");
6443 tracksToRemove->add(track);
6444 continue;
6445 }
6446
6447 if (track->mState == TrackBase::IDLE) {
6448 ALOGW("An idle track shouldn't be in active list");
6449 continue;
6450 }
6451
Kuowei Li23666472021-01-20 10:23:25 +08006452 if (track->isPausePending()) {
6453 track->pauseAck();
6454 // It is possible a track might have been flushed or stopped.
6455 // Other operations such as flush pending might occur on the next prepare.
6456 if (track->isPausing()) {
6457 track->setPaused();
6458 }
6459 // Always perform pause if last, as an immediate flush will change
6460 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006461 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006462 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006463 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006464 mHwPaused = true;
6465 }
6466 // If we were part way through writing the mixbuffer to
6467 // the HAL we must save this until we resume
6468 // BUG - this will be wrong if a different track is made active,
6469 // in that case we want to discard the pending data in the
6470 // mixbuffer and tell the client to present it again when the
6471 // track is resumed
6472 mPausedWriteLength = mCurrentWriteLength;
6473 mPausedBytesRemaining = mBytesRemaining;
6474 mBytesRemaining = 0; // stop writing
6475 }
6476 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006477 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006478 if (track->isStopping_1()) {
6479 track->mRetryCount = kMaxTrackStopRetriesOffload;
6480 } else {
6481 track->mRetryCount = kMaxTrackRetriesOffload;
6482 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006483 track->flushAck();
6484 if (last) {
6485 mFlushPending = true;
6486 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006487 } else if (track->isResumePending()){
6488 track->resumeAck();
6489 if (last) {
6490 if (mPausedBytesRemaining) {
6491 // Need to continue write that was interrupted
6492 mCurrentWriteLength = mPausedWriteLength;
6493 mBytesRemaining = mPausedBytesRemaining;
6494 mPausedBytesRemaining = 0;
6495 }
6496 if (mHwPaused) {
6497 doHwResume = true;
6498 mHwPaused = false;
6499 // threadLoop_mix() will handle the case that we need to
6500 // resume an interrupted write
6501 }
6502 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006503 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006504
Eric Laurent3df841a2016-07-15 15:15:40 -07006505 mLeftVolFloat = mRightVolFloat = -1.0;
6506
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006507 // Do not handle new data in this iteration even if track->framesReady()
6508 mixerStatus = MIXER_TRACKS_ENABLED;
6509 }
6510 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006511 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006512 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006513 if (track->mFillingUpStatus == Track::FS_FILLED) {
6514 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006515 if (last) {
6516 // make sure processVolume_l() will apply new volume even if 0
6517 mLeftVolFloat = mRightVolFloat = -1.0;
6518 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006519 }
6520
6521 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006522 sp<Track> previousTrack = mPreviousTrack.promote();
6523 if (previousTrack != 0) {
6524 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006525 // Flush any data still being written from last track
6526 mBytesRemaining = 0;
6527 if (mPausedBytesRemaining) {
6528 // Last track was paused so we also need to flush saved
6529 // mixbuffer state and invalidate track so that it will
6530 // re-submit that unwritten data when it is next resumed
6531 mPausedBytesRemaining = 0;
6532 // Invalidate is a bit drastic - would be more efficient
6533 // to have a flag to tell client that some of the
6534 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006535 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006536 }
6537 // flush data already sent to the DSP if changing audio session as audio
6538 // comes from a different source. Also invalidate previous track to force a
6539 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006540 if (previousTrack->sessionId() != track->sessionId()) {
6541 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006542 }
6543 }
6544 }
6545 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006546 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006547 if (track->isStopping_1()) {
6548 track->mRetryCount = kMaxTrackStopRetriesOffload;
6549 } else {
6550 track->mRetryCount = kMaxTrackRetriesOffload;
6551 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006552 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006553 mixerStatus = MIXER_TRACKS_READY;
6554 }
6555 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006556 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006557 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006558 if (--(track->mRetryCount) <= 0) {
6559 // Hardware buffer can hold a large amount of audio so we must
6560 // wait for all current track's data to drain before we say
6561 // that the track is stopped.
6562 if (mBytesRemaining == 0) {
6563 // Only start draining when all data in mixbuffer
6564 // has been written
6565 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6566 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6567 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6568 if (last && !mStandby) {
6569 // do not modify drain sequence if we are already draining. This happens
6570 // when resuming from pause after drain.
6571 if ((mDrainSequence & 1) == 0) {
6572 mSleepTimeUs = 0;
6573 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6574 mixerStatus = MIXER_DRAIN_TRACK;
6575 mDrainSequence += 2;
6576 }
6577 if (mHwPaused) {
6578 // It is possible to move from PAUSED to STOPPING_1 without
6579 // a resume so we must ensure hardware is running
6580 doHwResume = true;
6581 mHwPaused = false;
6582 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006583 }
6584 }
Eric Laurente93cc032016-05-05 10:15:10 -07006585 } else if (last) {
6586 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6587 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006588 }
6589 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006590 // Drain has completed or we are in standby, signal presentation complete
6591 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006592 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006593 uint32_t latency = 0;
6594 status_t result = mOutput->stream->getLatency(&latency);
6595 ALOGE_IF(result != OK,
6596 "Error when retrieving output stream latency: %d", result);
6597 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006598 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006599 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006600 track->presentationComplete(framesWritten, audioHALFrames);
6601 track->reset();
6602 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006603 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006604 if (!mUseAsyncWrite) {
6605 // If we don't get explicit drain notification we must
6606 // register discontinuity regardless of whether this is
6607 // the previous (!last) or the upcoming (last) track
6608 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006609 mTimestampVerifier.discontinuity(
6610 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006611 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006612 }
6613 } else {
6614 // No buffers for this track. Give it a few chances to
6615 // fill a buffer, then remove it from active list.
6616 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006617 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006618 uint64_t position = 0;
6619 struct timespec unused;
6620 // The running check restarts the retry counter at least once.
6621 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6622 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6623 running = true;
6624 mOffloadUnderrunPosition = position;
6625 }
6626 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006627 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6628 (long long)position, (long long)mOffloadUnderrunPosition);
6629 }
6630 if (running) { // still running, give us more time.
6631 track->mRetryCount = kMaxTrackRetriesOffload;
6632 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006633 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6634 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006635 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006636 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006637 // it will then automatically call start() when data is available
6638 track->disable();
6639 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006640 } else if (last){
6641 mixerStatus = MIXER_TRACKS_ENABLED;
6642 }
6643 }
6644 }
6645 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006646 if (track->isReady()) { // check ready to prevent premature start.
6647 processVolume_l(track, last);
6648 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006649 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006650
Eric Laurentea0fade2013-10-04 16:23:48 -07006651 // make sure the pause/flush/resume sequence is executed in the right order.
6652 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6653 // before flush and then resume HW. This can happen in case of pause/flush/resume
6654 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006655 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006656 status_t result = mOutput->stream->pause();
6657 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006658 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006659 if (mFlushPending) {
6660 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006661 }
Eric Laurentfd477972013-10-25 18:10:40 -07006662 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006663 status_t result = mOutput->stream->resume();
6664 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006665 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006666
Eric Laurentbfb1b832013-01-07 09:53:42 -08006667 // remove all the tracks that need to be...
6668 removeTracks_l(*tracksToRemove);
6669
6670 return mixerStatus;
6671}
6672
Eric Laurentbfb1b832013-01-07 09:53:42 -08006673// must be called with thread mutex locked
6674bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6675{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006676 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6677 mWriteAckSequence, mDrainSequence);
6678 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006679 return true;
6680 }
6681 return false;
6682}
6683
Eric Laurentbfb1b832013-01-07 09:53:42 -08006684bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6685{
6686 Mutex::Autolock _l(mLock);
6687 return waitingAsyncCallback_l();
6688}
6689
6690void AudioFlinger::OffloadThread::flushHw_l()
6691{
Eric Laurente659ef42014-09-29 13:06:46 -07006692 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006693 // Flush anything still waiting in the mixbuffer
6694 mCurrentWriteLength = 0;
6695 mBytesRemaining = 0;
6696 mPausedWriteLength = 0;
6697 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006698 // reset bytes written count to reflect that DSP buffers are empty after flush.
6699 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006700 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006701
Eric Laurentbfb1b832013-01-07 09:53:42 -08006702 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006703 // discard any pending drain or write ack by incrementing sequence
6704 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6705 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006706 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006707 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6708 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006709 }
6710}
6711
Haynes Mathew George05317d22016-05-03 16:34:26 -07006712void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6713{
6714 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006715 if (PlaybackThread::invalidateTracks_l(streamType)) {
6716 mFlushPending = true;
6717 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006718}
6719
Eric Laurentbfb1b832013-01-07 09:53:42 -08006720// ----------------------------------------------------------------------------
6721
Eric Laurent81784c32012-11-19 14:55:58 -08006722AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006723 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006724 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006725 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006726 mWaitTimeMs(UINT_MAX)
6727{
6728 addOutputTrack(mainThread);
6729}
6730
6731AudioFlinger::DuplicatingThread::~DuplicatingThread()
6732{
6733 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6734 mOutputTracks[i]->destroy();
6735 }
6736}
6737
6738void AudioFlinger::DuplicatingThread::threadLoop_mix()
6739{
6740 // mix buffers...
6741 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006742 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006743 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006744 if (mMixerBufferValid) {
6745 memset(mMixerBuffer, 0, mMixerBufferSize);
6746 } else {
6747 memset(mSinkBuffer, 0, mSinkBufferSize);
6748 }
Eric Laurent81784c32012-11-19 14:55:58 -08006749 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006750 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006751 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006752 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006753 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006754}
6755
6756void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6757{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006758 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006759 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006760 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006761 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006762 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006763 }
6764 } else if (mBytesWritten != 0) {
6765 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6766 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006767 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006768 } else {
6769 // flush remaining overflow buffers in output tracks
6770 writeFrames = 0;
6771 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006772 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006773 }
6774}
6775
Eric Laurentbfb1b832013-01-07 09:53:42 -08006776ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006777{
6778 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006779 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6780
6781 // Consider the first OutputTrack for timestamp and frame counting.
6782
6783 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6784 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6785 // we always claim success.
6786 if (i == 0) {
6787 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6788 ALOGD_IF(correction != 0 && writeFrames != 0,
6789 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6790 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6791 mFramesWritten -= correction;
6792 }
6793
6794 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006795 }
Andy Hungcf10d742020-04-28 15:38:24 -07006796 if (mStandby) {
6797 mThreadMetrics.logBeginInterval();
6798 mStandby = false;
6799 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006800 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006801}
6802
6803void AudioFlinger::DuplicatingThread::threadLoop_standby()
6804{
6805 // DuplicatingThread implements standby by stopping all tracks
6806 for (size_t i = 0; i < outputTracks.size(); i++) {
6807 outputTracks[i]->stop();
6808 }
6809}
6810
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006811void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006812{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006813 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006814
6815 std::stringstream ss;
6816 const size_t numTracks = mOutputTracks.size();
6817 ss << " " << numTracks << " OutputTracks";
6818 if (numTracks > 0) {
6819 ss << ":";
6820 for (const auto &track : mOutputTracks) {
6821 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006822 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006823 if (thread.get() != nullptr) {
6824 ss << thread.get() << ", " << thread->id();
6825 } else {
6826 ss << "null";
6827 }
6828 ss << ")";
6829 }
6830 }
6831 ss << "\n";
6832 std::string result = ss.str();
6833 write(fd, result.c_str(), result.size());
6834}
6835
Eric Laurent81784c32012-11-19 14:55:58 -08006836void AudioFlinger::DuplicatingThread::saveOutputTracks()
6837{
6838 outputTracks = mOutputTracks;
6839}
6840
6841void AudioFlinger::DuplicatingThread::clearOutputTracks()
6842{
6843 outputTracks.clear();
6844}
6845
6846void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6847{
6848 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006849 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6850 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6851 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6852 const size_t frameCount =
6853 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6854 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6855 // from different OutputTracks and their associated MixerThreads (e.g. one may
6856 // nearly empty and the other may be dropping data).
6857
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006858 // TODO b/182392769: use identity util, move to server edge
6859 Identity identity = Identity();
6860 identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
6861 IPCThreadState::self()->getCallingUid()));
6862 identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
6863 IPCThreadState::self()->getCallingPid()));
Andy Hungc25b84a2015-01-14 19:04:10 -08006864 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006865 this,
6866 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006867 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006868 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006869 frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006870 identity);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006871 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6872 if (status != NO_ERROR) {
6873 ALOGE("addOutputTrack() initCheck failed %d", status);
6874 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006875 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006876 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6877 mOutputTracks.add(outputTrack);
6878 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6879 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006880}
6881
6882void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6883{
6884 Mutex::Autolock _l(mLock);
6885 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6886 if (mOutputTracks[i]->thread() == thread) {
6887 mOutputTracks[i]->destroy();
6888 mOutputTracks.removeAt(i);
6889 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006890 if (thread->getOutput() == mOutput) {
6891 mOutput = NULL;
6892 }
Eric Laurent81784c32012-11-19 14:55:58 -08006893 return;
6894 }
6895 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006896 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006897}
6898
6899// caller must hold mLock
6900void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6901{
6902 mWaitTimeMs = UINT_MAX;
6903 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6904 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6905 if (strong != 0) {
6906 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6907 if (waitTimeMs < mWaitTimeMs) {
6908 mWaitTimeMs = waitTimeMs;
6909 }
6910 }
6911 }
6912}
6913
6914
6915bool AudioFlinger::DuplicatingThread::outputsReady(
6916 const SortedVector< sp<OutputTrack> > &outputTracks)
6917{
6918 for (size_t i = 0; i < outputTracks.size(); i++) {
6919 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6920 if (thread == 0) {
6921 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6922 outputTracks[i].get());
6923 return false;
6924 }
6925 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6926 // see note at standby() declaration
6927 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6928 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6929 thread.get());
6930 return false;
6931 }
6932 }
6933 return true;
6934}
6935
Kevin Rocard12381092018-04-11 09:19:59 -07006936void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6937 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006938{
Kevin Rocard12381092018-04-11 09:19:59 -07006939 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6940 outputTrack->setMetadatas(metadata.tracks);
6941 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006942}
6943
Eric Laurent81784c32012-11-19 14:55:58 -08006944uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6945{
6946 return (mWaitTimeMs * 1000) / 2;
6947}
6948
6949void AudioFlinger::DuplicatingThread::cacheParameters_l()
6950{
6951 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6952 updateWaitTime_l();
6953
6954 MixerThread::cacheParameters_l();
6955}
6956
Eric Laurent6acd1d42017-01-04 14:23:29 -08006957
Eric Laurent81784c32012-11-19 14:55:58 -08006958// ----------------------------------------------------------------------------
6959// Record
6960// ----------------------------------------------------------------------------
6961
6962AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6963 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006964 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006965 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006966 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006967 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006968 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006969 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006970 mActiveTracks(&this->mLocalLog),
6971 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006972 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006973 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006974 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6975 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006976 // mFastCapture below
6977 , mFastCaptureFutex(0)
6978 // mInputSource
6979 // mPipeSink
6980 // mPipeSource
6981 , mPipeFramesP2(0)
6982 // mPipeMemory
6983 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006984 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006985 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006986{
Glenn Kastend7dca052015-03-05 16:05:54 -08006987 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6988 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006989
George Burgess IVa8f90c12020-05-14 11:27:19 -07006990 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07006991 mIsMsdDevice = strcmp(
6992 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6993 }
6994
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006995 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006996
Andy Hungc8fddf32018-08-08 18:32:37 -07006997 // TODO: We may also match on address as well as device type for
6998 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07006999 // TODO: This property should be ensure that only contains one single device type.
7000 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7001 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007002 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7003 : AUDIO_DEVICE_NONE));
7004
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007005 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007006 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007007 size_t numCounterOffers = 0;
7008 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007009#if !LOG_NDEBUG
7010 ssize_t index =
7011#else
7012 (void)
7013#endif
7014 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007015 ALOG_ASSERT(index == 0);
7016
7017 // initialize fast capture depending on configuration
7018 bool initFastCapture;
7019 switch (kUseFastCapture) {
7020 case FastCapture_Never:
7021 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007022 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007023 break;
7024 case FastCapture_Always:
7025 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007026 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007027 break;
7028 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007029 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007030 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7031 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7032 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007033 break;
7034 // case FastCapture_Dynamic:
7035 }
7036
7037 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007038 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007039 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007040 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7041 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007042 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007043 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007044 const sp<MemoryDealer> roHeap(readOnlyHeap());
7045 sp<IMemory> pipeMemory;
7046 if ((roHeap == 0) ||
7047 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007048 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007049 ALOGE("not enough memory for pipe buffer size=%zu; "
7050 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7051 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7052 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007053 goto failed;
7054 }
7055 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7056 memset(pipeBuffer, 0, pipeSize);
7057 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7058 const NBAIO_Format offers[1] = {format};
7059 size_t numCounterOffers = 0;
7060 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7061 ALOG_ASSERT(index == 0);
7062 mPipeSink = pipe;
7063 PipeReader *pipeReader = new PipeReader(*pipe);
7064 numCounterOffers = 0;
7065 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7066 ALOG_ASSERT(index == 0);
7067 mPipeSource = pipeReader;
7068 mPipeFramesP2 = pipeFramesP2;
7069 mPipeMemory = pipeMemory;
7070
7071 // create fast capture
7072 mFastCapture = new FastCapture();
7073 FastCaptureStateQueue *sq = mFastCapture->sq();
7074#ifdef STATE_QUEUE_DUMP
7075 // FIXME
7076#endif
7077 FastCaptureState *state = sq->begin();
7078 state->mCblk = NULL;
7079 state->mInputSource = mInputSource.get();
7080 state->mInputSourceGen++;
7081 state->mPipeSink = pipe;
7082 state->mPipeSinkGen++;
7083 state->mFrameCount = mFrameCount;
7084 state->mCommand = FastCaptureState::COLD_IDLE;
7085 // already done in constructor initialization list
7086 //mFastCaptureFutex = 0;
7087 state->mColdFutexAddr = &mFastCaptureFutex;
7088 state->mColdGen++;
7089 state->mDumpState = &mFastCaptureDumpState;
7090#ifdef TEE_SINK
7091 // FIXME
7092#endif
7093 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7094 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7095 sq->end();
7096 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7097
7098 // start the fast capture
7099 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7100 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007101 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007102 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007103#ifdef AUDIO_WATCHDOG
7104 // FIXME
7105#endif
7106
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007107 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007108 }
Andy Hung8946a282018-04-19 20:04:56 -07007109#ifdef TEE_SINK
7110 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7111 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7112#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007113failed: ;
7114
7115 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007116}
7117
Eric Laurent81784c32012-11-19 14:55:58 -08007118AudioFlinger::RecordThread::~RecordThread()
7119{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007120 if (mFastCapture != 0) {
7121 FastCaptureStateQueue *sq = mFastCapture->sq();
7122 FastCaptureState *state = sq->begin();
7123 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7124 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7125 if (old == -1) {
7126 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7127 }
7128 }
7129 state->mCommand = FastCaptureState::EXIT;
7130 sq->end();
7131 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7132 mFastCapture->join();
7133 mFastCapture.clear();
7134 }
7135 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007136 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007137 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007138}
7139
7140void AudioFlinger::RecordThread::onFirstRef()
7141{
Glenn Kastend7dca052015-03-05 16:05:54 -08007142 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007143}
7144
Eric Laurent555530a2017-02-07 18:17:24 -08007145void AudioFlinger::RecordThread::preExit()
7146{
7147 ALOGV(" preExit()");
7148 Mutex::Autolock _l(mLock);
7149 for (size_t i = 0; i < mTracks.size(); i++) {
7150 sp<RecordTrack> track = mTracks[i];
7151 track->invalidate();
7152 }
7153 mActiveTracks.clear();
7154 mStartStopCond.broadcast();
7155}
7156
Eric Laurent81784c32012-11-19 14:55:58 -08007157bool AudioFlinger::RecordThread::threadLoop()
7158{
Eric Laurent81784c32012-11-19 14:55:58 -08007159 nsecs_t lastWarning = 0;
7160
7161 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007162
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007163reacquire_wakelock:
7164 sp<RecordTrack> activeTrack;
7165 {
7166 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007167 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007168 }
7169
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007170 // used to request a deferred sleep, to be executed later while mutex is unlocked
7171 uint32_t sleepUs = 0;
7172
Andy Hung446f4df2019-02-21 12:26:41 -08007173 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7174
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007175 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007176 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007177 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007178
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007179 // activeTracks accumulates a copy of a subset of mActiveTracks
7180 Vector< sp<RecordTrack> > activeTracks;
7181
Glenn Kasten735f45f2014-08-18 15:51:59 -07007182 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007183 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007184
Glenn Kasten735f45f2014-08-18 15:51:59 -07007185 // reference to a fast track which is about to be removed
7186 sp<RecordTrack> fastTrackToRemove;
7187
Eric Laurent33403f02020-05-29 18:35:06 -07007188 bool silenceFastCapture = false;
7189
Eric Laurent81784c32012-11-19 14:55:58 -08007190 { // scope for mLock
7191 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007192
Eric Laurent021cf962014-05-13 10:18:14 -07007193 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007194
Eric Laurent000a4192014-01-29 15:17:32 -08007195 // check exitPending here because checkForNewParameters_l() and
7196 // checkForNewParameters_l() can temporarily release mLock
7197 if (exitPending()) {
7198 break;
7199 }
7200
Eric Laurent5c25d562016-07-13 17:17:45 -07007201 // sleep with mutex unlocked
7202 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007203 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007204 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7205 ATRACE_END();
7206 sleepUs = 0;
7207 continue;
7208 }
7209
Glenn Kasten2b806402013-11-20 16:37:38 -08007210 // if no active track(s), then standby and release wakelock
7211 size_t size = mActiveTracks.size();
7212 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007213 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007214 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007215 releaseWakeLock_l();
7216 ALOGV("RecordThread: loop stopping");
7217 // go to sleep
7218 mWaitWorkCV.wait(mLock);
7219 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007220 goto reacquire_wakelock;
7221 }
7222
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007223 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007224 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007225 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007226
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007227 activeTrack = mActiveTracks[i];
7228 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007229 if (activeTrack->isFastTrack()) {
7230 ALOG_ASSERT(fastTrackToRemove == 0);
7231 fastTrackToRemove = activeTrack;
7232 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007233 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007234 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007235 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007236 continue;
7237 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007238
7239 TrackBase::track_state activeTrackState = activeTrack->mState;
7240 switch (activeTrackState) {
7241
7242 case TrackBase::PAUSING:
7243 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007244 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007245 doBroadcast = true;
7246 size--;
7247 continue;
7248
7249 case TrackBase::STARTING_1:
7250 sleepUs = 10000;
7251 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007252 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007253 continue;
7254
7255 case TrackBase::STARTING_2:
7256 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007257 if (mStandby) {
7258 mThreadMetrics.logBeginInterval();
7259 mStandby = false;
7260 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007261 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007262 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007263 break;
7264
7265 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007266 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007267 break;
7268
Andy Hungce685402018-10-05 17:23:27 -07007269 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7270 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7271 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007272 default:
Andy Hungce685402018-10-05 17:23:27 -07007273 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7274 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007275 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007276
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007277 if (activeTrack->isFastTrack()) {
7278 ALOG_ASSERT(!mFastTrackAvail);
7279 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007280 // if the active fast track is silenced either:
7281 // 1) silence the whole capture from fast capture buffer if this is
7282 // the only active track
7283 // 2) invalidate this track: this will cause the client to reconnect and possibly
7284 // be invalidated again until unsilenced
7285 if (activeTrack->isSilenced()) {
7286 if (size > 1) {
7287 activeTrack->invalidate();
7288 ALOG_ASSERT(fastTrackToRemove == 0);
7289 fastTrackToRemove = activeTrack;
7290 removeTrack_l(activeTrack);
7291 mActiveTracks.remove(activeTrack);
7292 size--;
7293 continue;
7294 } else {
7295 silenceFastCapture = true;
7296 }
7297 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007298 fastTrack = activeTrack;
7299 }
Eric Laurent33403f02020-05-29 18:35:06 -07007300
7301 activeTracks.add(activeTrack);
7302 i++;
7303
Glenn Kasten9e982352013-08-14 14:39:50 -07007304 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007305
Andy Hungdae27702016-10-31 14:01:16 -07007306 mActiveTracks.updatePowerState(this);
7307
Kevin Rocard069c2712018-03-29 19:09:14 -07007308 updateMetadata_l();
7309
Eric Laurent5c25d562016-07-13 17:17:45 -07007310 if (allStopped) {
7311 standbyIfNotAlreadyInStandby();
7312 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007313 if (doBroadcast) {
7314 mStartStopCond.broadcast();
7315 }
7316
7317 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007318 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007319 if (sleepUs == 0) {
7320 sleepUs = kRecordThreadSleepUs;
7321 }
7322 continue;
7323 }
7324 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007325
Eric Laurent81784c32012-11-19 14:55:58 -08007326 lockEffectChains_l(effectChains);
7327 }
7328
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007329 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007330
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007331 size_t size = effectChains.size();
7332 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007333 // thread mutex is not locked, but effect chain is locked
7334 effectChains[i]->process_l();
7335 }
7336
Glenn Kasten735f45f2014-08-18 15:51:59 -07007337 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007338 if (mFastCapture != 0) {
7339 FastCaptureStateQueue *sq = mFastCapture->sq();
7340 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007341 bool didModify = false;
7342 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007343 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7344 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7345 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7346 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7347 if (old == -1) {
7348 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7349 }
7350 }
7351 state->mCommand = FastCaptureState::READ_WRITE;
7352#if 0 // FIXME
7353 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007354 FastThreadDumpState::kSamplingNforLowRamDevice :
7355 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007356#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007357 didModify = true;
7358 }
7359 audio_track_cblk_t *cblkOld = state->mCblk;
7360 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7361 if (cblkNew != cblkOld) {
7362 state->mCblk = cblkNew;
7363 // block until acked if removing a fast track
7364 if (cblkOld != NULL) {
7365 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7366 }
7367 didModify = true;
7368 }
jiabin01c8f562018-07-19 17:47:28 -07007369 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7370 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7371 if (state->mFastPatchRecordBufferProvider != abp) {
7372 state->mFastPatchRecordBufferProvider = abp;
7373 state->mFastPatchRecordFormat = fastTrack == 0 ?
7374 AUDIO_FORMAT_INVALID : fastTrack->format();
7375 didModify = true;
7376 }
Eric Laurent33403f02020-05-29 18:35:06 -07007377 if (state->mSilenceCapture != silenceFastCapture) {
7378 state->mSilenceCapture = silenceFastCapture;
7379 didModify = true;
7380 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007381 sq->end(didModify);
7382 if (didModify) {
7383 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007384#if 0
7385 if (kUseFastCapture == FastCapture_Dynamic) {
7386 mNormalSource = mPipeSource;
7387 }
7388#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007389 }
7390 }
7391
Glenn Kasten735f45f2014-08-18 15:51:59 -07007392 // now run the fast track destructor with thread mutex unlocked
7393 fastTrackToRemove.clear();
7394
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007395 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7396 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7397 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7398 // If destination is non-contiguous, first read past the nominal end of buffer, then
7399 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007400
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007401 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007402 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007403 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007404
7405 // If an NBAIO source is present, use it to read the normal capture's data
7406 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007407 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007408
7409 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7410 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7411 // we immediately retry the read() to get data and prevent another overflow.
7412 for (int retries = 0; retries <= 2; ++retries) {
7413 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7414 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7415 framesToRead);
7416 if (framesRead != OVERRUN) break;
7417 }
7418
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007419 const ssize_t availableToRead = mPipeSource->availableToRead();
7420 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007421 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007422 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7423 "more frames to read than fifo size, %zd > %zu",
7424 availableToRead, mPipeFramesP2);
7425 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7426 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7427 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7428 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007429 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7430 }
7431 if (framesRead < 0) {
7432 status_t status = (status_t) framesRead;
7433 switch (status) {
7434 case OVERRUN:
7435 ALOGW("overrun on read from pipe");
7436 framesRead = 0;
7437 break;
7438 case NEGOTIATE:
7439 ALOGE("re-negotiation is needed");
7440 framesRead = -1; // Will cause an attempt to recover.
7441 break;
7442 default:
7443 ALOGE("unknown error %d on read from pipe", status);
7444 break;
7445 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007446 }
7447 // otherwise use the HAL / AudioStreamIn directly
7448 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007449 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007450 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007451 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007452 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007453 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007454 if (result < 0) {
7455 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007456 } else {
7457 framesRead = bytesRead / mFrameSize;
7458 }
7459 }
7460
Andy Hung446f4df2019-02-21 12:26:41 -08007461 const int64_t lastIoEndNs = systemTime(); // end IO timing
7462
Andy Hung3f0c9022016-01-15 17:49:46 -08007463 // Update server timestamp with server stats
7464 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007465 if (framesRead >= 0) {
7466 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7467 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7468 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007469
7470 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007471 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007472 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007473 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007474 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7475 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7476 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007477 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007478 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7479
7480 mTimestampVerifier.add(position, time, mSampleRate);
7481
7482 // Correct timestamps
7483 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007484 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007485 id(), (long long)time, (long long)position);
7486 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7487 position = correctedTimestamp.mFrames;
7488 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007489 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007490 id(), (long long)time, (long long)position);
7491 }
7492
Andy Hung3f0c9022016-01-15 17:49:46 -08007493 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7494 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7495 // Note: In general record buffers should tend to be empty in
7496 // a properly running pipeline.
7497 //
7498 // Also, it is not advantageous to call get_presentation_position during the read
7499 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007500 } else {
7501 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007502 }
7503 }
Andy Hunge6c37112019-02-26 17:38:10 -08007504
7505 // From the timestamp, input read latency is negative output write latency.
7506 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7507 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7508 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7509 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7510 mLatencyMs.add(latencyMs);
7511 }
7512
Andy Hung3f0c9022016-01-15 17:49:46 -08007513 // Use this to track timestamp information
7514 // ALOGD("%s", mTimestamp.toString().c_str());
7515
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007516 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007517 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007518 // Force input into standby so that it tries to recover at next read attempt
7519 inputStandBy();
7520 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007521 }
7522 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007523 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007524 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007525 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007526 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007527
Andy Hung8946a282018-04-19 20:04:56 -07007528#ifdef TEE_SINK
7529 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7530#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007531 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007532 {
7533 size_t part1 = mRsmpInFramesP2 - rear;
7534 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007535 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007536 (framesRead - part1) * mFrameSize);
7537 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007538 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007539 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007540
7541 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007542
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007543 // loop over each active track
7544 for (size_t i = 0; i < size; i++) {
7545 activeTrack = activeTracks[i];
7546
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007547 // skip fast tracks, as those are handled directly by FastCapture
7548 if (activeTrack->isFastTrack()) {
7549 continue;
7550 }
7551
Andy Hung73c02e42015-03-29 01:13:58 -07007552 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007553 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7554
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007555 enum {
7556 OVERRUN_UNKNOWN,
7557 OVERRUN_TRUE,
7558 OVERRUN_FALSE
7559 } overrun = OVERRUN_UNKNOWN;
7560
7561 // loop over getNextBuffer to handle circular sink
7562 for (;;) {
7563
7564 activeTrack->mSink.frameCount = ~0;
7565 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7566 size_t framesOut = activeTrack->mSink.frameCount;
7567 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7568
Andy Hung73c02e42015-03-29 01:13:58 -07007569 // check available frames and handle overrun conditions
7570 // if the record track isn't draining fast enough.
7571 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007572 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007573 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7574 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007575 overrun = OVERRUN_TRUE;
7576 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007577 if (framesOut == 0 || framesIn == 0) {
7578 break;
7579 }
7580
Andy Hung6770c6f2015-04-07 13:43:36 -07007581 // Don't allow framesOut to be larger than what is possible with resampling
7582 // from framesIn.
7583 // This isn't strictly necessary but helps limit buffer resizing in
7584 // RecordBufferConverter. TODO: remove when no longer needed.
7585 framesOut = min(framesOut,
7586 destinationFramesPossible(
7587 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007588
7589 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007590 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007591 // straight from RecordThread buffer to RecordTrack buffer.
7592 AudioBufferProvider::Buffer buffer;
7593 buffer.frameCount = framesOut;
7594 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7595 if (status == OK && buffer.frameCount != 0) {
7596 ALOGV_IF(buffer.frameCount != framesOut,
7597 "%s() read less than expected (%zu vs %zu)",
7598 __func__, buffer.frameCount, framesOut);
7599 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007600 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007601 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7602 } else {
7603 framesOut = 0;
7604 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7605 __func__, status, buffer.frameCount);
7606 }
7607 } else {
7608 // process frames from the RecordThread buffer provider to the RecordTrack
7609 // buffer
7610 framesOut = activeTrack->mRecordBufferConverter->convert(
7611 activeTrack->mSink.raw,
7612 activeTrack->mResamplerBufferProvider,
7613 framesOut);
7614 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007615
7616 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7617 overrun = OVERRUN_FALSE;
7618 }
7619
7620 if (activeTrack->mFramesToDrop == 0) {
7621 if (framesOut > 0) {
7622 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007623 // Sanitize before releasing if the track has no access to the source data
7624 // An idle UID receives silence from non virtual devices until active
7625 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007626 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007627 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007628 activeTrack->releaseBuffer(&activeTrack->mSink);
7629 }
7630 } else {
7631 // FIXME could do a partial drop of framesOut
7632 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007633 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007634 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007635 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007636 }
7637 } else {
7638 activeTrack->mFramesToDrop += framesOut;
7639 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7640 activeTrack->mSyncStartEvent->isCancelled()) {
7641 ALOGW("Synced record %s, session %d, trigger session %d",
7642 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7643 activeTrack->sessionId(),
7644 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007645 activeTrack->mSyncStartEvent->triggerSession() :
7646 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007647 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007648 }
7649 }
7650 }
7651
7652 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007653 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007654 }
7655 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007656
7657 switch (overrun) {
7658 case OVERRUN_TRUE:
7659 // client isn't retrieving buffers fast enough
7660 if (!activeTrack->setOverflow()) {
7661 nsecs_t now = systemTime();
7662 // FIXME should lastWarning per track?
7663 if ((now - lastWarning) > kWarningThrottleNs) {
7664 ALOGW("RecordThread: buffer overflow");
7665 lastWarning = now;
7666 }
7667 }
7668 break;
7669 case OVERRUN_FALSE:
7670 activeTrack->clearOverflow();
7671 break;
7672 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007673 break;
7674 }
7675
Andy Hung3f0c9022016-01-15 17:49:46 -08007676 // update frame information and push timestamp out
7677 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007678 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007679 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7680 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007681 }
7682
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007683unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007684 // enable changes in effect chain
7685 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007686 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007687 if (audio_has_proportional_frames(mFormat)
7688 && loopCount == lastLoopCountRead + 1) {
7689 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7690 const double jitterMs =
7691 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7692 {framesRead, readPeriodNs},
7693 {0, 0} /* lastTimestamp */, mSampleRate);
7694 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7695
7696 Mutex::Autolock _l(mLock);
7697 mIoJitterMs.add(jitterMs);
7698 mProcessTimeMs.add(processMs);
7699 }
7700 // update timing info.
7701 mLastIoBeginNs = lastIoBeginNs;
7702 mLastIoEndNs = lastIoEndNs;
7703 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007704 }
7705
Glenn Kasten93e471f2013-08-19 08:40:07 -07007706 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007707
7708 {
7709 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007710 for (size_t i = 0; i < mTracks.size(); i++) {
7711 sp<RecordTrack> track = mTracks[i];
7712 track->invalidate();
7713 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007714 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007715 mStartStopCond.broadcast();
7716 }
7717
7718 releaseWakeLock();
7719
7720 ALOGV("RecordThread %p exiting", this);
7721 return false;
7722}
7723
Glenn Kasten93e471f2013-08-19 08:40:07 -07007724void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007725{
7726 if (!mStandby) {
7727 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007728 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007729 mStandby = true;
7730 }
7731}
7732
7733void AudioFlinger::RecordThread::inputStandBy()
7734{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007735 // Idle the fast capture if it's currently running
7736 if (mFastCapture != 0) {
7737 FastCaptureStateQueue *sq = mFastCapture->sq();
7738 FastCaptureState *state = sq->begin();
7739 if (!(state->mCommand & FastCaptureState::IDLE)) {
7740 state->mCommand = FastCaptureState::COLD_IDLE;
7741 state->mColdFutexAddr = &mFastCaptureFutex;
7742 state->mColdGen++;
7743 mFastCaptureFutex = 0;
7744 sq->end();
7745 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7746 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7747#if 0
7748 if (kUseFastCapture == FastCapture_Dynamic) {
7749 // FIXME
7750 }
7751#endif
7752#ifdef AUDIO_WATCHDOG
7753 // FIXME
7754#endif
7755 } else {
7756 sq->end(false /*didModify*/);
7757 }
7758 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007759 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007760 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007761
7762 // If going into standby, flush the pipe source.
7763 if (mPipeSource.get() != nullptr) {
7764 const ssize_t flushed = mPipeSource->flush();
7765 if (flushed > 0) {
7766 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7767 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7768 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7769 }
7770 }
Eric Laurent81784c32012-11-19 14:55:58 -08007771}
7772
Glenn Kasten05997e22014-03-13 15:08:33 -07007773// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007774sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007775 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007776 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007777 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007778 audio_format_t format,
7779 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007780 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007781 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007782 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007783 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007784 const Identity& identity,
Eric Laurent05067782016-06-01 18:27:28 -07007785 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007786 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007787 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02007788 audio_port_handle_t portId,
7789 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08007790{
Glenn Kasten74935e42013-12-19 08:56:45 -08007791 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007792 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007793 sp<RecordTrack> track;
7794 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007795 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007796 audio_input_flags_t requestedFlags = *flags;
7797 uint32_t sampleRate;
Eric Laurentec376dc2021-04-08 20:41:22 +02007798 Identity checkedIdentity = AudioFlinger::checkIdentityPackage(identity);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007799
7800 lStatus = initCheck();
7801 if (lStatus != NO_ERROR) {
7802 ALOGE("createRecordTrack_l() audio driver not initialized");
7803 goto Exit;
7804 }
7805
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007806 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7807 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7808 lStatus = BAD_VALUE;
7809 goto Exit;
7810 }
7811
Eric Laurentec376dc2021-04-08 20:41:22 +02007812 if (maxSharedAudioHistoryMs != 0) {
7813 if (!captureHotwordAllowed(checkedIdentity)) {
7814 lStatus = PERMISSION_DENIED;
7815 goto Exit;
7816 }
7817 //TODO: b/185972521 allow resampling buffer resizing on fast mixers by pausing
7818 // the fast mixer thread while resizing the buffer in the normal thread
7819 if (hasFastCapture()) {
7820 lStatus = BAD_VALUE;
7821 goto Exit;
7822 }
7823 if (maxSharedAudioHistoryMs < 0
7824 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
7825 lStatus = BAD_VALUE;
7826 goto Exit;
7827 }
7828 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08007829 if (*pSampleRate == 0) {
7830 *pSampleRate = mSampleRate;
7831 }
7832 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007833
7834 // special case for FAST flag considered OK if fast capture is present
7835 if (hasFastCapture()) {
7836 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7837 }
7838
Eric Laurentf14db3c2017-12-08 14:20:36 -08007839 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007840 if ((*flags & inputFlags) != *flags) {
7841 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7842 " input flags (%08x)",
7843 *flags, inputFlags);
7844 *flags = (audio_input_flags_t)(*flags & inputFlags);
7845 }
Eric Laurent81784c32012-11-19 14:55:58 -08007846
Glenn Kasten90e58b12013-07-31 16:16:02 -07007847 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007848 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007849 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007850 // we formerly checked for a callback handler (non-0 tid),
7851 // but that is no longer required for TRANSFER_OBTAIN mode
7852 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007853 // Frame count is not specified (0), or is less than or equal the pipe depth.
7854 // It is OK to provide a higher capacity than requested.
7855 // We will force it to mPipeFramesP2 below.
7856 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007857 // PCM data
7858 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007859 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007860 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007861 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007862 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007863 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007864 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007865 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007866 hasFastCapture() &&
7867 // there are sufficient fast track slots available
7868 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007869 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007870 // check compatibility with audio effects.
7871 Mutex::Autolock _l(mLock);
7872 // Do not accept FAST flag if the session has software effects
7873 sp<EffectChain> chain = getEffectChain_l(sessionId);
7874 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007875 audio_input_flags_t old = *flags;
7876 chain->checkInputFlagCompatibility(flags);
7877 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007878 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7879 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007880 }
7881 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007882 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007883 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7884 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007885 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007886 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7887 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007888 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007889 this, frameCount, mFrameCount, mPipeFramesP2,
7890 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007891 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007892 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007893 }
7894 }
7895
Eric Laurentf14db3c2017-12-08 14:20:36 -08007896 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7897 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7898 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7899 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7900 lStatus = BAD_TYPE;
7901 goto Exit;
7902 }
7903
Glenn Kasten74105912014-07-03 12:28:53 -07007904 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007905 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007906 // fast track: frame count is exactly the pipe depth
7907 frameCount = mPipeFramesP2;
7908 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007909 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007910 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007911 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7912 // or 20 ms if there is a fast capture
7913 // TODO This could be a roundupRatio inline, and const
7914 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7915 * sampleRate + mSampleRate - 1) / mSampleRate;
7916 // minimum number of notification periods is at least kMinNotifications,
7917 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7918 static const size_t kMinNotifications = 3;
7919 static const uint32_t kMinMs = 30;
7920 // TODO This could be a roundupRatio inline
7921 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7922 // TODO This could be a roundupRatio inline
7923 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7924 maxNotificationFrames;
7925 const size_t minFrameCount = maxNotificationFrames *
7926 max(kMinNotifications, minNotificationsByMs);
7927 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007928 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7929 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007930 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007931 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007932 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007933 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007934
7935 { // scope for mLock
7936 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02007937 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02007938 if (!mSharedAudioPackageName.empty()
7939 && mSharedAudioPackageName == checkedIdentity.packageName
7940 && mSharedAudioSessionId == sessionId
7941 && captureHotwordAllowed(checkedIdentity)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02007942 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02007943 }
Eric Laurent81784c32012-11-19 14:55:58 -08007944
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007945 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007946 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007947 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Eric Laurent2407ce32021-04-26 14:56:03 +02007948 checkedIdentity, *flags, TrackBase::TYPE_DEFAULT, portId, startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08007949
Glenn Kasten03003332013-08-06 15:40:54 -07007950 lStatus = track->initCheck();
7951 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007952 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007953 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007954 goto Exit;
7955 }
7956 mTracks.add(track);
7957
Eric Laurent05067782016-06-01 18:27:28 -07007958 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007959 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7960 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7961 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007962 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007963 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007964
7965 if (maxSharedAudioHistoryMs != 0) {
7966 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
7967 }
7968
Eric Laurent81784c32012-11-19 14:55:58 -08007969 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007970
Eric Laurent81784c32012-11-19 14:55:58 -08007971 lStatus = NO_ERROR;
7972
7973Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007974 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007975 return track;
7976}
7977
7978status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7979 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007980 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007981{
7982 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7983 sp<ThreadBase> strongMe = this;
7984 status_t status = NO_ERROR;
7985
7986 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007987 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007988 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007989 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007990 triggerSession,
7991 recordTrack->sessionId(),
7992 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007993 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007994 // Sync event can be cancelled by the trigger session if the track is not in a
7995 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007996 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007997 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007998 } else {
7999 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008000 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008001 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008002 }
8003 }
8004
8005 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008006 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008007 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008008 if (recordTrack->isInvalid()) {
8009 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008010 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8011 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008012 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008013 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8014 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008015 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8016 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008017 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008018 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008019 } else {
8020 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008021 }
8022 return status;
8023 }
8024
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008025 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8026 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8027 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008028 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008029 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008030 status_t status = NO_ERROR;
8031 if (recordTrack->isExternalTrack()) {
8032 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008033 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008034 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008035 if (recordTrack->isInvalid()) {
8036 recordTrack->clearSyncStartEvent();
8037 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8038 recordTrack->mState = TrackBase::STARTING_2;
8039 // STARTING_2 forces destroy to call stopInput.
8040 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008041 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8042 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008043 }
8044 if (recordTrack->mState != TrackBase::STARTING_1) {
8045 ALOGW("%s(%d): unsynchronized mState:%d change",
8046 __func__, recordTrack->id(), recordTrack->mState);
8047 // Someone else has changed state, let them take over,
8048 // leave mState in the new state.
8049 recordTrack->clearSyncStartEvent();
8050 return INVALID_OPERATION;
8051 }
8052 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008053 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008054 ALOGW("%s(%d): startInput failed, status %d",
8055 __func__, recordTrack->id(), status);
8056 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8057 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008058 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008059 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008060 return status;
8061 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008062 sendIoConfigEvent_l(
8063 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008064 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008065
8066 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8067
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008068 // Catch up with current buffer indices if thread is already running.
8069 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8070 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8071 // see previously buffered data before it called start(), but with greater risk of overrun.
8072
Andy Hung73c02e42015-03-29 01:13:58 -07008073 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008074 if (!recordTrack->isDirect()) {
8075 // clear any converter state as new data will be discontinuous
8076 recordTrack->mRecordBufferConverter->reset();
8077 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008078 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008079 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008080 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008081 return status;
8082 }
Eric Laurent81784c32012-11-19 14:55:58 -08008083}
8084
Eric Laurent81784c32012-11-19 14:55:58 -08008085void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8086{
8087 sp<SyncEvent> strongEvent = event.promote();
8088
8089 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008090 sp<RefBase> ptr = strongEvent->cookie().promote();
8091 if (ptr != 0) {
8092 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8093 recordTrack->handleSyncStartEvent(strongEvent);
8094 }
Eric Laurent81784c32012-11-19 14:55:58 -08008095 }
8096}
8097
Glenn Kastena8356f62013-07-25 14:37:52 -07008098bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008099 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008100 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008101 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008102 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008103 return false;
8104 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008105 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008106 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008107
Andy Hungabfab202019-03-07 19:45:54 -08008108 // NOTE: Waiting here is important to keep stop synchronous.
8109 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008110 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8111 mWaitWorkCV.broadcast(); // signal thread to stop
8112 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008113 }
Andy Hungce685402018-10-05 17:23:27 -07008114
8115 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008116 ALOGV("Record stopped OK");
8117 return true;
8118 }
Andy Hungce685402018-10-05 17:23:27 -07008119
8120 // don't handle anything - we've been invalidated or restarted and in a different state
8121 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8122 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008123 return false;
8124}
8125
Glenn Kasten0f11b512014-01-31 16:18:54 -08008126bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008127{
8128 return false;
8129}
8130
Glenn Kasten0f11b512014-01-31 16:18:54 -08008131status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008132{
8133#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8134 if (!isValidSyncEvent(event)) {
8135 return BAD_VALUE;
8136 }
8137
Glenn Kastend848eb42016-03-08 13:42:11 -08008138 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008139 status_t ret = NAME_NOT_FOUND;
8140
8141 Mutex::Autolock _l(mLock);
8142
8143 for (size_t i = 0; i < mTracks.size(); i++) {
8144 sp<RecordTrack> track = mTracks[i];
8145 if (eventSession == track->sessionId()) {
8146 (void) track->setSyncEvent(event);
8147 ret = NO_ERROR;
8148 }
8149 }
8150 return ret;
8151#else
8152 return BAD_VALUE;
8153#endif
8154}
8155
jiabin653cc0a2018-01-17 17:54:10 -08008156status_t AudioFlinger::RecordThread::getActiveMicrophones(
8157 std::vector<media::MicrophoneInfo>* activeMicrophones)
8158{
8159 ALOGV("RecordThread::getActiveMicrophones");
8160 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008161 if (mInput == nullptr || mInput->stream == nullptr) {
8162 return NO_INIT;
8163 }
jiabin9ff780e2018-03-19 18:19:52 -07008164 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8165 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008166}
8167
Paul McLean12340082019-03-19 09:35:05 -06008168status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8169 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008170{
Paul McLean12340082019-03-19 09:35:05 -06008171 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008172 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008173 if (mInput == nullptr || mInput->stream == nullptr) {
8174 return NO_INIT;
8175 }
Paul McLean12340082019-03-19 09:35:05 -06008176 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008177}
8178
Paul McLean12340082019-03-19 09:35:05 -06008179status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008180{
Paul McLean12340082019-03-19 09:35:05 -06008181 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008182 AutoMutex _l(mLock);
Paul McLean8a661a32021-04-12 10:21:42 -06008183 if (mInput == nullptr || mInput->stream == nullptr) {
8184 return NO_INIT;
8185 }
Paul McLean12340082019-03-19 09:35:05 -06008186 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008187}
8188
Eric Laurentec376dc2021-04-08 20:41:22 +02008189status_t AudioFlinger::RecordThread::shareAudioHistory(
8190 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8191 int64_t sharedAudioStartMs) {
8192 AutoMutex _l(mLock);
8193 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8194}
8195
8196status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8197 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8198 int64_t sharedAudioStartMs) {
8199 if (hasFastCapture()) {
8200 return BAD_VALUE;
8201 }
8202 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8203 return BAD_VALUE;
8204 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008205
8206 if (sharedAudioStartMs < 0
8207 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008208 return BAD_VALUE;
8209 }
8210
Eric Laurent2407ce32021-04-26 14:56:03 +02008211 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8212 // As we cannot detect more than one wraparound, only accept values up current write position
8213 // after one wraparound
8214 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8215 // app waits several hours after the start time was computed.
8216 const int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
8217 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8218 (int32_t)sharedAudioStartFrames);
8219 if (sharedOffset < 0
8220 || sharedOffset > mRsmpInFrames) {
8221 return BAD_VALUE;
8222 }
8223
Eric Laurentec376dc2021-04-08 20:41:22 +02008224 mSharedAudioPackageName = sharedAudioPackageName;
8225 if (mSharedAudioPackageName.empty()) {
8226 mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent2407ce32021-04-26 14:56:03 +02008227 mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008228 } else {
8229 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008230 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008231 }
8232 return NO_ERROR;
8233}
8234
Kevin Rocard069c2712018-03-29 19:09:14 -07008235void AudioFlinger::RecordThread::updateMetadata_l()
8236{
8237 if (mInput == nullptr || mInput->stream == nullptr ||
8238 !mActiveTracks.readAndClearHasChanged()) {
8239 return;
8240 }
8241 StreamInHalInterface::SinkMetadata metadata;
8242 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008243 // Do not forward PatchRecord metadata to audio HAL
8244 if (track->isPatchTrack()) {
8245 continue;
8246 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008247 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008248 record_track_metadata_v7_t trackMetadata;
8249 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008250 .source = track->attributes().source,
8251 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008252 };
8253 trackMetadata.channel_mask = track->channelMask(),
8254 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8255
8256 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008257 }
8258 mInput->stream->updateSinkMetadata(metadata);
8259}
8260
Eric Laurent81784c32012-11-19 14:55:58 -08008261// destroyTrack_l() must be called with ThreadBase::mLock held
8262void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8263{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008264 track->terminate();
8265 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008266
Eric Laurent81784c32012-11-19 14:55:58 -08008267 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008268 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008269 removeTrack_l(track);
8270 }
8271}
8272
8273void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8274{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008275 String8 result;
8276 track->appendDump(result, false /* active */);
8277 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8278
Eric Laurent81784c32012-11-19 14:55:58 -08008279 mTracks.remove(track);
8280 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008281 if (track->isFastTrack()) {
8282 ALOG_ASSERT(!mFastTrackAvail);
8283 mFastTrackAvail = true;
8284 }
Eric Laurent81784c32012-11-19 14:55:58 -08008285}
8286
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008287void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008288{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008289 AudioStreamIn *input = mInput;
8290 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8291 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008292 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008293 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008294 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008295 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008296 }
Andy Hungbfa64962017-06-12 14:43:19 -07008297
8298 if (input != nullptr) {
8299 dprintf(fd, " Hal stream dump:\n");
8300 (void)input->stream->dump(fd);
8301 }
8302
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008303 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008304 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008305
Glenn Kasten2f90c512015-12-02 11:40:09 -08008306 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8307 // while we are dumping it. It may be inconsistent, but it won't mutate!
8308 // This is a large object so we place it on the heap.
8309 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008310 const std::unique_ptr<FastCaptureDumpState> copy =
8311 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008312 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008313}
8314
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008315void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008316{
Eric Laurent81784c32012-11-19 14:55:58 -08008317 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008318 size_t numtracks = mTracks.size();
8319 size_t numactive = mActiveTracks.size();
8320 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008321 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008322 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008323 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008324 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008325 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008326 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008327 for (size_t i = 0; i < numtracks ; ++i) {
8328 sp<RecordTrack> track = mTracks[i];
8329 if (track != 0) {
8330 bool active = mActiveTracks.indexOf(track) >= 0;
8331 if (active) {
8332 numactiveseen++;
8333 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008334 result.append(prefix);
8335 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008336 }
Eric Laurent81784c32012-11-19 14:55:58 -08008337 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008338 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008339 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008340 }
8341
Marco Nelissenb2208842014-02-07 14:00:50 -08008342 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008343 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008344 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008345 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008346 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008347 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008348 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008349 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008350 result.append(prefix);
8351 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008352 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008353 }
Eric Laurent81784c32012-11-19 14:55:58 -08008354
8355 }
8356 write(fd, result.string(), result.size());
8357}
8358
Eric Laurent5ada82e2019-08-29 17:53:54 -07008359void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008360{
8361 Mutex::Autolock _l(mLock);
8362 for (size_t i = 0; i < mTracks.size() ; i++) {
8363 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008364 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008365 track->setSilenced(silenced);
8366 }
8367 }
8368}
Andy Hung73c02e42015-03-29 01:13:58 -07008369
8370void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8371{
8372 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8373 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008374 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008375 const int32_t rear = recordThread->mRsmpInRear;
8376 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008377 if (mRecordTrack->startFrames() >= 0) {
8378 int32_t startFrames = mRecordTrack->startFrames();
8379 // Accept a recent wraparound of mRsmpInRear
8380 if (startFrames <= rear) {
8381 deltaFrames = rear - startFrames;
8382 } else {
8383 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008384 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008385 // start frame cannot be further in the past than start of resampling buffer
8386 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8387 deltaFrames = recordThread->mRsmpInFrames;
8388 }
8389 }
8390 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008391}
8392
8393void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8394 size_t *framesAvailable, bool *hasOverrun)
8395{
8396 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8397 RecordThread *recordThread = (RecordThread *) threadBase.get();
8398 const int32_t rear = recordThread->mRsmpInRear;
8399 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008400 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008401
8402 size_t framesIn;
8403 bool overrun = false;
8404 if (filled < 0) {
8405 // should not happen, but treat like a massive overrun and re-sync
8406 framesIn = 0;
8407 mRsmpInFront = rear;
8408 overrun = true;
8409 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8410 framesIn = (size_t) filled;
8411 } else {
8412 // client is not keeping up with server, but give it latest data
8413 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008414 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8415 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008416 overrun = true;
8417 }
8418 if (framesAvailable != NULL) {
8419 *framesAvailable = framesIn;
8420 }
8421 if (hasOverrun != NULL) {
8422 *hasOverrun = overrun;
8423 }
8424}
8425
Eric Laurent81784c32012-11-19 14:55:58 -08008426// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008427status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008428 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008429{
Andy Hung73c02e42015-03-29 01:13:58 -07008430 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008431 if (threadBase == 0) {
8432 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008433 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008434 return NOT_ENOUGH_DATA;
8435 }
8436 RecordThread *recordThread = (RecordThread *) threadBase.get();
8437 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008438 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008439 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008440 // FIXME should not be P2 (don't want to increase latency)
8441 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008442 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008443 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008444 front &= recordThread->mRsmpInFramesP2 - 1;
8445 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008446 if (part1 > (size_t) filled) {
8447 part1 = filled;
8448 }
8449 size_t ask = buffer->frameCount;
8450 ALOG_ASSERT(ask > 0);
8451 if (part1 > ask) {
8452 part1 = ask;
8453 }
8454 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008455 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008456 buffer->raw = NULL;
8457 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008458 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008459 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008460 }
8461
Andy Hung57446612015-04-19 23:56:46 -07008462 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008463 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008464 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008465 return NO_ERROR;
8466}
8467
8468// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008469void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8470 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008471{
Hongwei Wang95e37682019-04-12 11:13:36 -07008472 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008473 if (stepCount == 0) {
8474 return;
8475 }
Andy Hung73c02e42015-03-29 01:13:58 -07008476 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8477 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008478 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008479 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008480 buffer->frameCount = 0;
8481}
8482
Eric Laurentd8365c52017-07-16 15:27:05 -07008483void AudioFlinger::RecordThread::checkBtNrec()
8484{
8485 Mutex::Autolock _l(mLock);
8486 checkBtNrec_l();
8487}
8488
8489void AudioFlinger::RecordThread::checkBtNrec_l()
8490{
8491 // disable AEC and NS if the device is a BT SCO headset supporting those
8492 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008493 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008494 mAudioFlinger->btNrecIsOff();
8495 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8496 for (size_t i = 0; i < mEffectChains.size(); i++) {
8497 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8498 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8499 }
8500 }
8501}
8502
Andy Hung97a893e2015-03-29 01:03:07 -07008503
Eric Laurent10351942014-05-08 18:49:52 -07008504bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8505 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008506{
8507 bool reconfig = false;
8508
Eric Laurent10351942014-05-08 18:49:52 -07008509 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008510
Eric Laurent10351942014-05-08 18:49:52 -07008511 audio_format_t reqFormat = mFormat;
8512 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008513 // 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 -07008514 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8515
8516 AudioParameter param = AudioParameter(keyValuePair);
8517 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008518
8519 // scope for AutoPark extends to end of method
8520 AutoPark<FastCapture> park(mFastCapture);
8521
Eric Laurent10351942014-05-08 18:49:52 -07008522 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8523 // channel count change can be requested. Do we mandate the first client defines the
8524 // HAL sampling rate and channel count or do we allow changes on the fly?
8525 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8526 samplingRate = value;
8527 reconfig = true;
8528 }
8529 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008530 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008531 status = BAD_VALUE;
8532 } else {
8533 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008534 reconfig = true;
8535 }
Eric Laurent10351942014-05-08 18:49:52 -07008536 }
8537 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8538 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008539 if (!audio_is_input_channel(mask) ||
8540 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008541 status = BAD_VALUE;
8542 } else {
8543 channelMask = mask;
8544 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008545 }
Eric Laurent10351942014-05-08 18:49:52 -07008546 }
8547 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8548 // do not accept frame count changes if tracks are open as the track buffer
8549 // size depends on frame count and correct behavior would not be guaranteed
8550 // if frame count is changed after track creation
8551 if (mActiveTracks.size() > 0) {
8552 status = INVALID_OPERATION;
8553 } else {
8554 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008555 }
Eric Laurent10351942014-05-08 18:49:52 -07008556 }
8557 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008558 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008559 }
8560 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8561 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008562 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008563 }
Glenn Kastene198c362013-08-13 09:13:36 -07008564
Eric Laurent10351942014-05-08 18:49:52 -07008565 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008566 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008567 if (status == INVALID_OPERATION) {
8568 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008569 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008570 }
8571 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008572 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008573 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8574 if (mInput->stream->getAudioProperties(&config) == OK &&
8575 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8576 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8577 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_8) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008578 status = NO_ERROR;
8579 }
Eric Laurent81784c32012-11-19 14:55:58 -08008580 }
Eric Laurent10351942014-05-08 18:49:52 -07008581 if (status == NO_ERROR) {
8582 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008583 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008584 }
8585 }
Eric Laurent81784c32012-11-19 14:55:58 -08008586 }
Eric Laurent10351942014-05-08 18:49:52 -07008587
Eric Laurent81784c32012-11-19 14:55:58 -08008588 return reconfig;
8589}
8590
8591String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8592{
Eric Laurent81784c32012-11-19 14:55:58 -08008593 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008594 if (initCheck() == NO_ERROR) {
8595 String8 out_s8;
8596 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8597 return out_s8;
8598 }
Eric Laurent81784c32012-11-19 14:55:58 -08008599 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008600 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008601}
8602
Eric Laurent09f1ed22019-04-24 17:45:17 -07008603void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8604 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008605 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8606
8607 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008608
8609 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008610 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008611 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008612 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008613 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008614 desc->mChannelMask = mChannelMask;
8615 desc->mSamplingRate = mSampleRate;
8616 desc->mFormat = mFormat;
8617 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008618 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008619 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008620 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008621 case AUDIO_CLIENT_STARTED:
8622 desc->mPatch = mPatch;
8623 desc->mPortId = portId;
8624 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008625 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008626 default:
8627 break;
8628 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008629 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008630}
8631
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008632void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008633{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008634 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8635 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008636 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008637 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8638 if (audio_is_linear_pcm(mFormat)) {
8639 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8640 mChannelCount, FCC_8);
8641 } else {
8642 // Can have more that FCC_8 channels in encoded streams.
8643 ALOGI("HAL format %#x is not linear pcm", mFormat);
8644 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008645 result = mInput->stream->getFrameSize(&mFrameSize);
8646 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008647 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8648 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008649 result = mInput->stream->getBufferSize(&mBufferSize);
8650 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008651 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008652 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8653 "mBufferSize=%zu, mFrameCount=%zu",
8654 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008655
Eric Laurentec376dc2021-04-08 20:41:22 +02008656 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8657 mRsmpInFrames = 0;
8658 resizeInputBuffer_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008659
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008660 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8661 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008662
8663 audio_input_flags_t flags = mInput->flags;
8664 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8665 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8666 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8667 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8668 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8669 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8670 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8671 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8672 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008673}
8674
Glenn Kasten5f972c02014-01-13 09:59:31 -08008675uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008676{
8677 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008678 uint32_t result;
8679 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8680 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008681 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008682 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008683}
8684
Glenn Kastend848eb42016-03-08 13:42:11 -08008685KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008686{
Glenn Kastend848eb42016-03-08 13:42:11 -08008687 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008688 Mutex::Autolock _l(mLock);
8689 for (size_t j = 0; j < mTracks.size(); ++j) {
8690 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008691 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008692 if (ids.indexOfKey(sessionId) < 0) {
8693 ids.add(sessionId, true);
8694 }
8695 }
8696 return ids;
8697}
8698
8699AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8700{
8701 Mutex::Autolock _l(mLock);
8702 AudioStreamIn *input = mInput;
8703 mInput = NULL;
8704 return input;
8705}
8706
8707// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008708sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008709{
8710 if (mInput == NULL) {
8711 return NULL;
8712 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008713 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008714}
8715
8716status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8717{
Eric Laurent81784c32012-11-19 14:55:58 -08008718 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008719 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008720 chain->setInBuffer(NULL);
8721 chain->setOutBuffer(NULL);
8722
8723 checkSuspendOnAddEffectChain_l(chain);
8724
Eric Laurent1b928682014-10-02 19:41:47 -07008725 // make sure enabled pre processing effects state is communicated to the HAL as we
8726 // just moved them to a new input stream.
8727 chain->syncHalEffectsState();
8728
Eric Laurent81784c32012-11-19 14:55:58 -08008729 mEffectChains.add(chain);
8730
8731 return NO_ERROR;
8732}
8733
8734size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8735{
8736 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008737
8738 for (size_t i = 0; i < mEffectChains.size(); i++) {
8739 if (chain == mEffectChains[i]) {
8740 mEffectChains.removeAt(i);
8741 break;
8742 }
Eric Laurent81784c32012-11-19 14:55:58 -08008743 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008744 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008745}
8746
Eric Laurent1c333e22014-05-20 10:48:17 -07008747status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8748 audio_patch_handle_t *handle)
8749{
8750 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008751
8752 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008753 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008754 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008755 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008756 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008757 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008758 }
8759
Eric Laurentd8365c52017-07-16 15:27:05 -07008760 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008761
8762 // store new source and send to effects
8763 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8764 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008765 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008766 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008767 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008768 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008769
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008770 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008771 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8772 status = hwDevice->createAudioPatch(patch->num_sources,
8773 patch->sources,
8774 patch->num_sinks,
8775 patch->sinks,
8776 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008777 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008778 char *address;
8779 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8780 address = audio_device_address_to_parameter(
8781 patch->sources[0].ext.device.type,
8782 patch->sources[0].ext.device.address);
8783 } else {
8784 address = (char *)calloc(1, 1);
8785 }
8786 AudioParameter param = AudioParameter(String8(address));
8787 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008788 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008789 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008790 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008791 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008792 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008793 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008794 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008795
jiabinc52b1ff2019-10-31 17:20:42 -07008796 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008797 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008798 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008799 }
Eric Laurent296fb132015-05-01 11:38:42 -07008800
Andy Hungc2b11cb2020-04-22 09:04:01 -07008801 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008802 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008803 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008804 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008805 // also dispatch to active AudioRecords
8806 for (const auto &track : mActiveTracks) {
8807 track->logEndInterval();
8808 track->logBeginInterval(pathSourcesAsString);
8809 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008810 return status;
8811}
8812
8813status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8814{
8815 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008816
jiabinc52b1ff2019-10-31 17:20:42 -07008817 mPatch = audio_patch{};
8818 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008819
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008820 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008821 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8822 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008823 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008824 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008825 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008826 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008827 }
8828 return status;
8829}
8830
jiabinc52b1ff2019-10-31 17:20:42 -07008831void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8832{
wendy lin56aa82b2020-12-02 15:19:55 +08008833 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07008834 mOutDevices = outDevices;
8835 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8836 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008837 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008838 }
8839}
8840
Eric Laurentec376dc2021-04-08 20:41:22 +02008841int32_t AudioFlinger::RecordThread::getOldestFront_l()
8842{
8843 if (mTracks.size() == 0) {
8844 return 0;
8845 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008846 int32_t oldestFront = mRsmpInRear;
8847 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008848 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008849 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8850 int32_t filled;
8851 if (front <= mRsmpInRear) {
8852 filled = mRsmpInRear - front;
8853 } else {
8854 filled = (int32_t)((int64_t)mRsmpInRear + UINT32_MAX + 1 - front);
8855 }
8856 if (filled > maxFilled) {
8857 oldestFront = front;
8858 maxFilled = filled;
8859 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008860 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008861 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02008862}
8863
8864void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
8865{
8866 if (offset == 0) {
8867 return;
8868 }
8869 for (size_t i = 0; i < mTracks.size(); i++) {
8870 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8871 front = audio_utils::safe_sub_overflow(front, offset);
8872 mTracks[i]->mResamplerBufferProvider->setFront(front);
8873 }
8874}
8875
8876void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
8877{
8878 // This is the formula for calculating the temporary buffer size.
8879 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
8880 // 1 full output buffer, regardless of the alignment of the available input.
8881 // The value is somewhat arbitrary, and could probably be even larger.
8882 // A larger value should allow more old data to be read after a track calls start(),
8883 // without increasing latency.
8884 //
8885 // Note this is independent of the maximum downsampling ratio permitted for capture.
8886 size_t minRsmpInFrames = mFrameCount * 7;
8887
8888 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
8889 // capture history available to another client using the same session ID:
8890 // dimension the resampler input buffer accordingly.
8891
8892 // Get oldest client read position: getOldestFront_l() must be called before altering
8893 // mRsmpInRear, or mRsmpInFrames
8894 int32_t previousFront = getOldestFront_l();
8895 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
8896 int32_t previousRear = mRsmpInRear;
8897 mRsmpInRear = 0;
8898
8899 if (maxSharedAudioHistoryMs != 0) {
8900 // resizeInputBuffer_l should never be called with a non zero shared history if the
8901 // buffer was not already allocated
8902 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
8903 "resizeInputBuffer_l() called with shared history and unallocated buffer");
8904 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
8905 // never reduce resampler input buffer size
8906 if (rsmpInFrames < mRsmpInFrames) {
8907 return;
8908 }
8909 mRsmpInFrames = rsmpInFrames;
8910 }
8911 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
8912 // initialized
8913 if (mRsmpInFrames < minRsmpInFrames) {
8914 mRsmpInFrames = minRsmpInFrames;
8915 }
8916 mRsmpInFramesP2 = roundup(mRsmpInFrames);
8917
8918 // TODO optimize audio capture buffer sizes ...
8919 // Here we calculate the size of the sliding buffer used as a source
8920 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8921 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8922 // be better to have it derived from the pipe depth in the long term.
8923 // The current value is higher than necessary. However it should not add to latency.
8924
8925 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
8926 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8927
8928 void *rsmpInBuffer;
8929 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
8930 // if posix_memalign fails, will segv here.
8931 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
8932
8933 // Copy audio history if any from old buffer before freeing it
8934 if (previousRear != 0) {
8935 ALOG_ASSERT(mRsmpInBuffer != nullptr,
8936 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
8937
8938 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
8939 previousFront &= previousRsmpInFramesP2 - 1;
8940 size_t part1 = previousRsmpInFramesP2 - previousFront;
8941 if (part1 > (size_t) unread) {
8942 part1 = unread;
8943 }
8944 if (part1 != 0) {
8945 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
8946 part1 * mFrameSize);
8947 mRsmpInRear = part1;
8948 part1 = unread - part1;
8949 if (part1 != 0) {
8950 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
8951 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
8952 mRsmpInRear += part1;
8953 }
8954 }
8955 // Update front for all clients according to new rear
8956 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
8957 } else {
8958 mRsmpInRear = 0;
8959 }
8960 free(mRsmpInBuffer);
8961 mRsmpInBuffer = rsmpInBuffer;
8962}
8963
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008964void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008965{
8966 Mutex::Autolock _l(mLock);
8967 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008968 if (record->getSource()) {
8969 mSource = record->getSource();
8970 }
Eric Laurent83b88082014-06-20 18:31:16 -07008971}
8972
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008973void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008974{
8975 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008976 if (mSource == record->getSource()) {
8977 mSource = mInput;
8978 }
Eric Laurent83b88082014-06-20 18:31:16 -07008979 destroyTrack_l(record);
8980}
8981
Mikhail Naganovdc769682018-05-04 15:34:08 -07008982void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008983{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008984 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008985 config->role = AUDIO_PORT_ROLE_SINK;
8986 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8987 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008988 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8989 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8990 config->flags.input = mInput->flags;
8991 }
Eric Laurent83b88082014-06-20 18:31:16 -07008992}
Eric Laurent1c333e22014-05-20 10:48:17 -07008993
Eric Laurent6acd1d42017-01-04 14:23:29 -08008994// ----------------------------------------------------------------------------
8995// Mmap
8996// ----------------------------------------------------------------------------
8997
8998AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8999 : mThread(thread)
9000{
Phil Burk9fabbf82017-08-03 12:02:00 -07009001 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009002}
9003
9004AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9005{
Phil Burk9fabbf82017-08-03 12:02:00 -07009006 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009007}
9008
9009status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9010 struct audio_mmap_buffer_info *info)
9011{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009012 return mThread->createMmapBuffer(minSizeFrames, info);
9013}
9014
9015status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9016{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009017 return mThread->getMmapPosition(position);
9018}
9019
jiabinb7d8c5a2020-08-26 17:24:52 -07009020status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9021 int64_t *timeNanos) {
9022 return mThread->getExternalPosition(position, timeNanos);
9023}
9024
Eric Laurenta54f1282017-07-01 19:39:32 -07009025status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009026 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009027
9028{
jiabind1f1cb62020-03-24 11:57:57 -07009029 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009030}
9031
9032status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9033{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009034 return mThread->stop(handle);
9035}
9036
Eric Laurent18b57012017-02-13 16:23:52 -08009037status_t AudioFlinger::MmapThreadHandle::standby()
9038{
Eric Laurent18b57012017-02-13 16:23:52 -08009039 return mThread->standby();
9040}
9041
Eric Laurent6acd1d42017-01-04 14:23:29 -08009042
9043AudioFlinger::MmapThread::MmapThread(
9044 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009045 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009046 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009047 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009048 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009049 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009050 mActiveTracks(&this->mLocalLog),
9051 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9052 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009053{
Eric Laurent18b57012017-02-13 16:23:52 -08009054 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009055 readHalParameters_l();
9056}
9057
9058AudioFlinger::MmapThread::~MmapThread()
9059{
9060}
9061
9062void AudioFlinger::MmapThread::onFirstRef()
9063{
9064 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9065}
9066
9067void AudioFlinger::MmapThread::disconnect()
9068{
Eric Laurent331679c2018-04-16 17:03:16 -07009069 ActiveTracks<MmapTrack> activeTracks;
9070 {
9071 Mutex::Autolock _l(mLock);
9072 for (const sp<MmapTrack> &t : mActiveTracks) {
9073 activeTracks.add(t);
9074 }
9075 }
9076 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009077 stop(t->portId());
9078 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009079 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009080 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009081 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009082 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009083 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009084 }
9085}
9086
9087
9088void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9089 audio_stream_type_t streamType __unused,
9090 audio_session_t sessionId,
9091 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009092 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009093 audio_port_handle_t portId)
9094{
9095 mAttr = *attr;
9096 mSessionId = sessionId;
9097 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009098 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009099 mPortId = portId;
9100}
9101
9102status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9103 struct audio_mmap_buffer_info *info)
9104{
9105 if (mHalStream == 0) {
9106 return NO_INIT;
9107 }
Eric Laurent18b57012017-02-13 16:23:52 -08009108 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009109 return mHalStream->createMmapBuffer(minSizeFrames, info);
9110}
9111
9112status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9113{
9114 if (mHalStream == 0) {
9115 return NO_INIT;
9116 }
9117 return mHalStream->getMmapPosition(position);
9118}
9119
Eric Laurent331679c2018-04-16 17:03:16 -07009120status_t AudioFlinger::MmapThread::exitStandby()
9121{
9122 status_t ret = mHalStream->start();
9123 if (ret != NO_ERROR) {
9124 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9125 return ret;
9126 }
Andy Hungcf10d742020-04-28 15:38:24 -07009127 if (mStandby) {
9128 mThreadMetrics.logBeginInterval();
9129 mStandby = false;
9130 }
Eric Laurent331679c2018-04-16 17:03:16 -07009131 return NO_ERROR;
9132}
9133
Eric Laurenta54f1282017-07-01 19:39:32 -07009134status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009135 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009136 audio_port_handle_t *handle)
9137{
Eric Laurenta54f1282017-07-01 19:39:32 -07009138 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009139 client.identity.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009140 if (mHalStream == 0) {
9141 return NO_INIT;
9142 }
9143
9144 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009145
Eric Laurenta54f1282017-07-01 19:39:32 -07009146 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009147 // For the first track, reuse portId and session allocated when the stream was opened.
9148 ret = exitStandby();
9149 if (ret == NO_ERROR) {
9150 acquireWakeLock();
9151 }
9152 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009153 }
9154
9155 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9156
9157 audio_io_handle_t io = mId;
9158 if (isOutput()) {
9159 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9160 config.sample_rate = mSampleRate;
9161 config.channel_mask = mChannelMask;
9162 config.format = mFormat;
9163 audio_stream_type_t stream = streamType();
9164 audio_output_flags_t flags =
9165 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009166 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009167 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009168 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9169 mSessionId,
9170 &stream,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009171 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07009172 &config,
9173 flags,
9174 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009175 &portId,
9176 &secondaryOutputs);
9177 ALOGD_IF(!secondaryOutputs.empty(),
9178 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009179 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009180 audio_config_base_t config;
9181 config.sample_rate = mSampleRate;
9182 config.channel_mask = mChannelMask;
9183 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009184 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009185 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009186 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009187 mSessionId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009188 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07009189 &config,
9190 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9191 &deviceId,
9192 &portId);
9193 }
9194 // APM should not chose a different input or output stream for the same set of attributes
9195 // and audo configuration
9196 if (ret != NO_ERROR || io != mId) {
9197 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9198 __FUNCTION__, ret, io, mId);
9199 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009200 }
9201
9202 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009203 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009204 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009205 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009206 }
9207
Eric Laurent331679c2018-04-16 17:03:16 -07009208 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009209 // abort if start is rejected by audio policy manager
9210 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009211 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009212 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009213 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009214 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009215 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009216 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009217 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009218 }
Eric Laurent331679c2018-04-16 17:03:16 -07009219 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009220 } else {
9221 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009222 }
9223 return PERMISSION_DENIED;
9224 }
9225
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009226 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009227 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009228 mChannelMask, mSessionId, isOutput(), client.identity,
9229 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009230
Eric Laurent4eb58f12018-12-07 16:41:02 -08009231 if (isOutput()) {
9232 // force volume update when a new track is added
9233 mHalVolFloat = -1.0f;
9234 } else if (!track->isSilenced_l()) {
9235 for (const sp<MmapTrack> &t : mActiveTracks) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009236 if (t->isSilenced_l() && t->uid() != client.identity.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009237 t->invalidate();
9238 }
9239 }
9240
9241
Eric Laurent6acd1d42017-01-04 14:23:29 -08009242 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009243 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009244 if (chain != 0) {
9245 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
9246 chain->incTrackCnt();
9247 chain->incActiveTrackCnt();
9248 }
9249
Andy Hungc2b11cb2020-04-22 09:04:01 -07009250 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009251 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009252 broadcast_l();
9253
Eric Laurenta54f1282017-07-01 19:39:32 -07009254 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009255
9256 return NO_ERROR;
9257}
9258
9259status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9260{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009261 ALOGV("%s handle %d", __FUNCTION__, handle);
9262
9263 if (mHalStream == 0) {
9264 return NO_INIT;
9265 }
9266
Eric Laurenta54f1282017-07-01 19:39:32 -07009267 if (handle == mPortId) {
9268 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009269 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009270 return NO_ERROR;
9271 }
9272
Eric Laurent331679c2018-04-16 17:03:16 -07009273 Mutex::Autolock _l(mLock);
9274
Eric Laurent6acd1d42017-01-04 14:23:29 -08009275 sp<MmapTrack> track;
9276 for (const sp<MmapTrack> &t : mActiveTracks) {
9277 if (handle == t->portId()) {
9278 track = t;
9279 break;
9280 }
9281 }
9282 if (track == 0) {
9283 return BAD_VALUE;
9284 }
9285
9286 mActiveTracks.remove(track);
9287
Eric Laurent331679c2018-04-16 17:03:16 -07009288 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009289 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009290 AudioSystem::stopOutput(track->portId());
9291 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009292 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009293 AudioSystem::stopInput(track->portId());
9294 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009295 }
Eric Laurent331679c2018-04-16 17:03:16 -07009296 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009297
9298 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9299 if (chain != 0) {
9300 chain->decActiveTrackCnt();
9301 chain->decTrackCnt();
9302 }
9303
9304 broadcast_l();
9305
Eric Laurent6acd1d42017-01-04 14:23:29 -08009306 return NO_ERROR;
9307}
9308
Eric Laurent18b57012017-02-13 16:23:52 -08009309status_t AudioFlinger::MmapThread::standby()
9310{
9311 ALOGV("%s", __FUNCTION__);
9312
9313 if (mHalStream == 0) {
9314 return NO_INIT;
9315 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009316 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009317 return INVALID_OPERATION;
9318 }
9319 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009320 if (!mStandby) {
9321 mThreadMetrics.logEndInterval();
9322 mStandby = true;
9323 }
Eric Laurent18b57012017-02-13 16:23:52 -08009324 releaseWakeLock();
9325 return NO_ERROR;
9326}
9327
Eric Laurent6acd1d42017-01-04 14:23:29 -08009328
9329void AudioFlinger::MmapThread::readHalParameters_l()
9330{
9331 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9332 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9333 mFormat = mHALFormat;
9334 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9335 result = mHalStream->getFrameSize(&mFrameSize);
9336 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009337 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9338 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009339 result = mHalStream->getBufferSize(&mBufferSize);
9340 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9341 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009342
Andy Hungcf10d742020-04-28 15:38:24 -07009343 // TODO: make a readHalParameters call?
9344 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009345 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9346 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9347 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9348 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9349 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9350 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9351 /*
9352 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9353 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9354 (int32_t)mHapticChannelMask)
9355 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9356 (int32_t)mHapticChannelCount)
9357 */
9358 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9359 formatToString(mHALFormat).c_str())
9360 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9361 (int32_t)mFrameCount) // sic - added HAL
9362 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009363}
9364
9365bool AudioFlinger::MmapThread::threadLoop()
9366{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009367 checkSilentMode_l();
9368
9369 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9370
9371 while (!exitPending())
9372 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009373 Vector< sp<EffectChain> > effectChains;
9374
Andy Hung13850be2019-03-14 11:33:09 -07009375 { // under Thread lock
9376 Mutex::Autolock _l(mLock);
9377
Eric Laurent6acd1d42017-01-04 14:23:29 -08009378 if (mSignalPending) {
9379 // A signal was raised while we were unlocked
9380 mSignalPending = false;
9381 } else {
9382 if (mConfigEvents.isEmpty()) {
9383 // we're about to wait, flush the binder command buffer
9384 IPCThreadState::self()->flushCommands();
9385
9386 if (exitPending()) {
9387 break;
9388 }
9389
Eric Laurent6acd1d42017-01-04 14:23:29 -08009390 // wait until we have something to do...
9391 ALOGV("%s going to sleep", myName.string());
9392 mWaitWorkCV.wait(mLock);
9393 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009394
9395 checkSilentMode_l();
9396
9397 continue;
9398 }
9399 }
9400
9401 processConfigEvents_l();
9402
9403 processVolume_l();
9404
9405 checkInvalidTracks_l();
9406
9407 mActiveTracks.updatePowerState(this);
9408
Kevin Rocard069c2712018-03-29 19:09:14 -07009409 updateMetadata_l();
9410
Eric Laurent6acd1d42017-01-04 14:23:29 -08009411 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009412 } // release Thread lock
9413
Eric Laurent6acd1d42017-01-04 14:23:29 -08009414 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009415 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009416 }
Andy Hung13850be2019-03-14 11:33:09 -07009417
9418 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009419 unlockEffectChains(effectChains);
9420 // Effect chains will be actually deleted here if they were removed from
9421 // mEffectChains list during mixing or effects processing
9422 }
9423
9424 threadLoop_exit();
9425
9426 if (!mStandby) {
9427 threadLoop_standby();
9428 mStandby = true;
9429 }
9430
Eric Laurent6acd1d42017-01-04 14:23:29 -08009431 ALOGV("Thread %p type %d exiting", this, mType);
9432 return false;
9433}
9434
9435// checkForNewParameter_l() must be called with ThreadBase::mLock held
9436bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9437 status_t& status)
9438{
9439 AudioParameter param = AudioParameter(keyValuePair);
9440 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009441 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009442 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009443 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009444 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009445 if (sendToHal) {
9446 status = mHalStream->setParameters(keyValuePair);
9447 } else {
9448 status = NO_ERROR;
9449 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009450
9451 return false;
9452}
9453
9454String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9455{
9456 Mutex::Autolock _l(mLock);
9457 String8 out_s8;
9458 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9459 return out_s8;
9460 }
9461 return String8();
9462}
9463
Eric Laurent09f1ed22019-04-24 17:45:17 -07009464void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9465 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009466 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9467
9468 desc->mIoHandle = mId;
9469
9470 switch (event) {
9471 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009472 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009473 case AUDIO_INPUT_CONFIG_CHANGED:
9474 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009475 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009476 case AUDIO_OUTPUT_CONFIG_CHANGED:
9477 desc->mPatch = mPatch;
9478 desc->mChannelMask = mChannelMask;
9479 desc->mSamplingRate = mSampleRate;
9480 desc->mFormat = mFormat;
9481 desc->mFrameCount = mFrameCount;
9482 desc->mFrameCountHAL = mFrameCount;
9483 desc->mLatency = 0;
9484 break;
9485
9486 case AUDIO_INPUT_CLOSED:
9487 case AUDIO_OUTPUT_CLOSED:
9488 default:
9489 break;
9490 }
9491 mAudioFlinger->ioConfigChanged(event, desc, pid);
9492}
9493
9494status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9495 audio_patch_handle_t *handle)
9496{
9497 status_t status = NO_ERROR;
9498
9499 // store new device and send to effects
9500 audio_devices_t type = AUDIO_DEVICE_NONE;
9501 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009502 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9503 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9504 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009505 if (isOutput()) {
9506 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009507 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9508 && !mAudioHwDev->supportsAudioPatches(),
9509 "Enumerated device type(%#x) must not be used "
9510 "as it does not support audio patches",
9511 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009512 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009513 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9514 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009515 }
9516 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009517 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009518 } else {
9519 type = patch->sources[0].ext.device.type;
9520 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009521 numDevices = mPatch.num_sources;
9522 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009523 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009524 }
9525
9526 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009527 if (isOutput()) {
9528 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9529 } else {
9530 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9531 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009532 }
9533
jiabinc52b1ff2019-10-31 17:20:42 -07009534 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009535 // store new source and send to effects
9536 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9537 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9538 for (size_t i = 0; i < mEffectChains.size(); i++) {
9539 mEffectChains[i]->setAudioSource_l(mAudioSource);
9540 }
9541 }
9542 }
9543
9544 if (mAudioHwDev->supportsAudioPatches()) {
9545 status = mHalDevice->createAudioPatch(patch->num_sources,
9546 patch->sources,
9547 patch->num_sinks,
9548 patch->sinks,
9549 handle);
9550 } else {
9551 char *address;
9552 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9553 //FIXME: we only support address on first sink with HAL version < 3.0
9554 address = audio_device_address_to_parameter(
9555 patch->sinks[0].ext.device.type,
9556 patch->sinks[0].ext.device.address);
9557 } else {
9558 address = (char *)calloc(1, 1);
9559 }
9560 AudioParameter param = AudioParameter(String8(address));
9561 free(address);
9562 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9563 if (!isOutput()) {
9564 param.addInt(String8(AudioParameter::keyInputSource),
9565 (int)patch->sinks[0].ext.mix.usecase.source);
9566 }
9567 status = mHalStream->setParameters(param.toString());
9568 *handle = AUDIO_PATCH_HANDLE_NONE;
9569 }
9570
jiabinc52b1ff2019-10-31 17:20:42 -07009571 if (numDevices == 0 || mDeviceId != deviceId) {
9572 if (isOutput()) {
9573 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9574 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009575 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009576 } else {
9577 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9578 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9579 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009580 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009581 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009582 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009583 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009584 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009585 }
jiabinc52b1ff2019-10-31 17:20:42 -07009586 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009587 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009588 }
9589 return status;
9590}
9591
9592status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9593{
9594 status_t status = NO_ERROR;
9595
jiabinc52b1ff2019-10-31 17:20:42 -07009596 mPatch = audio_patch{};
9597 mOutDeviceTypeAddrs.clear();
9598 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009599
9600 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9601 supportsAudioPatches : false;
9602
9603 if (supportsAudioPatches) {
9604 status = mHalDevice->releaseAudioPatch(handle);
9605 } else {
9606 AudioParameter param;
9607 param.addInt(String8(AudioParameter::keyRouting), 0);
9608 status = mHalStream->setParameters(param.toString());
9609 }
9610 return status;
9611}
9612
Mikhail Naganovdc769682018-05-04 15:34:08 -07009613void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009614{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009615 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009616 if (isOutput()) {
9617 config->role = AUDIO_PORT_ROLE_SOURCE;
9618 config->ext.mix.hw_module = mAudioHwDev->handle();
9619 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9620 } else {
9621 config->role = AUDIO_PORT_ROLE_SINK;
9622 config->ext.mix.hw_module = mAudioHwDev->handle();
9623 config->ext.mix.usecase.source = mAudioSource;
9624 }
9625}
9626
9627status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9628{
9629 audio_session_t session = chain->sessionId();
9630
9631 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9632 // Attach all tracks with same session ID to this chain.
9633 // indicate all active tracks in the chain
9634 for (const sp<MmapTrack> &track : mActiveTracks) {
9635 if (session == track->sessionId()) {
9636 chain->incTrackCnt();
9637 chain->incActiveTrackCnt();
9638 }
9639 }
9640
9641 chain->setThread(this);
9642 chain->setInBuffer(nullptr);
9643 chain->setOutBuffer(nullptr);
9644 chain->syncHalEffectsState();
9645
9646 mEffectChains.add(chain);
9647 checkSuspendOnAddEffectChain_l(chain);
9648 return NO_ERROR;
9649}
9650
9651size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9652{
9653 audio_session_t session = chain->sessionId();
9654
9655 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9656
9657 for (size_t i = 0; i < mEffectChains.size(); i++) {
9658 if (chain == mEffectChains[i]) {
9659 mEffectChains.removeAt(i);
9660 // detach all active tracks from the chain
9661 // detach all tracks with same session ID from this chain
9662 for (const sp<MmapTrack> &track : mActiveTracks) {
9663 if (session == track->sessionId()) {
9664 chain->decActiveTrackCnt();
9665 chain->decTrackCnt();
9666 }
9667 }
9668 break;
9669 }
9670 }
9671 return mEffectChains.size();
9672}
9673
Eric Laurent6acd1d42017-01-04 14:23:29 -08009674void AudioFlinger::MmapThread::threadLoop_standby()
9675{
9676 mHalStream->standby();
9677}
9678
9679void AudioFlinger::MmapThread::threadLoop_exit()
9680{
Phil Burk7dce7282017-09-27 13:51:41 -07009681 // Do not call callback->onTearDown() because it is redundant for thread exit
9682 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009683}
9684
9685status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9686{
9687 return BAD_VALUE;
9688}
9689
9690bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9691{
9692 return false;
9693}
9694
9695status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9696 const effect_descriptor_t *desc, audio_session_t sessionId)
9697{
9698 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009699 if (audio_is_global_session(sessionId)) {
9700 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009701 desc->name, mThreadName);
9702 return BAD_VALUE;
9703 }
9704
9705 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9706 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9707 desc->name);
9708 return BAD_VALUE;
9709 }
9710 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009711 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9712 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009713 return BAD_VALUE;
9714 }
9715
9716 // Only allow effects without processing load or latency
9717 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9718 return BAD_VALUE;
9719 }
9720
jiabineb3bda02020-06-30 14:07:03 -07009721 if (EffectModule::isHapticGenerator(&desc->type)) {
9722 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9723 return BAD_VALUE;
9724 }
9725
Eric Laurent6acd1d42017-01-04 14:23:29 -08009726 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009727}
9728
9729void AudioFlinger::MmapThread::checkInvalidTracks_l()
9730{
9731 for (const sp<MmapTrack> &track : mActiveTracks) {
9732 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009733 sp<MmapStreamCallback> callback = mCallback.promote();
9734 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009735 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009736 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009737 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009738 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9739 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9740 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009741 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009742 }
9743 }
9744}
9745
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009746void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009747{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009748 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9749 mAttr.content_type, mAttr.usage, mAttr.source);
9750 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009751 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009752 dprintf(fd, " No active clients\n");
9753 }
9754}
9755
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009756void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009757{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009758 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009759 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009760 dprintf(fd, " %zu Tracks\n", numtracks);
9761 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009762 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009763 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009764 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009765 for (size_t i = 0; i < numtracks ; ++i) {
9766 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009767 result.append(prefix);
9768 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009769 }
9770 } else {
9771 dprintf(fd, "\n");
9772 }
9773 write(fd, result.string(), result.size());
9774}
9775
9776AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9777 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009778 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009779 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009780 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009781 mStreamVolume(1.0),
9782 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009783 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009784{
9785 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9786 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9787 mMasterVolume = audioFlinger->masterVolume_l();
9788 mMasterMute = audioFlinger->masterMute_l();
9789 if (mAudioHwDev) {
9790 if (mAudioHwDev->canSetMasterVolume()) {
9791 mMasterVolume = 1.0;
9792 }
9793
9794 if (mAudioHwDev->canSetMasterMute()) {
9795 mMasterMute = false;
9796 }
9797 }
9798}
9799
9800void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9801 audio_stream_type_t streamType,
9802 audio_session_t sessionId,
9803 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009804 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009805 audio_port_handle_t portId)
9806{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009807 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009808 mStreamType = streamType;
9809}
9810
9811AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9812{
9813 Mutex::Autolock _l(mLock);
9814 AudioStreamOut *output = mOutput;
9815 mOutput = NULL;
9816 return output;
9817}
9818
9819void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9820{
9821 Mutex::Autolock _l(mLock);
9822 // Don't apply master volume in SW if our HAL can do it for us.
9823 if (mAudioHwDev &&
9824 mAudioHwDev->canSetMasterVolume()) {
9825 mMasterVolume = 1.0;
9826 } else {
9827 mMasterVolume = value;
9828 }
9829}
9830
9831void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9832{
9833 Mutex::Autolock _l(mLock);
9834 // Don't apply master mute in SW if our HAL can do it for us.
9835 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9836 mMasterMute = false;
9837 } else {
9838 mMasterMute = muted;
9839 }
9840}
9841
9842void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9843{
9844 Mutex::Autolock _l(mLock);
9845 if (stream == mStreamType) {
9846 mStreamVolume = value;
9847 broadcast_l();
9848 }
9849}
9850
9851float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9852{
9853 Mutex::Autolock _l(mLock);
9854 if (stream == mStreamType) {
9855 return mStreamVolume;
9856 }
9857 return 0.0f;
9858}
9859
9860void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9861{
9862 Mutex::Autolock _l(mLock);
9863 if (stream == mStreamType) {
9864 mStreamMute= muted;
9865 broadcast_l();
9866 }
9867}
9868
9869void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9870{
9871 Mutex::Autolock _l(mLock);
9872 if (streamType == mStreamType) {
9873 for (const sp<MmapTrack> &track : mActiveTracks) {
9874 track->invalidate();
9875 }
9876 broadcast_l();
9877 }
9878}
9879
9880void AudioFlinger::MmapPlaybackThread::processVolume_l()
9881{
9882 float volume;
9883
9884 if (mMasterMute || mStreamMute) {
9885 volume = 0;
9886 } else {
9887 volume = mMasterVolume * mStreamVolume;
9888 }
9889
9890 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009891
9892 // Convert volumes from float to 8.24
9893 uint32_t vol = (uint32_t)(volume * (1 << 24));
9894
9895 // Delegate volume control to effect in track effect chain if needed
9896 // only one effect chain can be present on DirectOutputThread, so if
9897 // there is one, the track is connected to it
9898 if (!mEffectChains.isEmpty()) {
9899 mEffectChains[0]->setVolume_l(&vol, &vol);
9900 volume = (float)vol / (1 << 24);
9901 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009902 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009903 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9904 mHalVolFloat = volume; // HW volume control worked, so update value.
9905 mNoCallbackWarningCount = 0;
9906 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009907 sp<MmapStreamCallback> callback = mCallback.promote();
9908 if (callback != 0) {
9909 int channelCount;
9910 if (isOutput()) {
9911 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9912 } else {
9913 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9914 }
9915 Vector<float> values;
9916 for (int i = 0; i < channelCount; i++) {
9917 values.add(volume);
9918 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009919 mHalVolFloat = volume; // SW volume control worked, so update value.
9920 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009921 mLock.unlock();
9922 callback->onVolumeChanged(mChannelMask, values);
9923 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009924 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009925 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9926 ALOGW("Could not set MMAP stream volume: no volume callback!");
9927 mNoCallbackWarningCount++;
9928 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009929 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009930 }
9931 }
9932}
9933
Kevin Rocard069c2712018-03-29 19:09:14 -07009934void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9935{
9936 if (mOutput == nullptr || mOutput->stream == nullptr ||
9937 !mActiveTracks.readAndClearHasChanged()) {
9938 return;
9939 }
9940 StreamOutHalInterface::SourceMetadata metadata;
9941 for (const sp<MmapTrack> &track : mActiveTracks) {
9942 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01009943 playback_track_metadata_v7_t trackMetadata;
9944 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009945 .usage = track->attributes().usage,
9946 .content_type = track->attributes().content_type,
9947 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +01009948 };
9949 trackMetadata.channel_mask = track->channelMask(),
9950 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9951 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009952 }
9953 mOutput->stream->updateSourceMetadata(metadata);
9954}
9955
Eric Laurent6acd1d42017-01-04 14:23:29 -08009956void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9957{
9958 if (!mMasterMute) {
9959 char value[PROPERTY_VALUE_MAX];
9960 if (property_get("ro.audio.silent", value, "0") > 0) {
9961 char *endptr;
9962 unsigned long ul = strtoul(value, &endptr, 0);
9963 if (*endptr == '\0' && ul != 0) {
9964 ALOGD("Silence is golden");
9965 // The setprop command will not allow a property to be changed after
9966 // the first time it is set, so we don't have to worry about un-muting.
9967 setMasterMute_l(true);
9968 }
9969 }
9970 }
9971}
9972
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009973void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9974{
9975 MmapThread::toAudioPortConfig(config);
9976 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9977 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9978 config->flags.output = mOutput->flags;
9979 }
9980}
9981
jiabinb7d8c5a2020-08-26 17:24:52 -07009982status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
9983 int64_t *timeNanos)
9984{
9985 if (mOutput == nullptr) {
9986 return NO_INIT;
9987 }
9988 struct timespec timestamp;
9989 status_t status = mOutput->getPresentationPosition(position, &timestamp);
9990 if (status == NO_ERROR) {
9991 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
9992 }
9993 return status;
9994}
9995
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009996void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009997{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009998 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009999
Glenn Kastend3bb6452016-12-05 18:14:37 -080010000 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10001 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010002 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10003}
10004
10005AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10006 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010007 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010008 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010009 mInput(input)
10010{
10011 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10012 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10013}
10014
Eric Laurent331679c2018-04-16 17:03:16 -070010015status_t AudioFlinger::MmapCaptureThread::exitStandby()
10016{
Phil Burkf054fc32018-12-06 09:45:59 -080010017 {
10018 // mInput might have been cleared by clearInput()
10019 Mutex::Autolock _l(mLock);
10020 if (mInput != nullptr && mInput->stream != nullptr) {
10021 mInput->stream->setGain(1.0f);
10022 }
10023 }
Eric Laurent331679c2018-04-16 17:03:16 -070010024 return MmapThread::exitStandby();
10025}
10026
Eric Laurent6acd1d42017-01-04 14:23:29 -080010027AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10028{
10029 Mutex::Autolock _l(mLock);
10030 AudioStreamIn *input = mInput;
10031 mInput = NULL;
10032 return input;
10033}
Kevin Rocard069c2712018-03-29 19:09:14 -070010034
Eric Laurent331679c2018-04-16 17:03:16 -070010035
10036void AudioFlinger::MmapCaptureThread::processVolume_l()
10037{
10038 bool changed = false;
10039 bool silenced = false;
10040
10041 sp<MmapStreamCallback> callback = mCallback.promote();
10042 if (callback == 0) {
10043 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10044 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10045 mNoCallbackWarningCount++;
10046 }
10047 }
10048
10049 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10050 // track is silenced and unmute otherwise
10051 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10052 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10053 changed = true;
10054 silenced = mActiveTracks[i]->isSilenced_l();
10055 }
10056 }
10057
10058 if (changed) {
10059 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10060 }
10061}
10062
Kevin Rocard069c2712018-03-29 19:09:14 -070010063void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10064{
10065 if (mInput == nullptr || mInput->stream == nullptr ||
10066 !mActiveTracks.readAndClearHasChanged()) {
10067 return;
10068 }
10069 StreamInHalInterface::SinkMetadata metadata;
10070 for (const sp<MmapTrack> &track : mActiveTracks) {
10071 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010072 record_track_metadata_v7_t trackMetadata;
10073 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010074 .source = track->attributes().source,
10075 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010076 };
10077 trackMetadata.channel_mask = track->channelMask(),
10078 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10079 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010080 }
10081 mInput->stream->updateSinkMetadata(metadata);
10082}
10083
Eric Laurent5ada82e2019-08-29 17:53:54 -070010084void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010085{
10086 Mutex::Autolock _l(mLock);
10087 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010088 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010089 mActiveTracks[i]->setSilenced_l(silenced);
10090 broadcast_l();
10091 }
10092 }
10093}
10094
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010095void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10096{
10097 MmapThread::toAudioPortConfig(config);
10098 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10099 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10100 config->flags.input = mInput->flags;
10101 }
10102}
10103
jiabinb7d8c5a2020-08-26 17:24:52 -070010104status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10105 uint64_t *position, int64_t *timeNanos)
10106{
10107 if (mInput == nullptr) {
10108 return NO_INIT;
10109 }
10110 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10111}
10112
Glenn Kasten63238ef2015-03-02 15:50:29 -080010113} // namespace android