blob: 7f91a54bd868bf9c847082c664539d9b4dd2ca2c [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 Laurent1c333e22014-05-20 10:48:17 -0700703
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700704// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700705void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700706{
Eric Laurent10351942014-05-08 18:49:52 -0700707 bool configChanged = false;
708
Eric Laurent81784c32012-11-19 14:55:58 -0800709 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700710 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700711 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800712 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700713 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700714 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700715 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
716 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800717 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700718 true /*asynchronous*/);
719 if (err != 0) {
720 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700721 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700722 }
723 } break;
724 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700725 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700726 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700727 } break;
728 case CFG_EVENT_SET_PARAMETER: {
729 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
730 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
731 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700732 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
733 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700734 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700735 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700736 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700737 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700738 CreateAudioPatchConfigEventData *data =
739 (CreateAudioPatchConfigEventData *)event->mData.get();
740 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700741 const DeviceTypeSet newDevices = getDeviceTypes();
742 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
743 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
744 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700745 } break;
746 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700747 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700748 ReleaseAudioPatchConfigEventData *data =
749 (ReleaseAudioPatchConfigEventData *)event->mData.get();
750 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700751 const DeviceTypeSet newDevices = getDeviceTypes();
752 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
753 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
754 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
755 } break;
756 case CFG_EVENT_UPDATE_OUT_DEVICE: {
757 UpdateOutDevicesConfigEventData *data =
758 (UpdateOutDevicesConfigEventData *)event->mData.get();
759 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700760 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700761 default:
Eric Laurent10351942014-05-08 18:49:52 -0700762 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700763 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800764 }
Eric Laurent10351942014-05-08 18:49:52 -0700765 {
766 Mutex::Autolock _l(event->mLock);
767 if (event->mWaitStatus) {
768 event->mWaitStatus = false;
769 event->mCond.signal();
770 }
771 }
772 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
773 }
774
775 if (configChanged) {
776 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800777 }
Eric Laurent81784c32012-11-19 14:55:58 -0800778}
779
Marco Nelissenb2208842014-02-07 14:00:50 -0800780String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
781 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700782 const audio_channel_representation_t representation =
783 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700784
785 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800786 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700787 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
788 if (output) {
789 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
790 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
791 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
792 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
793 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
794 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
795 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
796 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
797 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
798 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
799 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
800 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
801 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
802 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
803 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
804 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
805 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
806 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700807 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
808 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800809 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
810 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700811 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
812 } else {
813 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
814 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
815 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
816 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
817 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
818 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
819 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
820 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
821 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
822 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
823 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
824 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700825 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
826 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
827 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
828 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
829 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
830 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700831 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
832 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
833 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
834 }
835 const int len = s.length();
836 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700837 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700838 s.unlockBuffer(len - 2); // remove trailing ", "
839 }
840 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800841 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700842 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
843 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
844 return s;
845 default:
846 s.appendFormat("unknown mask, representation:%d bits:%#x",
847 representation, audio_channel_mask_get_bits(mask));
848 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800849 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800850}
851
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700852void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800853{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800854 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
855 this, mThreadName, getTid(), type(), threadTypeToString(type()));
856
Eric Laurent81784c32012-11-19 14:55:58 -0800857 bool locked = AudioFlinger::dumpTryLock(mLock);
858 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800859 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800860 }
861
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700862 dumpBase_l(fd, args);
863 dumpInternals_l(fd, args);
864 dumpTracks_l(fd, args);
865 dumpEffectChains_l(fd, args);
866
867 if (locked) {
868 mLock.unlock();
869 }
870
871 dprintf(fd, " Local log:\n");
872 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
873}
874
875void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
876{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700877 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700878 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700879 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700880 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700881 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700882 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700883 dprintf(fd, " Channel count: %u\n", mChannelCount);
884 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800885 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700886 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700887 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700888 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800889 size_t numConfig = mConfigEvents.size();
890 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700891 const size_t SIZE = 256;
892 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800893 for (size_t i = 0; i < numConfig; i++) {
894 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700895 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800896 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700897 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800898 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700899 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800900 }
Andy Hung293558a2017-03-21 12:19:20 -0700901 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700902 dprintf(fd, " Output devices: %s (%s)\n",
903 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
904 dprintf(fd, " Input device: %#x (%s)\n",
905 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800906 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800907
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700908 // Dump timestamp statistics for the Thread types that support it.
909 if (mType == RECORD
910 || mType == MIXER
911 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700912 || mType == DIRECT
913 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700914 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700915 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700916 }
917
Andy Hung446f4df2019-02-21 12:26:41 -0800918 if (mLastIoBeginNs > 0) { // MMAP may not set this
919 dprintf(fd, " Last %s occurred (msecs): %lld\n",
920 isOutput() ? "write" : "read",
921 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
922 }
923
924 if (mProcessTimeMs.getN() > 0) {
925 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
926 }
927
928 if (mIoJitterMs.getN() > 0) {
929 dprintf(fd, " Hal %s jitter ms stats: %s\n",
930 isOutput() ? "write" : "read",
931 mIoJitterMs.toString().c_str());
932 }
933
Andy Hunge6c37112019-02-26 17:38:10 -0800934 if (mLatencyMs.getN() > 0) {
935 dprintf(fd, " Threadloop %s latency stats: %s\n",
936 isOutput() ? "write" : "read",
937 mLatencyMs.toString().c_str());
938 }
Eric Laurent81784c32012-11-19 14:55:58 -0800939}
940
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700941void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800942{
943 const size_t SIZE = 256;
944 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800945
Marco Nelissenb2208842014-02-07 14:00:50 -0800946 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000947 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800948 write(fd, buffer, strlen(buffer));
949
Marco Nelissenb2208842014-02-07 14:00:50 -0800950 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800951 sp<EffectChain> chain = mEffectChains[i];
952 if (chain != 0) {
953 chain->dump(fd, args);
954 }
955 }
956}
957
Andy Hungdae27702016-10-31 14:01:16 -0700958void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800959{
960 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700961 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800962}
963
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100964String16 AudioFlinger::ThreadBase::getWakeLockTag()
965{
966 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800967 case MIXER:
968 return String16("AudioMix");
969 case DIRECT:
970 return String16("AudioDirectOut");
971 case DUPLICATING:
972 return String16("AudioDup");
973 case RECORD:
974 return String16("AudioIn");
975 case OFFLOAD:
976 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -0700977 case MMAP_PLAYBACK:
978 return String16("MmapPlayback");
979 case MMAP_CAPTURE:
980 return String16("MmapCapture");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800981 default:
982 ALOG_ASSERT(false);
983 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100984 }
985}
986
Andy Hungdae27702016-10-31 14:01:16 -0700987void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800988{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800989 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800990 if (mPowerManager != 0) {
991 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700992 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -0800993 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
994 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100995 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700996 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -0800997 {} /* workSource */,
998 {} /* historyTag */);
999 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001000 mWakeLockToken = binder;
1001 }
Chris Ye6597d732020-02-28 22:38:25 -08001002 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001003 }
Wei Jia3f273d12015-11-24 09:06:49 -08001004
Andy Hung3f0c9022016-01-15 17:49:46 -08001005 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001006 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1007 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001008}
1009
1010void AudioFlinger::ThreadBase::releaseWakeLock()
1011{
1012 Mutex::Autolock _l(mLock);
1013 releaseWakeLock_l();
1014}
1015
1016void AudioFlinger::ThreadBase::releaseWakeLock_l()
1017{
Andy Hung3f0c9022016-01-15 17:49:46 -08001018 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001019 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001020 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001021 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001022 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001023 }
1024 mWakeLockToken.clear();
1025 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001026}
1027
1028void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001029 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001030 // use checkService() to avoid blocking if power service is not up yet
1031 sp<IBinder> binder =
1032 defaultServiceManager()->checkService(String16("power"));
1033 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001034 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001035 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001036 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001037 binder->linkToDeath(mDeathRecipient);
1038 }
1039 }
1040}
1041
Andy Hungd01b0f12016-11-07 16:10:30 -08001042void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001043 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001044
1045#if !LOG_NDEBUG
1046 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001047 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001048 s << uid << " ";
1049 }
1050 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1051#endif
1052
Andy Hung438e7572015-12-14 15:51:17 -08001053 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1054 if (mSystemReady) {
1055 ALOGE("no wake lock to update, but system ready!");
1056 } else {
1057 ALOGW("no wake lock to update, system not ready yet");
1058 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001059 return;
1060 }
1061 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001062 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001063 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1064 mWakeLockToken, uidsAsInt);
1065 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001066 }
1067}
1068
Eric Laurent81784c32012-11-19 14:55:58 -08001069void AudioFlinger::ThreadBase::clearPowerManager()
1070{
1071 Mutex::Autolock _l(mLock);
1072 releaseWakeLock_l();
1073 mPowerManager.clear();
1074}
1075
jiabinc52b1ff2019-10-31 17:20:42 -07001076void AudioFlinger::ThreadBase::updateOutDevices(
1077 const DeviceDescriptorBaseVector& outDevices __unused)
1078{
1079 ALOGE("%s should only be called in RecordThread", __func__);
1080}
1081
Glenn Kasten0f11b512014-01-31 16:18:54 -08001082void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001083{
1084 sp<ThreadBase> thread = mThread.promote();
1085 if (thread != 0) {
1086 thread->clearPowerManager();
1087 }
1088 ALOGW("power manager service died !!!");
1089}
1090
Eric Laurent81784c32012-11-19 14:55:58 -08001091void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001092 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001093{
1094 sp<EffectChain> chain = getEffectChain_l(sessionId);
1095 if (chain != 0) {
1096 if (type != NULL) {
1097 chain->setEffectSuspended_l(type, suspend);
1098 } else {
1099 chain->setEffectSuspendedAll_l(suspend);
1100 }
1101 }
1102
1103 updateSuspendedSessions_l(type, suspend, sessionId);
1104}
1105
1106void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1107{
1108 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1109 if (index < 0) {
1110 return;
1111 }
1112
1113 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1114 mSuspendedSessions.valueAt(index);
1115
1116 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001117 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001118 for (int j = 0; j < desc->mRefCount; j++) {
1119 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1120 chain->setEffectSuspendedAll_l(true);
1121 } else {
1122 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1123 desc->mType.timeLow);
1124 chain->setEffectSuspended_l(&desc->mType, true);
1125 }
1126 }
1127 }
1128}
1129
1130void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1131 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001132 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001133{
1134 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1135
1136 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1137
1138 if (suspend) {
1139 if (index >= 0) {
1140 sessionEffects = mSuspendedSessions.valueAt(index);
1141 } else {
1142 mSuspendedSessions.add(sessionId, sessionEffects);
1143 }
1144 } else {
1145 if (index < 0) {
1146 return;
1147 }
1148 sessionEffects = mSuspendedSessions.valueAt(index);
1149 }
1150
1151
1152 int key = EffectChain::kKeyForSuspendAll;
1153 if (type != NULL) {
1154 key = type->timeLow;
1155 }
1156 index = sessionEffects.indexOfKey(key);
1157
1158 sp<SuspendedSessionDesc> desc;
1159 if (suspend) {
1160 if (index >= 0) {
1161 desc = sessionEffects.valueAt(index);
1162 } else {
1163 desc = new SuspendedSessionDesc();
1164 if (type != NULL) {
1165 desc->mType = *type;
1166 }
1167 sessionEffects.add(key, desc);
1168 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1169 }
1170 desc->mRefCount++;
1171 } else {
1172 if (index < 0) {
1173 return;
1174 }
1175 desc = sessionEffects.valueAt(index);
1176 if (--desc->mRefCount == 0) {
1177 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1178 sessionEffects.removeItemsAt(index);
1179 if (sessionEffects.isEmpty()) {
1180 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1181 sessionId);
1182 mSuspendedSessions.removeItem(sessionId);
1183 }
1184 }
1185 }
1186 if (!sessionEffects.isEmpty()) {
1187 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1188 }
1189}
1190
Eric Laurent6b446ce2019-12-13 10:56:31 -08001191void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1192 audio_session_t sessionId,
1193 bool threadLocked) {
1194 if (!threadLocked) {
1195 mLock.lock();
1196 }
Eric Laurent81784c32012-11-19 14:55:58 -08001197
Eric Laurent81784c32012-11-19 14:55:58 -08001198 if (mType != RECORD) {
1199 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1200 // another session. This gives the priority to well behaved effect control panels
1201 // and applications not using global effects.
1202 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1203 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001204 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001205 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1206 }
1207 }
1208
Eric Laurent6b446ce2019-12-13 10:56:31 -08001209 if (!threadLocked) {
1210 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001211 }
1212}
1213
Eric Laurent4c415062016-06-17 16:14:16 -07001214// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1215status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1216 const effect_descriptor_t *desc, audio_session_t sessionId)
1217{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001218 // No global output effect sessions on record threads
1219 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1220 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001221 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1222 desc->name, mThreadName);
1223 return BAD_VALUE;
1224 }
1225 // only pre processing effects on record thread
1226 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1227 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1228 desc->name, mThreadName);
1229 return BAD_VALUE;
1230 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001231
1232 // always allow effects without processing load or latency
1233 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1234 return NO_ERROR;
1235 }
1236
Eric Laurent4c415062016-06-17 16:14:16 -07001237 audio_input_flags_t flags = mInput->flags;
1238 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1239 if (flags & AUDIO_INPUT_FLAG_RAW) {
1240 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1241 desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1245 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1246 desc->name, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 }
jiabineb3bda02020-06-30 14:07:03 -07001250
1251 if (EffectModule::isHapticGenerator(&desc->type)) {
1252 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1253 return BAD_VALUE;
1254 }
Eric Laurent4c415062016-06-17 16:14:16 -07001255 return NO_ERROR;
1256}
1257
1258// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1259status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1260 const effect_descriptor_t *desc, audio_session_t sessionId)
1261{
1262 // no preprocessing on playback threads
1263 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1264 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1265 " thread %s", desc->name, mThreadName);
1266 return BAD_VALUE;
1267 }
1268
Eric Laurent3e4de772017-07-16 16:55:08 -07001269 // always allow effects without processing load or latency
1270 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1271 return NO_ERROR;
1272 }
1273
jiabineb3bda02020-06-30 14:07:03 -07001274 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1275 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1276 __func__);
1277 return BAD_VALUE;
1278 }
1279
Eric Laurent4c415062016-06-17 16:14:16 -07001280 switch (mType) {
1281 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001282#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001283 // Reject any effect on mixer multichannel sinks.
1284 // TODO: fix both format and multichannel issues with effects.
1285 if (mChannelCount != FCC_2) {
1286 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1287 " thread %s", desc->name, mChannelCount, mThreadName);
1288 return BAD_VALUE;
1289 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001290#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001291 audio_output_flags_t flags = mOutput->flags;
1292 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1293 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1294 // global effects are applied only to non fast tracks if they are SW
1295 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1296 break;
1297 }
1298 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1299 // only post processing on output stage session
1300 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1301 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1302 " on output stage session", desc->name);
1303 return BAD_VALUE;
1304 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001305 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1306 // only post processing on output stage session
1307 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1308 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1309 " on device session", desc->name);
1310 return BAD_VALUE;
1311 }
Eric Laurent4c415062016-06-17 16:14:16 -07001312 } else {
1313 // no restriction on effects applied on non fast tracks
1314 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1315 break;
1316 }
1317 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001318
Eric Laurent4c415062016-06-17 16:14:16 -07001319 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1320 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1321 desc->name);
1322 return BAD_VALUE;
1323 }
1324 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1325 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1326 " in fast mode", desc->name);
1327 return BAD_VALUE;
1328 }
1329 }
1330 } break;
1331 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001332 // nothing actionable on offload threads, if the effect:
1333 // - is offloadable: the effect can be created
1334 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1335 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001336 break;
1337 case DIRECT:
1338 // Reject any effect on Direct output threads for now, since the format of
1339 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1340 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1341 desc->name, mThreadName);
1342 return BAD_VALUE;
1343 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001344#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001345 // Reject any effect on mixer multichannel sinks.
1346 // TODO: fix both format and multichannel issues with effects.
1347 if (mChannelCount != FCC_2) {
1348 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1349 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1350 return BAD_VALUE;
1351 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001352#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001353 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001354 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1355 " thread %s", desc->name, mThreadName);
1356 return BAD_VALUE;
1357 }
1358 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1359 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1360 " DUPLICATING thread %s", desc->name, mThreadName);
1361 return BAD_VALUE;
1362 }
1363 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1364 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1365 " DUPLICATING thread %s", desc->name, mThreadName);
1366 return BAD_VALUE;
1367 }
1368 break;
1369 default:
1370 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1371 }
1372
1373 return NO_ERROR;
1374}
1375
Eric Laurent81784c32012-11-19 14:55:58 -08001376// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1377sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1378 const sp<AudioFlinger::Client>& client,
1379 const sp<IEffectClient>& effectClient,
1380 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001381 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001382 effect_descriptor_t *desc,
1383 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001384 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001385 bool pinned,
1386 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001387{
1388 sp<EffectModule> effect;
1389 sp<EffectHandle> handle;
1390 status_t lStatus;
1391 sp<EffectChain> chain;
1392 bool chainCreated = false;
1393 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001394 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001395
1396 lStatus = initCheck();
1397 if (lStatus != NO_ERROR) {
1398 ALOGW("createEffect_l() Audio driver not initialized.");
1399 goto Exit;
1400 }
1401
Eric Laurent81784c32012-11-19 14:55:58 -08001402 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1403
1404 { // scope for mLock
1405 Mutex::Autolock _l(mLock);
1406
Eric Laurent4c415062016-06-17 16:14:16 -07001407 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001408 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001409 goto Exit;
1410 }
1411
Eric Laurent81784c32012-11-19 14:55:58 -08001412 // check for existing effect chain with the requested audio session
1413 chain = getEffectChain_l(sessionId);
1414 if (chain == 0) {
1415 // create a new chain for this session
1416 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1417 chain = new EffectChain(this, sessionId);
1418 addEffectChain_l(chain);
1419 chain->setStrategy(getStrategyForSession_l(sessionId));
1420 chainCreated = true;
1421 } else {
1422 effect = chain->getEffectFromDesc_l(desc);
1423 }
1424
1425 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1426
1427 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001428 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001429 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001430 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001431 if (lStatus != NO_ERROR) {
1432 goto Exit;
1433 }
1434 effectCreated = true;
1435
jiabinc52b1ff2019-10-31 17:20:42 -07001436 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001437 effect->setDevices(outDeviceTypeAddrs());
1438 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001439 effect->setMode(mAudioFlinger->getMode());
1440 effect->setAudioSource(mAudioSource);
1441 }
1442 // create effect handle and connect it to effect module
1443 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001444 lStatus = handle->initCheck();
1445 if (lStatus == OK) {
1446 lStatus = effect->addHandle(handle.get());
1447 }
Eric Laurent81784c32012-11-19 14:55:58 -08001448 if (enabled != NULL) {
1449 *enabled = (int)effect->isEnabled();
1450 }
1451 }
1452
1453Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001454 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001455 Mutex::Autolock _l(mLock);
1456 if (effectCreated) {
1457 chain->removeEffect_l(effect);
1458 }
Eric Laurent81784c32012-11-19 14:55:58 -08001459 if (chainCreated) {
1460 removeEffectChain_l(chain);
1461 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001462 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001463 }
1464
Glenn Kasten9156ef32013-08-06 15:39:08 -07001465 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001466 return handle;
1467}
1468
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001469void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1470 bool unpinIfLast)
1471{
1472 bool remove = false;
1473 sp<EffectModule> effect;
1474 {
1475 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001476 sp<EffectBase> effectBase = handle->effect().promote();
1477 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001478 return;
1479 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001480 effect = effectBase->asEffectModule();
1481 if (effect == nullptr) {
1482 return;
1483 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001484 // restore suspended effects if the disconnected handle was enabled and the last one.
1485 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1486 if (remove) {
1487 removeEffect_l(effect, true);
1488 }
1489 }
1490 if (remove) {
1491 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001492 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001493 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001494 }
1495 }
1496}
1497
Eric Laurent6b446ce2019-12-13 10:56:31 -08001498void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001499 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001500 Mutex::Autolock _l(mLock);
1501 broadcast_l();
1502 }
1503 if (!effect->isOffloadable()) {
1504 if (mType == ThreadBase::OFFLOAD) {
1505 PlaybackThread *t = (PlaybackThread *)this;
1506 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1507 }
1508 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1509 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1510 }
1511 }
1512}
1513
1514void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001515 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001516 Mutex::Autolock _l(mLock);
1517 broadcast_l();
1518 }
1519}
1520
Glenn Kastend848eb42016-03-08 13:42:11 -08001521sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1522 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001523{
1524 Mutex::Autolock _l(mLock);
1525 return getEffect_l(sessionId, effectId);
1526}
1527
Glenn Kastend848eb42016-03-08 13:42:11 -08001528sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1529 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001530{
1531 sp<EffectChain> chain = getEffectChain_l(sessionId);
1532 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1533}
1534
Eric Laurent6c796322019-04-09 14:13:17 -07001535std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1536{
1537 sp<EffectChain> chain = getEffectChain_l(sessionId);
1538 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1539}
1540
Eric Laurent81784c32012-11-19 14:55:58 -08001541// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1542// PlaybackThread::mLock held
1543status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1544{
1545 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001546 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001547 sp<EffectChain> chain = getEffectChain_l(sessionId);
1548 bool chainCreated = false;
1549
Eric Laurent5baf2af2013-09-12 17:37:00 -07001550 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001551 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001552 this, effect->desc().name, effect->desc().flags);
1553
Eric Laurent81784c32012-11-19 14:55:58 -08001554 if (chain == 0) {
1555 // create a new chain for this session
1556 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1557 chain = new EffectChain(this, sessionId);
1558 addEffectChain_l(chain);
1559 chain->setStrategy(getStrategyForSession_l(sessionId));
1560 chainCreated = true;
1561 }
1562 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1563
1564 if (chain->getEffectFromId_l(effect->id()) != 0) {
1565 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1566 this, effect->desc().name, chain.get());
1567 return BAD_VALUE;
1568 }
1569
Eric Laurent5baf2af2013-09-12 17:37:00 -07001570 effect->setOffloaded(mType == OFFLOAD, mId);
1571
Eric Laurent81784c32012-11-19 14:55:58 -08001572 status_t status = chain->addEffect_l(effect);
1573 if (status != NO_ERROR) {
1574 if (chainCreated) {
1575 removeEffectChain_l(chain);
1576 }
1577 return status;
1578 }
1579
jiabin8f278ee2019-11-11 12:16:27 -08001580 effect->setDevices(outDeviceTypeAddrs());
1581 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001582 effect->setMode(mAudioFlinger->getMode());
1583 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001584
Eric Laurent81784c32012-11-19 14:55:58 -08001585 return NO_ERROR;
1586}
1587
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001588void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001589
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001590 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001591 effect_descriptor_t desc = effect->desc();
1592 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1593 detachAuxEffect_l(effect->id());
1594 }
1595
Eric Laurent6b446ce2019-12-13 10:56:31 -08001596 sp<EffectChain> chain = effect->callback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001597 if (chain != 0) {
1598 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001599 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001600 removeEffectChain_l(chain);
1601 }
1602 } else {
1603 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1604 }
1605}
1606
1607void AudioFlinger::ThreadBase::lockEffectChains_l(
1608 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1609{
1610 effectChains = mEffectChains;
1611 for (size_t i = 0; i < mEffectChains.size(); i++) {
1612 mEffectChains[i]->lock();
1613 }
1614}
1615
1616void AudioFlinger::ThreadBase::unlockEffectChains(
1617 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1618{
1619 for (size_t i = 0; i < effectChains.size(); i++) {
1620 effectChains[i]->unlock();
1621 }
1622}
1623
Glenn Kastend848eb42016-03-08 13:42:11 -08001624sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001625{
1626 Mutex::Autolock _l(mLock);
1627 return getEffectChain_l(sessionId);
1628}
1629
Glenn Kastend848eb42016-03-08 13:42:11 -08001630sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1631 const
Eric Laurent81784c32012-11-19 14:55:58 -08001632{
1633 size_t size = mEffectChains.size();
1634 for (size_t i = 0; i < size; i++) {
1635 if (mEffectChains[i]->sessionId() == sessionId) {
1636 return mEffectChains[i];
1637 }
1638 }
1639 return 0;
1640}
1641
1642void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1643{
1644 Mutex::Autolock _l(mLock);
1645 size_t size = mEffectChains.size();
1646 for (size_t i = 0; i < size; i++) {
1647 mEffectChains[i]->setMode_l(mode);
1648 }
1649}
1650
Mikhail Naganovdc769682018-05-04 15:34:08 -07001651void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001652{
1653 config->type = AUDIO_PORT_TYPE_MIX;
1654 config->ext.mix.handle = mId;
1655 config->sample_rate = mSampleRate;
1656 config->format = mFormat;
1657 config->channel_mask = mChannelMask;
1658 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1659 AUDIO_PORT_CONFIG_FORMAT;
1660}
1661
Eric Laurent72e3f392015-05-20 14:43:50 -07001662void AudioFlinger::ThreadBase::systemReady()
1663{
1664 Mutex::Autolock _l(mLock);
1665 if (mSystemReady) {
1666 return;
1667 }
1668 mSystemReady = true;
1669
1670 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1671 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1672 }
1673 mPendingConfigEvents.clear();
1674}
1675
Andy Hungdae27702016-10-31 14:01:16 -07001676template <typename T>
1677ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1678 ssize_t index = mActiveTracks.indexOf(track);
1679 if (index >= 0) {
1680 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1681 return index;
1682 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001683 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001684 mActiveTracksGeneration++;
1685 mLatestActiveTrack = track;
1686 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001687 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001688 return mActiveTracks.add(track);
1689}
1690
1691template <typename T>
1692ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1693 ssize_t index = mActiveTracks.remove(track);
1694 if (index < 0) {
1695 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1696 return index;
1697 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001698 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001699 mActiveTracksGeneration++;
1700 --mBatteryCounter[track->uid()].second;
1701 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001702 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001703#ifdef TEE_SINK
1704 track->dumpTee(-1 /* fd */, "_REMOVE");
1705#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001706 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001707 return index;
1708}
1709
1710template <typename T>
1711void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1712 for (const sp<T> &track : mActiveTracks) {
1713 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001714 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001715 }
1716 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001717 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001718 mActiveTracks.clear();
1719 mLatestActiveTrack.clear();
1720 mBatteryCounter.clear();
1721}
1722
1723template <typename T>
1724void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1725 sp<ThreadBase> thread, bool force) {
1726 // Updates ActiveTracks client uids to the thread wakelock.
1727 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1728 thread->updateWakeLockUids_l(getWakeLockUids());
1729 mLastActiveTracksGeneration = mActiveTracksGeneration;
1730 }
1731
1732 // Updates BatteryNotifier uids
1733 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1734 const uid_t uid = it->first;
1735 ssize_t &previous = it->second.first;
1736 ssize_t &current = it->second.second;
1737 if (current > 0) {
1738 if (previous == 0) {
1739 BatteryNotifier::getInstance().noteStartAudio(uid);
1740 }
1741 previous = current;
1742 ++it;
1743 } else if (current == 0) {
1744 if (previous > 0) {
1745 BatteryNotifier::getInstance().noteStopAudio(uid);
1746 }
1747 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1748 } else /* (current < 0) */ {
1749 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1750 }
1751 }
1752}
Eric Laurent83b88082014-06-20 18:31:16 -07001753
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001754template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001755bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1756 const bool hasChanged = mHasChanged;
1757 mHasChanged = false;
1758 return hasChanged;
1759}
1760
1761template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001762void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1763 const char *funcName, const sp<T> &track) const {
1764 if (mLocalLog != nullptr) {
1765 String8 result;
1766 track->appendDump(result, false /* active */);
1767 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1768 }
1769}
1770
Eric Laurent6acd1d42017-01-04 14:23:29 -08001771void AudioFlinger::ThreadBase::broadcast_l()
1772{
1773 // Thread could be blocked waiting for async
1774 // so signal it to handle state changes immediately
1775 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1776 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1777 mSignalPending = true;
1778 mWaitWorkCV.broadcast();
1779}
1780
Andy Hungd0979812019-02-21 15:51:44 -08001781// Call only from threadLoop() or when it is idle.
1782// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1783void AudioFlinger::ThreadBase::sendStatistics(bool force)
1784{
1785 // Do not log if we have no stats.
1786 // We choose the timestamp verifier because it is the most likely item to be present.
1787 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1788 if (nstats == 0) {
1789 return;
1790 }
1791
1792 // Don't log more frequently than once per 12 hours.
1793 // We use BOOTTIME to include suspend time.
1794 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1795 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1796 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1797 return;
1798 }
1799
1800 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1801 mLastRecordedTimeNs = timeNs;
1802
Ray Essickf27e9872019-12-07 06:28:46 -08001803 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001804
1805#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1806
1807 // thread configuration
1808 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1809 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1810 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1811 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1812 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1813 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1814 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001815 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1816 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001817
1818 // thread statistics
1819 if (mIoJitterMs.getN() > 0) {
1820 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1821 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1822 }
1823 if (mProcessTimeMs.getN() > 0) {
1824 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1825 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1826 }
1827 const auto tsjitter = mTimestampVerifier.getJitterMs();
1828 if (tsjitter.getN() > 0) {
1829 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1830 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1831 }
1832 if (mLatencyMs.getN() > 0) {
1833 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1834 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1835 }
1836
1837 item->selfrecord();
1838}
1839
Eric Laurent81784c32012-11-19 14:55:58 -08001840// ----------------------------------------------------------------------------
1841// Playback
1842// ----------------------------------------------------------------------------
1843
1844AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1845 AudioStreamOut* output,
1846 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001847 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001848 bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07001849 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001850 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001851 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001852 mMixerBuffer(NULL),
1853 mMixerBufferSize(0),
1854 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1855 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001856 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001857 mEffectBuffer(NULL),
1858 mEffectBufferSize(0),
1859 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1860 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001861 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001862 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001863 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001864 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001865 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001866 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001867 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001868 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001869 mMixerStatus(MIXER_IDLE),
1870 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001871 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001872 mBytesRemaining(0),
1873 mCurrentWriteLength(0),
1874 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001875 mWriteAckSequence(0),
1876 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001877 mScreenState(AudioFlinger::mScreenState),
1878 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001879 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001880 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001881 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1882 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001883{
Glenn Kastend7dca052015-03-05 16:05:54 -08001884 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1885 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001886
1887 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1888 // it would be safer to explicitly pass initial masterVolume/masterMute as
1889 // parameter.
1890 //
1891 // If the HAL we are using has support for master volume or master mute,
1892 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1893 // and the mute set to false).
1894 mMasterVolume = audioFlinger->masterVolume_l();
1895 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001896 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001897 if (mOutput->audioHwDev->canSetMasterVolume()) {
1898 mMasterVolume = 1.0;
1899 }
1900
1901 if (mOutput->audioHwDev->canSetMasterMute()) {
1902 mMasterMute = false;
1903 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001904 mIsMsdDevice = strcmp(
1905 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001906 }
1907
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001908 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001909
Andy Hungc8fddf32018-08-08 18:32:37 -07001910 // TODO: We may also match on address as well as device type for
1911 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001912 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001913 // TODO: This property should be ensure that only contains one single device type.
1914 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1915 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001916 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1917 : AUDIO_DEVICE_NONE));
1918 }
1919
Mikhail Naganovf33115d2020-09-25 23:03:05 +00001920 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1921 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08001922 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001923 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1924 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001925 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001926 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1927 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001928 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1929 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001930}
1931
1932AudioFlinger::PlaybackThread::~PlaybackThread()
1933{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001934 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001935 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001936 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001937 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001938}
1939
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001940// Thread virtuals
1941
1942void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001943{
jiabinf6eb4c32020-02-25 14:06:25 -08001944 if (mOutput == nullptr || mOutput->stream == nullptr) {
1945 ALOGE("The stream is not open yet"); // This should not happen.
1946 } else {
1947 // setEventCallback will need a strong pointer as a parameter. Calling it
1948 // here instead of constructor of PlaybackThread so that the onFirstRef
1949 // callback would not be made on an incompletely constructed object.
1950 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07001951 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08001952 }
1953 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001954 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001955}
1956
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001957// ThreadBase virtuals
1958void AudioFlinger::PlaybackThread::preExit()
1959{
1960 ALOGV(" preExit()");
1961 // FIXME this is using hard-coded strings but in the future, this functionality will be
1962 // converted to use audio HAL extensions required to support tunneling
1963 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1964 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1965}
1966
1967void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001968{
Eric Laurent81784c32012-11-19 14:55:58 -08001969 String8 result;
1970
Marco Nelissenb2208842014-02-07 14:00:50 -08001971 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001972 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1973 const stream_type_t *st = &mStreamTypes[i];
1974 if (i > 0) {
1975 result.appendFormat(", ");
1976 }
1977 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1978 if (st->mute) {
1979 result.append("M");
1980 }
1981 }
1982 result.append("\n");
1983 write(fd, result.string(), result.length());
1984 result.clear();
1985
Eric Laurent81784c32012-11-19 14:55:58 -08001986 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1987 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001988 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001989 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001990
1991 size_t numtracks = mTracks.size();
1992 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001993 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001994 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001995 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001996 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001997 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001998 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001999 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002000 for (size_t i = 0; i < numtracks; ++i) {
2001 sp<Track> track = mTracks[i];
2002 if (track != 0) {
2003 bool active = mActiveTracks.indexOf(track) >= 0;
2004 if (active) {
2005 numactiveseen++;
2006 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002007 result.append(prefix);
2008 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002009 }
2010 }
2011 } else {
2012 result.append("\n");
2013 }
2014 if (numactiveseen != numactive) {
2015 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002016 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002017 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002018 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002019 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002020 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002021 sp<Track> track = mActiveTracks[i];
2022 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002023 result.append(prefix);
2024 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002025 }
2026 }
2027 }
2028
2029 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002030}
2031
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002032void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002033{
Andy Hung04cb8f72020-03-20 13:44:33 -07002034 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002035 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002036 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2037 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2038 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2039 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002040 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002041 dprintf(fd, " Total writes: %d\n", mNumWrites);
2042 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2043 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2044 dprintf(fd, " Suspend count: %d\n", mSuspended);
2045 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2046 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2047 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2048 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002049 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002050 AudioStreamOut *output = mOutput;
2051 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002052 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002053 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002054 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2055 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2056 if (mPipeSink.get() != nullptr) {
2057 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2058 }
2059 if (output != nullptr) {
2060 dprintf(fd, " Hal stream dump:\n");
2061 (void)output->stream->dump(fd);
2062 }
Eric Laurent81784c32012-11-19 14:55:58 -08002063}
2064
Eric Laurent81784c32012-11-19 14:55:58 -08002065// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2066sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2067 const sp<AudioFlinger::Client>& client,
2068 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002069 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002070 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002071 audio_format_t format,
2072 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002073 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002074 size_t *pNotificationFrameCount,
2075 uint32_t notificationsPerBuffer,
2076 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002077 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002078 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002079 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002080 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002081 const Identity& identity,
Eric Laurent81784c32012-11-19 14:55:58 -08002082 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002083 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002084 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002085 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002086{
Glenn Kasten74935e42013-12-19 08:56:45 -08002087 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002088 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002089 sp<Track> track;
2090 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002091 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002092 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002093 uint32_t sampleRate;
2094
2095 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2096 lStatus = BAD_VALUE;
2097 goto Exit;
2098 }
Eric Laurent21da6472017-11-09 16:29:26 -08002099
2100 if (*pSampleRate == 0) {
2101 *pSampleRate = mSampleRate;
2102 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002103 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002104
2105 // special case for FAST flag considered OK if fast mixer is present
2106 if (hasFastMixer()) {
2107 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2108 }
2109
2110 // Check if requested flags are compatible with output stream flags
2111 if ((*flags & outputFlags) != *flags) {
2112 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2113 *flags, outputFlags);
2114 *flags = (audio_output_flags_t)(*flags & outputFlags);
2115 }
Eric Laurent81784c32012-11-19 14:55:58 -08002116
Eric Laurent81784c32012-11-19 14:55:58 -08002117 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002118 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002119 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002120 // PCM data
2121 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002122 // TODO: extract as a data library function that checks that a computationally
2123 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002124 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002125 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2126 (channelMask == AUDIO_CHANNEL_OUT_MONO
2127 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002128 // hardware sample rate
2129 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002130 // normal mixer has an associated fast mixer
2131 hasFastMixer() &&
2132 // there are sufficient fast track slots available
2133 (mFastTrackAvailMask != 0)
2134 // FIXME test that MixerThread for this fast track has a capable output HAL
2135 // FIXME add a permission test also?
2136 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002137 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2138 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002139 // read the fast track multiplier property the first time it is needed
2140 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2141 if (ok != 0) {
2142 ALOGE("%s pthread_once failed: %d", __func__, ok);
2143 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002144 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002145 }
Eric Laurent4c415062016-06-17 16:14:16 -07002146
2147 // check compatibility with audio effects.
2148 { // scope for mLock
2149 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002150 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002151 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002152 AUDIO_SESSION_OUTPUT_STAGE,
2153 AUDIO_SESSION_OUTPUT_MIX,
2154 sessionId,
2155 }) {
2156 sp<EffectChain> chain = getEffectChain_l(session);
2157 if (chain.get() != nullptr) {
2158 audio_output_flags_t old = *flags;
2159 chain->checkOutputFlagCompatibility(flags);
2160 if (old != *flags) {
2161 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2162 (int)session, (int)old, (int)*flags);
2163 }
Eric Laurent4c415062016-06-17 16:14:16 -07002164 }
2165 }
2166 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002167 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002168 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2169 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002170 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002171 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2172 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002173 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002174 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002175 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002176 audio_is_linear_pcm(format), channelMask, sampleRate,
2177 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002178 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002179 }
2180 }
Eric Laurent21da6472017-11-09 16:29:26 -08002181
2182 if (!audio_has_proportional_frames(format)) {
2183 if (sharedBuffer != 0) {
2184 // Same comment as below about ignoring frameCount parameter for set()
2185 frameCount = sharedBuffer->size();
2186 } else if (frameCount == 0) {
2187 frameCount = mNormalFrameCount;
2188 }
2189 if (notificationFrameCount != frameCount) {
2190 notificationFrameCount = frameCount;
2191 }
2192 } else if (sharedBuffer != 0) {
2193 // FIXME: Ensure client side memory buffers need
2194 // not have additional alignment beyond sample
2195 // (e.g. 16 bit stereo accessed as 32 bit frame).
2196 size_t alignment = audio_bytes_per_sample(format);
2197 if (alignment & 1) {
2198 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2199 alignment = 1;
2200 }
2201 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2202 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2203 if (channelCount > 1) {
2204 // More than 2 channels does not require stronger alignment than stereo
2205 alignment <<= 1;
2206 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002207 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002208 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002209 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002210 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002211 goto Exit;
2212 }
Eric Laurent21da6472017-11-09 16:29:26 -08002213
2214 // When initializing a shared buffer AudioTrack via constructors,
2215 // there's no frameCount parameter.
2216 // But when initializing a shared buffer AudioTrack via set(),
2217 // there _is_ a frameCount parameter. We silently ignore it.
2218 frameCount = sharedBuffer->size() / frameSize;
2219 } else {
2220 size_t minFrameCount = 0;
2221 // For fast tracks we try to respect the application's request for notifications per buffer.
2222 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2223 if (notificationsPerBuffer > 0) {
2224 // Avoid possible arithmetic overflow during multiplication.
2225 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2226 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2227 notificationsPerBuffer, mFrameCount);
2228 } else {
2229 minFrameCount = mFrameCount * notificationsPerBuffer;
2230 }
2231 }
2232 } else {
2233 // For normal PCM streaming tracks, update minimum frame count.
2234 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2235 // cover audio hardware latency.
2236 // This is probably too conservative, but legacy application code may depend on it.
2237 // If you change this calculation, also review the start threshold which is related.
2238 uint32_t latencyMs = latency_l();
2239 if (latencyMs == 0) {
2240 ALOGE("Error when retrieving output stream latency");
2241 lStatus = UNKNOWN_ERROR;
2242 goto Exit;
2243 }
2244
2245 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2246 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2247
Eric Laurent81784c32012-11-19 14:55:58 -08002248 }
Eric Laurent21da6472017-11-09 16:29:26 -08002249 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002250 frameCount = minFrameCount;
2251 }
Eric Laurent81784c32012-11-19 14:55:58 -08002252 }
Eric Laurent21da6472017-11-09 16:29:26 -08002253
2254 // Make sure that application is notified with sufficient margin before underrun.
2255 // The client can divide the AudioTrack buffer into sub-buffers,
2256 // and expresses its desire to server as the notification frame count.
2257 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2258 size_t maxNotificationFrames;
2259 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2260 // notify every HAL buffer, regardless of the size of the track buffer
2261 maxNotificationFrames = mFrameCount;
2262 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002263 // Triple buffer the notification period for a triple buffered mixer period;
2264 // otherwise, double buffering for the notification period is fine.
2265 //
2266 // TODO: This should be moved to AudioTrack to modify the notification period
2267 // on AudioTrack::setBufferSizeInFrames() changes.
2268 const int nBuffering =
2269 (uint64_t{frameCount} * mSampleRate)
2270 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2271
Eric Laurent21da6472017-11-09 16:29:26 -08002272 maxNotificationFrames = frameCount / nBuffering;
2273 // If client requested a fast track but this was denied, then use the smaller maximum.
2274 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2275 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2276 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2277 maxNotificationFrames = maxNotificationFramesFastDenied;
2278 }
2279 }
2280 }
2281 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2282 if (notificationFrameCount == 0) {
2283 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2284 maxNotificationFrames, frameCount);
2285 } else {
2286 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2287 notificationFrameCount, maxNotificationFrames, frameCount);
2288 }
2289 notificationFrameCount = maxNotificationFrames;
2290 }
2291 }
2292
Glenn Kasten74935e42013-12-19 08:56:45 -08002293 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002294 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002295
Glenn Kastenc3df8382014-03-13 15:05:25 -07002296 switch (mType) {
2297
2298 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002299 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002300 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002301 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2302 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002303 sampleRate, format, channelMask, mOutput, mFormat);
2304 lStatus = BAD_VALUE;
2305 goto Exit;
2306 }
2307 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002308 break;
2309
2310 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002311 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002312 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2313 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002314 sampleRate, format, channelMask, mOutput, mFormat);
2315 lStatus = BAD_VALUE;
2316 goto Exit;
2317 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002318 break;
2319
2320 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002321 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002322 ALOGE("createTrack_l() Bad parameter: format %#x \""
2323 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002324 format, mOutput, mFormat);
2325 lStatus = BAD_VALUE;
2326 goto Exit;
2327 }
Andy Hungcd044842014-08-07 11:04:34 -07002328 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002329 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2330 lStatus = BAD_VALUE;
2331 goto Exit;
2332 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002333 break;
2334
Eric Laurent81784c32012-11-19 14:55:58 -08002335 }
2336
2337 lStatus = initCheck();
2338 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002339 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002340 goto Exit;
2341 }
2342
2343 { // scope for mLock
2344 Mutex::Autolock _l(mLock);
2345
2346 // all tracks in same audio session must share the same routing strategy otherwise
2347 // conflicts will happen when tracks are moved from one output to another by audio policy
2348 // manager
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002349 product_strategy_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002350 for (size_t i = 0; i < mTracks.size(); ++i) {
2351 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002352 if (t != 0 && t->isExternalTrack()) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002353 product_strategy_t actual = AudioSystem::getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002354 if (sessionId == t->sessionId() && strategy != actual) {
2355 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2356 strategy, actual);
2357 lStatus = BAD_VALUE;
2358 goto Exit;
2359 }
2360 }
2361 }
2362
yucliuc9c49cd2020-07-13 16:25:21 -07002363 // Set DIRECT flag if current thread is DirectOutputThread. This can
2364 // happen when the playback is rerouted to direct output thread by
2365 // dynamic audio policy.
2366 // Do NOT report the flag changes back to client, since the client
2367 // doesn't explicitly request a direct flag.
2368 audio_output_flags_t trackFlags = *flags;
2369 if (mType == DIRECT) {
2370 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2371 }
2372
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002373 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002374 channelMask, frameCount,
2375 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002376 sessionId, creatorPid, identity, trackFlags, TrackBase::TYPE_DEFAULT,
2377 portId, SIZE_MAX /*frameCountToBeReady*/);
Glenn Kasten03003332013-08-06 15:40:54 -07002378
Glenn Kasten03003332013-08-06 15:40:54 -07002379 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2380 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002381 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002382 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002383 goto Exit;
2384 }
2385 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002386 {
2387 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2388 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002389 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002390 }
2391 }
Eric Laurent81784c32012-11-19 14:55:58 -08002392
2393 sp<EffectChain> chain = getEffectChain_l(sessionId);
2394 if (chain != 0) {
2395 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2396 track->setMainBuffer(chain->inBuffer());
2397 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2398 chain->incTrackCnt();
2399 }
2400
Eric Laurent05067782016-06-01 18:27:28 -07002401 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002402 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2403 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2404 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002405 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002406 }
2407 }
2408
2409 lStatus = NO_ERROR;
2410
2411Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002412 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002413 return track;
2414}
2415
Andy Hung1bc088a2018-02-09 15:57:31 -08002416template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002417ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2418{
Andy Hungc0691382018-09-12 18:01:57 -07002419 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002420 const ssize_t index = mTracks.remove(track);
2421 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002422 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002423 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002424 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002425 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002426 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002427 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002428 }
2429 return index;
2430}
2431
Eric Laurent81784c32012-11-19 14:55:58 -08002432uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2433{
2434 return latency;
2435}
2436
2437uint32_t AudioFlinger::PlaybackThread::latency() const
2438{
2439 Mutex::Autolock _l(mLock);
2440 return latency_l();
2441}
2442uint32_t AudioFlinger::PlaybackThread::latency_l() const
2443{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002444 uint32_t latency;
2445 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2446 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002447 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002448 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002449}
2450
2451void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2452{
2453 Mutex::Autolock _l(mLock);
2454 // Don't apply master volume in SW if our HAL can do it for us.
2455 if (mOutput && mOutput->audioHwDev &&
2456 mOutput->audioHwDev->canSetMasterVolume()) {
2457 mMasterVolume = 1.0;
2458 } else {
2459 mMasterVolume = value;
2460 }
2461}
2462
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002463void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2464{
2465 mMasterBalance.store(balance);
2466}
2467
Eric Laurent81784c32012-11-19 14:55:58 -08002468void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2469{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002470 if (isDuplicating()) {
2471 return;
2472 }
Eric Laurent81784c32012-11-19 14:55:58 -08002473 Mutex::Autolock _l(mLock);
2474 // Don't apply master mute in SW if our HAL can do it for us.
2475 if (mOutput && mOutput->audioHwDev &&
2476 mOutput->audioHwDev->canSetMasterMute()) {
2477 mMasterMute = false;
2478 } else {
2479 mMasterMute = muted;
2480 }
2481}
2482
2483void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2484{
2485 Mutex::Autolock _l(mLock);
2486 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002487 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002488}
2489
2490void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2491{
2492 Mutex::Autolock _l(mLock);
2493 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002494 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002495}
2496
2497float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2498{
2499 Mutex::Autolock _l(mLock);
2500 return mStreamTypes[stream].volume;
2501}
2502
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002503void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2504{
2505 mOutput->stream->setVolume(left, right);
2506}
2507
Eric Laurent81784c32012-11-19 14:55:58 -08002508// addTrack_l() must be called with ThreadBase::mLock held
2509status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2510{
2511 status_t status = ALREADY_EXISTS;
2512
Eric Laurent81784c32012-11-19 14:55:58 -08002513 if (mActiveTracks.indexOf(track) < 0) {
2514 // the track is newly added, make sure it fills up all its
2515 // buffers before playing. This is to ensure the client will
2516 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002517 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002518 TrackBase::track_state state = track->mState;
2519 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002520 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002521 mLock.lock();
2522 // abort track was stopped/paused while we released the lock
2523 if (state != track->mState) {
2524 if (status == NO_ERROR) {
2525 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002526 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002527 mLock.lock();
2528 }
2529 return INVALID_OPERATION;
2530 }
2531 // abort if start is rejected by audio policy manager
2532 if (status != NO_ERROR) {
2533 return PERMISSION_DENIED;
2534 }
2535#ifdef ADD_BATTERY_DATA
2536 // to track the speaker usage
2537 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2538#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002539 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002540 }
2541
Eric Laurent51716182016-02-29 18:00:56 -08002542 // set retry count for buffer fill
2543 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002544 if (track->isStopping_1()) {
2545 track->mRetryCount = kMaxTrackStopRetriesOffload;
2546 } else {
2547 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2548 }
2549 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002550 } else {
2551 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002552 track->mFillingUpStatus =
2553 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002554 }
2555
jiabineb3bda02020-06-30 14:07:03 -07002556 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2557 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2558 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2559 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002560 // Unlock due to VibratorService will lock for this call and will
2561 // call Tracks.mute/unmute which also require thread's lock.
2562 mLock.unlock();
2563 const int intensity = AudioFlinger::onExternalVibrationStart(
2564 track->getExternalVibration());
2565 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002566 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002567 // Haptic playback should be enabled by vibrator service.
2568 if (track->getHapticPlaybackEnabled()) {
2569 // Disable haptic playback of all active track to ensure only
2570 // one track playing haptic if current track should play haptic.
2571 for (const auto &t : mActiveTracks) {
2572 t->setHapticPlaybackEnabled(false);
2573 }
jiabin245cdd92018-12-07 17:55:15 -08002574 }
jiabine70bc7f2020-06-30 22:07:55 -07002575
2576 // Set haptic intensity for effect
2577 if (chain != nullptr) {
2578 chain->setHapticIntensity_l(track->id(), intensity);
2579 }
jiabin245cdd92018-12-07 17:55:15 -08002580 }
2581
Eric Laurent81784c32012-11-19 14:55:58 -08002582 track->mResetDone = false;
2583 track->mPresentationCompleteFrames = 0;
2584 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002585 if (chain != 0) {
2586 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2587 track->sessionId());
2588 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002589 }
2590
Andy Hungc2b11cb2020-04-22 09:04:01 -07002591 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002592 status = NO_ERROR;
2593 }
2594
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002595 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002596 return status;
2597}
2598
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002600{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002601 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002602 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2604 track->mState = TrackBase::STOPPED;
2605 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002606 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002607 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002608 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002609 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002610
2611 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002612}
2613
2614void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2615{
2616 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002617
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002618 String8 result;
2619 track->appendDump(result, false /* active */);
2620 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002621
Eric Laurent81784c32012-11-19 14:55:58 -08002622 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002623 {
2624 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2625 mAudioTrackCallbacks.erase(track);
2626 }
Eric Laurent81784c32012-11-19 14:55:58 -08002627 if (track->isFastTrack()) {
2628 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002629 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002630 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2631 mFastTrackAvailMask |= 1 << index;
2632 // redundant as track is about to be destroyed, for dumpsys only
2633 track->mFastIndex = -1;
2634 }
2635 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2636 if (chain != 0) {
2637 chain->decTrackCnt();
2638 }
2639}
2640
2641String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2642{
Eric Laurent81784c32012-11-19 14:55:58 -08002643 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002644 String8 out_s8;
2645 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2646 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002647 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002648 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002649}
2650
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002651status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2652 Mutex::Autolock _l(mLock);
2653 if (mOutput == nullptr || mOutput->stream == nullptr) {
2654 return NO_INIT;
2655 }
2656 return mOutput->stream->selectPresentation(presentationId, programId);
2657}
2658
Eric Laurent09f1ed22019-04-24 17:45:17 -07002659void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2660 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002661 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2662 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002663
Eric Laurent73e26b62015-04-27 16:55:58 -07002664 desc->mIoHandle = mId;
Eric Laurent74c38dc2020-12-23 18:19:44 +01002665 struct audio_patch patch = mPatch;
2666 if (isMsdDevice()) {
2667 patch = mDownStreamPatch;
2668 }
Eric Laurent81784c32012-11-19 14:55:58 -08002669
2670 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002671 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002672 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002673 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002674 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002675 desc->mChannelMask = mChannelMask;
2676 desc->mSamplingRate = mSampleRate;
2677 desc->mFormat = mFormat;
2678 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002679 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002680 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002681 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002682 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002683 case AUDIO_CLIENT_STARTED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002684 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002685 desc->mPortId = portId;
2686 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002687 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002688 default:
2689 break;
2690 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002691 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002692}
2693
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002694void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002695{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002696 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002697}
2698
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002699void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002700{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002701 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002702}
2703
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002704void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002705{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002706 mCallbackThread->setAsyncError();
2707}
2708
jiabinf6eb4c32020-02-25 14:06:25 -08002709void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2710 const std::basic_string<uint8_t>& metadataBs)
2711{
2712 std::thread([this, metadataBs]() {
2713 audio_utils::metadata::Data metadata =
2714 audio_utils::metadata::dataFromByteString(metadataBs);
2715 if (metadata.empty()) {
2716 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2717 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2718 (int)metadataBs.size());
2719 return;
2720 }
2721
2722 audio_utils::metadata::ByteString metaDataStr =
2723 audio_utils::metadata::byteStringFromData(metadata);
2724 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2725 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002726 for (const auto& callbackPair : mAudioTrackCallbacks) {
2727 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002728 }
2729 }).detach();
2730}
2731
Eric Laurent3b4529e2013-09-05 18:09:19 -07002732void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733{
2734 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002735 // reject out of sequence requests
2736 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2737 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002738 mWaitWorkCV.signal();
2739 }
2740}
2741
Eric Laurent3b4529e2013-09-05 18:09:19 -07002742void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002743{
2744 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002745 // reject out of sequence requests
2746 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002747 // Register discontinuity when HW drain is completed because that can cause
2748 // the timestamp frame position to reset to 0 for direct and offload threads.
2749 // (Out of sequence requests are ignored, since the discontinuity would be handled
2750 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002751 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002752 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002753 mWaitWorkCV.signal();
2754 }
2755}
2756
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002757void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002758{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002759 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002760 mSampleRate = mOutput->getSampleRate();
2761 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002762 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002763 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002764 }
Andy Hung9a592762014-07-21 21:56:01 -07002765 if ((mType == MIXER || mType == DUPLICATING)
2766 && !isValidPcmSinkChannelMask(mChannelMask)) {
2767 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2768 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002769 }
Andy Hunge5412692014-05-16 11:25:07 -07002770 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002771 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002772
2773 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002774 status_t result = mOutput->stream->getFormat(&mHALFormat);
2775 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002776 // Get format from the shim, which will be different than the HAL format
2777 // if playing compressed audio over HDMI passthrough.
2778 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002779 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002780 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002781 }
Andy Hung6146c082014-03-18 11:56:15 -07002782 if ((mType == MIXER || mType == DUPLICATING)
2783 && !isValidPcmSinkFormat(mFormat)) {
2784 LOG_FATAL("HAL format %#x not supported for mixed output",
2785 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002786 }
Phil Burk062e67a2015-02-11 13:40:50 -08002787 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002788 result = mOutput->stream->getBufferSize(&mBufferSize);
2789 LOG_ALWAYS_FATAL_IF(result != OK,
2790 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002791 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002792 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002793 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002794 mFrameCount);
2795 }
2796
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002797 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2798 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002799 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002800 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002801 }
2802 }
2803
Eric Laurentd1f69b02014-12-15 14:33:13 -08002804 mHwSupportsPause = false;
2805 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002806 bool supportsPause = false, supportsResume = false;
2807 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2808 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002809 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002810 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002811 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002812 } else if (supportsResume) {
2813 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002814 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002815 }
2816 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002817 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2818 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2819 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002820
Andy Hungfbfc3952015-01-15 13:33:51 -08002821 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2822 // For best precision, we use float instead of the associated output
2823 // device format (typically PCM 16 bit).
2824
2825 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2826 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2827 mBufferSize = mFrameSize * mFrameCount;
2828
2829 // TODO: We currently use the associated output device channel mask and sample rate.
2830 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2831 // (if a valid mask) to avoid premature downmix.
2832 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2833 // instead of the output device sample rate to avoid loss of high frequency information.
2834 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2835 }
2836
Andy Hung09a50072014-02-27 14:30:47 -08002837 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002838 double multiplier = 1.0;
2839 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2840 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002841 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2842 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002843
Eric Laurent81784c32012-11-19 14:55:58 -08002844 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2845 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2846 maxNormalFrameCount = maxNormalFrameCount & ~15;
2847 if (maxNormalFrameCount < minNormalFrameCount) {
2848 maxNormalFrameCount = minNormalFrameCount;
2849 }
2850 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2851 if (multiplier <= 1.0) {
2852 multiplier = 1.0;
2853 } else if (multiplier <= 2.0) {
2854 if (2 * mFrameCount <= maxNormalFrameCount) {
2855 multiplier = 2.0;
2856 } else {
2857 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2858 }
2859 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002860 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002861 }
2862 }
2863 mNormalFrameCount = multiplier * mFrameCount;
2864 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002865 if (mType == MIXER || mType == DUPLICATING) {
2866 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2867 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002868 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002869 mNormalFrameCount);
2870
Andy Hung08fb1742015-05-31 23:22:10 -07002871 // Check if we want to throttle the processing to no more than 2x normal rate
2872 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002873 mThreadThrottleTimeMs = 0;
2874 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002875 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2876
Andy Hung010a1a12014-03-13 13:57:33 -07002877 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2878 // Originally this was int16_t[] array, need to remove legacy implications.
2879 free(mSinkBuffer);
2880 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002881 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2882 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2883 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002884 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002885
Andy Hung69aed5f2014-02-25 17:24:40 -08002886 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2887 // drives the output.
2888 free(mMixerBuffer);
2889 mMixerBuffer = NULL;
2890 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002891 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002892 mMixerBufferSize = mNormalFrameCount * mChannelCount
2893 * audio_bytes_per_sample(mMixerBufferFormat);
2894 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2895 }
Andy Hung98ef9782014-03-04 14:46:50 -08002896 free(mEffectBuffer);
2897 mEffectBuffer = NULL;
2898 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002899 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002900 mEffectBufferSize = mNormalFrameCount * mChannelCount
2901 * audio_bytes_per_sample(mEffectBufferFormat);
2902 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2903 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002904
Mikhail Naganov55773032020-10-01 15:08:13 -07002905 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2906 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002907 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2908 mChannelCount -= mHapticChannelCount;
2909
Eric Laurent81784c32012-11-19 14:55:58 -08002910 // force reconfiguration of effect chains and engines to take new buffer size and audio
2911 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002912 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002913 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2914 // matter.
2915 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2916 Vector< sp<EffectChain> > effectChains = mEffectChains;
2917 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002918 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2919 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002920 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002921
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002922 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002923 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002924 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2925 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2926 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2927 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2928 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2929 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2930 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2931 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2932 (int32_t)mHapticChannelMask)
2933 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2934 (int32_t)mHapticChannelCount)
2935 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2936 formatToString(mHALFormat).c_str())
2937 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2938 (int32_t)mFrameCount) // sic - added HAL
2939 ;
2940 uint32_t latencyMs;
2941 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2942 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2943 }
2944 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08002945}
2946
Kevin Rocard069c2712018-03-29 19:09:14 -07002947void AudioFlinger::PlaybackThread::updateMetadata_l()
2948{
Kevin Rocard12381092018-04-11 09:19:59 -07002949 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2950 return; // That should not happen
2951 }
2952 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2953 for (const sp<Track> &track : mActiveTracks) {
2954 // Do not short-circuit as all hasChanged states must be reset
2955 // as all the metadata are going to be sent
2956 hasChanged |= track->readAndClearHasChanged();
2957 }
2958 if (!hasChanged) {
2959 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002960 }
2961 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002962 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002963 for (const sp<Track> &track : mActiveTracks) {
2964 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01002965 // Do not forward metadata for PatchTrack with unspecified stream type
2966 if (track->streamType() != AUDIO_STREAM_PATCH) {
2967 track->copyMetadataTo(backInserter);
2968 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002969 }
Kevin Rocard12381092018-04-11 09:19:59 -07002970 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002971}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002972
Kevin Rocard12381092018-04-11 09:19:59 -07002973void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2974 const StreamOutHalInterface::SourceMetadata& metadata)
2975{
2976 mOutput->stream->updateSourceMetadata(metadata);
2977};
2978
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002979status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002980{
2981 if (halFrames == NULL || dspFrames == NULL) {
2982 return BAD_VALUE;
2983 }
2984 Mutex::Autolock _l(mLock);
2985 if (initCheck() != NO_ERROR) {
2986 return INVALID_OPERATION;
2987 }
Andy Hung818e7a32016-02-16 18:08:07 -08002988 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002989 *halFrames = framesWritten;
2990
2991 if (isSuspended()) {
2992 // return an estimation of rendered frames when the output is suspended
2993 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002994 *dspFrames = (uint32_t)
2995 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002996 return NO_ERROR;
2997 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002998 status_t status;
2999 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003000 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003001 *dspFrames = (size_t)frames;
3002 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003003 }
3004}
3005
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003006product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003007{
3008 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3009 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3010 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3011 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3012 }
3013 for (size_t i = 0; i < mTracks.size(); i++) {
3014 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003015 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003016 return AudioSystem::getStrategyForStream(track->streamType());
3017 }
3018 }
3019 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3020}
3021
3022
Phil Burk062e67a2015-02-11 13:40:50 -08003023AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003024{
3025 Mutex::Autolock _l(mLock);
3026 return mOutput;
3027}
3028
Phil Burk062e67a2015-02-11 13:40:50 -08003029AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003030{
3031 Mutex::Autolock _l(mLock);
3032 AudioStreamOut *output = mOutput;
3033 mOutput = NULL;
3034 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3035 // must push a NULL and wait for ack
3036 mOutputSink.clear();
3037 mPipeSink.clear();
3038 mNormalSink.clear();
3039 return output;
3040}
3041
3042// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003043sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003044{
3045 if (mOutput == NULL) {
3046 return NULL;
3047 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003048 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003049}
3050
3051uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3052{
3053 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3054}
3055
3056status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3057{
3058 if (!isValidSyncEvent(event)) {
3059 return BAD_VALUE;
3060 }
3061
3062 Mutex::Autolock _l(mLock);
3063
3064 for (size_t i = 0; i < mTracks.size(); ++i) {
3065 sp<Track> track = mTracks[i];
3066 if (event->triggerSession() == track->sessionId()) {
3067 (void) track->setSyncEvent(event);
3068 return NO_ERROR;
3069 }
3070 }
3071
3072 return NAME_NOT_FOUND;
3073}
3074
3075bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3076{
3077 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3078}
3079
3080void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3081 const Vector< sp<Track> >& tracksToRemove)
3082{
Andy Hungfe726a62018-09-27 15:17:25 -07003083 // Miscellaneous track cleanup when removed from the active list,
3084 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003085#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003086 for (const auto& track : tracksToRemove) {
3087 if (track->isExternalTrack()) {
3088 // to track the speaker usage
3089 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003090 }
3091 }
Andy Hungfe726a62018-09-27 15:17:25 -07003092#else
3093 (void)tracksToRemove; // suppress unused warning
3094#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003095}
3096
3097void AudioFlinger::PlaybackThread::checkSilentMode_l()
3098{
3099 if (!mMasterMute) {
3100 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003101 if (mOutDeviceTypeAddrs.empty()) {
3102 ALOGD("ro.audio.silent is ignored since no output device is set");
3103 return;
3104 }
jiabinc52b1ff2019-10-31 17:20:42 -07003105 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003106 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3107 return;
3108 }
Eric Laurent81784c32012-11-19 14:55:58 -08003109 if (property_get("ro.audio.silent", value, "0") > 0) {
3110 char *endptr;
3111 unsigned long ul = strtoul(value, &endptr, 0);
3112 if (*endptr == '\0' && ul != 0) {
3113 ALOGD("Silence is golden");
3114 // The setprop command will not allow a property to be changed after
3115 // the first time it is set, so we don't have to worry about un-muting.
3116 setMasterMute_l(true);
3117 }
3118 }
3119 }
3120}
3121
3122// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003123ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003124{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003125 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003126 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003127 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003128 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003129
3130 // If an NBAIO sink is present, use it to write the normal mixer's submix
3131 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003132
Andy Hung010a1a12014-03-13 13:57:33 -07003133 const size_t count = mBytesRemaining / mFrameSize;
3134
Simon Wilson2d590962012-11-29 15:18:50 -08003135 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003136 // update the setpoint when AudioFlinger::mScreenState changes
3137 uint32_t screenState = AudioFlinger::mScreenState;
3138 if (screenState != mScreenState) {
3139 mScreenState = screenState;
3140 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3141 if (pipe != NULL) {
3142 pipe->setAvgFrames((mScreenState & 1) ?
3143 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3144 }
3145 }
Andy Hung010a1a12014-03-13 13:57:33 -07003146 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003147 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003148 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003149 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003150#ifdef TEE_SINK
3151 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3152#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003153 } else {
3154 bytesWritten = framesWritten;
3155 }
3156 // otherwise use the HAL / AudioStreamOut directly
3157 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003158 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003159
Eric Laurentbfb1b832013-01-07 09:53:42 -08003160 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003161 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3162 mWriteAckSequence += 2;
3163 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003165 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003166 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003167 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003168 // FIXME We should have an implementation of timestamps for direct output threads.
3169 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003170 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003171 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003172
Eric Laurentbfb1b832013-01-07 09:53:42 -08003173 if (mUseAsyncWrite &&
3174 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3175 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003176 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003177 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003178 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003179 }
Eric Laurent81784c32012-11-19 14:55:58 -08003180 }
3181
Eric Laurent81784c32012-11-19 14:55:58 -08003182 mNumWrites++;
3183 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003184 if (mStandby) {
3185 mThreadMetrics.logBeginInterval();
3186 mStandby = false;
3187 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003188 return bytesWritten;
3189}
3190
3191void AudioFlinger::PlaybackThread::threadLoop_drain()
3192{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003193 bool supportsDrain = false;
3194 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003195 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3196 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003197 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3198 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003199 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003200 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003201 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003202 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003203 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003204 }
3205}
3206
3207void AudioFlinger::PlaybackThread::threadLoop_exit()
3208{
Eric Laurent275e8e92014-11-30 15:14:47 -08003209 {
3210 Mutex::Autolock _l(mLock);
3211 for (size_t i = 0; i < mTracks.size(); i++) {
3212 sp<Track> track = mTracks[i];
3213 track->invalidate();
3214 }
Andy Hungdae27702016-10-31 14:01:16 -07003215 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3216 // After we exit there are no more track changes sent to BatteryNotifier
3217 // because that requires an active threadLoop.
3218 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3219 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003220 }
Eric Laurent81784c32012-11-19 14:55:58 -08003221}
3222
3223/*
3224The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003225 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003226 - mActiveSleepTimeUs from activeSleepTimeUs()
3227 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003228 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3229 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003230 - maxPeriod from frame count and sample rate (MIXER only)
3231
3232The parameters that affect these derived values are:
3233 - frame count
3234 - frame size
3235 - sample rate
3236 - device type: A2DP or not
3237 - device latency
3238 - format: PCM or not
3239 - active sleep time
3240 - idle sleep time
3241*/
3242
3243void AudioFlinger::PlaybackThread::cacheParameters_l()
3244{
Andy Hung25c2dac2014-02-27 14:56:00 -08003245 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003246 mActiveSleepTimeUs = activeSleepTimeUs();
3247 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003248
3249 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3250 // truncating audio when going to standby.
3251 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003252 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003253 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3254 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3255 }
3256 }
Eric Laurent81784c32012-11-19 14:55:58 -08003257}
3258
Eric Laurent13084622016-05-17 10:51:49 -07003259bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003260{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003261 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003262 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003263 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003264 size_t size = mTracks.size();
3265 for (size_t i = 0; i < size; i++) {
3266 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003267 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003268 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003269 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003270 }
3271 }
Eric Laurent13084622016-05-17 10:51:49 -07003272 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003273}
3274
Haynes Mathew George05317d22016-05-03 16:34:26 -07003275void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3276{
3277 Mutex::Autolock _l(mLock);
3278 invalidateTracks_l(streamType);
3279}
3280
Eric Laurent81784c32012-11-19 14:55:58 -08003281status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3282{
Glenn Kastend848eb42016-03-08 13:42:11 -08003283 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003284 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003285 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003286 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3287 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3288 &halInBuffer);
3289 if (result != OK) return result;
3290 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003291 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003292 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003293 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003294 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003295 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003296 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003297 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003298 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003299 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003300 &halInBuffer);
3301 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003302#ifdef FLOAT_EFFECT_CHAIN
3303 buffer = halInBuffer->audioBuffer()->f32;
3304#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003305 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003306#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003307 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3308 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003309 }
3310
3311 // Attach all tracks with same session ID to this chain.
3312 for (size_t i = 0; i < mTracks.size(); ++i) {
3313 sp<Track> track = mTracks[i];
3314 if (session == track->sessionId()) {
3315 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3316 buffer);
3317 track->setMainBuffer(buffer);
3318 chain->incTrackCnt();
3319 }
3320 }
3321
3322 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003323 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003324 if (session == track->sessionId()) {
3325 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3326 chain->incActiveTrackCnt();
3327 }
3328 }
3329 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003330 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003331 chain->setInBuffer(halInBuffer);
3332 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003333 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3334 // chains list in order to be processed last as it contains output device effects.
3335 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3336 // processing effects specific to an output stream before effects applied to all streams
3337 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003338 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3339 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003340 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003341 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003342 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003343 // Effect chain for other sessions are inserted at beginning of effect
3344 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003345 // sessions is not important.
3346 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003347 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3348 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003349 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003350 size_t size = mEffectChains.size();
3351 size_t i = 0;
3352 for (i = 0; i < size; i++) {
3353 if (mEffectChains[i]->sessionId() < session) {
3354 break;
3355 }
3356 }
3357 mEffectChains.insertAt(chain, i);
3358 checkSuspendOnAddEffectChain_l(chain);
3359
3360 return NO_ERROR;
3361}
3362
3363size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3364{
Glenn Kastend848eb42016-03-08 13:42:11 -08003365 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003366
3367 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3368
3369 for (size_t i = 0; i < mEffectChains.size(); i++) {
3370 if (chain == mEffectChains[i]) {
3371 mEffectChains.removeAt(i);
3372 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003373 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003374 if (session == track->sessionId()) {
3375 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3376 chain.get(), session);
3377 chain->decActiveTrackCnt();
3378 }
3379 }
3380
3381 // detach all tracks with same session ID from this chain
3382 for (size_t i = 0; i < mTracks.size(); ++i) {
3383 sp<Track> track = mTracks[i];
3384 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003385 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003386 chain->decTrackCnt();
3387 }
3388 }
3389 break;
3390 }
3391 }
3392 return mEffectChains.size();
3393}
3394
3395status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003396 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003397{
3398 Mutex::Autolock _l(mLock);
3399 return attachAuxEffect_l(track, EffectId);
3400}
3401
3402status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003403 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003404{
3405 status_t status = NO_ERROR;
3406
3407 if (EffectId == 0) {
3408 track->setAuxBuffer(0, NULL);
3409 } else {
3410 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3411 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3412 if (effect != 0) {
3413 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3414 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3415 } else {
3416 status = INVALID_OPERATION;
3417 }
3418 } else {
3419 status = BAD_VALUE;
3420 }
3421 }
3422 return status;
3423}
3424
3425void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3426{
3427 for (size_t i = 0; i < mTracks.size(); ++i) {
3428 sp<Track> track = mTracks[i];
3429 if (track->auxEffectId() == effectId) {
3430 attachAuxEffect_l(track, 0);
3431 }
3432 }
3433}
3434
3435bool AudioFlinger::PlaybackThread::threadLoop()
3436{
Glenn Kasten388d5712017-04-07 14:38:41 -07003437 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003438
Eric Laurent81784c32012-11-19 14:55:58 -08003439 Vector< sp<Track> > tracksToRemove;
3440
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003441 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003442 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003443
3444 // MIXER
3445 nsecs_t lastWarning = 0;
3446
3447 // DUPLICATING
3448 // FIXME could this be made local to while loop?
3449 writeFrames = 0;
3450
3451 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003452 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003453
3454 if (mType == MIXER) {
3455 sleepTimeShift = 0;
3456 }
3457
3458 CpuStats cpuStats;
3459 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3460
3461 acquireWakeLock();
3462
Glenn Kasteneef598c2017-04-03 14:41:13 -07003463 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3464 // thread associated with this PlaybackThread.
3465 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3466 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003467 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3468 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003469 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003470 const char *logString = NULL;
3471
rago1bb90822017-05-02 18:31:48 -07003472 // Estimated time for next buffer to be written to hal. This is used only on
3473 // suspended mode (for now) to help schedule the wait time until next iteration.
3474 nsecs_t timeLoopNextNs = 0;
3475
Eric Laurent664539d2013-09-23 18:24:31 -07003476 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003477
Andy Hung2dbffc22018-08-08 18:50:41 -07003478 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003479
Andy Hung446f4df2019-02-21 12:26:41 -08003480 // loopCount is used for statistics and diagnostics.
3481 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003482 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003483 // Log merge requests are performed during AudioFlinger binder transactions, but
3484 // that does not cover audio playback. It's requested here for that reason.
3485 mAudioFlinger->requestLogMerge();
3486
Eric Laurent81784c32012-11-19 14:55:58 -08003487 cpuStats.sample(myName);
3488
3489 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003490 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003491 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003492
Andy Hung2dbffc22018-08-08 18:50:41 -07003493 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3494 //
jiabinc52b1ff2019-10-31 17:20:42 -07003495 // Note: we access outDeviceTypes() outside of mLock.
3496 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003497 // Here, we try for the AF lock, but do not block on it as the latency
3498 // is more informational.
3499 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3500 std::vector<PatchPanel::SoftwarePatch> swPatches;
3501 double latencyMs;
3502 status_t status = INVALID_OPERATION;
3503 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3504 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3505 && swPatches.size() > 0) {
3506 status = swPatches[0].getLatencyMs_l(&latencyMs);
3507 downstreamPatchHandle = swPatches[0].getPatchHandle();
3508 }
3509 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003510 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003511 lastDownstreamPatchHandle = downstreamPatchHandle;
3512 }
3513 if (status == OK) {
3514 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003515 // latency of 5 seconds).
3516 const double minLatency = 0., maxLatency = 5000.;
3517 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003518 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003519 } else {
3520 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003521 if (latencyMs < minLatency) latencyMs = minLatency;
3522 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003523 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003524 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003525 }
3526 mAudioFlinger->mLock.unlock();
3527 }
3528 } else {
3529 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3530 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003531 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003532 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3533 }
3534 }
3535
Eric Laurent81784c32012-11-19 14:55:58 -08003536 { // scope for mLock
3537
3538 Mutex::Autolock _l(mLock);
3539
Eric Laurent021cf962014-05-13 10:18:14 -07003540 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003541
Glenn Kasteneef598c2017-04-03 14:41:13 -07003542 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003543 if (logString != NULL) {
3544 mNBLogWriter->logTimestamp();
3545 mNBLogWriter->log(logString);
3546 logString = NULL;
3547 }
3548
Dean Wheatley12473e92021-03-18 23:00:55 +11003549 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003550
Eric Laurent81784c32012-11-19 14:55:58 -08003551 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003552 if (mSignalPending) {
3553 // A signal was raised while we were unlocked
3554 mSignalPending = false;
3555 } else if (waitingAsyncCallback_l()) {
3556 if (exitPending()) {
3557 break;
3558 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003559 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003560 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003561 releaseWakeLock_l();
3562 released = true;
3563 }
Andy Hung10cbff12017-02-21 17:30:14 -08003564
3565 const int64_t waitNs = computeWaitTimeNs_l();
3566 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3567 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3568 if (status == TIMED_OUT) {
3569 mSignalPending = true; // if timeout recheck everything
3570 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003572 if (released) {
3573 acquireWakeLock_l();
3574 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003575 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3576 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003577
3578 continue;
3579 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003580 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003581 isSuspended()) {
3582 // put audio hardware into standby after short delay
3583 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003584
3585 threadLoop_standby();
3586
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003587 // This is where we go into standby
3588 if (!mStandby) {
3589 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003590 mThreadMetrics.logEndInterval();
3591 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003592 }
Andy Hungd0979812019-02-21 15:51:44 -08003593 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003594 }
3595
Eric Tan39ec8d62018-07-24 09:49:29 -07003596 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003597 // we're about to wait, flush the binder command buffer
3598 IPCThreadState::self()->flushCommands();
3599
3600 clearOutputTracks();
3601
3602 if (exitPending()) {
3603 break;
3604 }
3605
3606 releaseWakeLock_l();
3607 // wait until we have something to do...
3608 ALOGV("%s going to sleep", myName.string());
3609 mWaitWorkCV.wait(mLock);
3610 ALOGV("%s waking up", myName.string());
3611 acquireWakeLock_l();
3612
3613 mMixerStatus = MIXER_IDLE;
3614 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3615 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003616 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003617 checkSilentMode_l();
3618
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003619 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3620 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003621 if (mType == MIXER) {
3622 sleepTimeShift = 0;
3623 }
3624
3625 continue;
3626 }
3627 }
Eric Laurent81784c32012-11-19 14:55:58 -08003628 // mMixerStatusIgnoringFastTracks is also updated internally
3629 mMixerStatus = prepareTracks_l(&tracksToRemove);
3630
Andy Hungdae27702016-10-31 14:01:16 -07003631 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003632
Kevin Rocard069c2712018-03-29 19:09:14 -07003633 updateMetadata_l();
3634
Eric Laurent81784c32012-11-19 14:55:58 -08003635 // prevent any changes in effect chain list and in each effect chain
3636 // during mixing and effect process as the audio buffers could be deleted
3637 // or modified if an effect is created or deleted
3638 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003639
3640 // Determine which session to pick up haptic data.
3641 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003642 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003643 // TODO: Write haptic data directly to sink buffer when mixing.
3644 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3645 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003646 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3647 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3648 activeHapticSessionId = track->sessionId();
3649 break;
3650 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003651 if (track->getHapticPlaybackEnabled()) {
3652 activeHapticSessionId = track->sessionId();
3653 break;
3654 }
3655 }
3656 }
3657
Andy Hungc1646382019-04-30 16:12:10 -07003658 // Acquire a local copy of active tracks with lock (release w/o lock).
3659 //
3660 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3661 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3662 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3663 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003664 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003665
Eric Laurentbfb1b832013-01-07 09:53:42 -08003666 if (mBytesRemaining == 0) {
3667 mCurrentWriteLength = 0;
3668 if (mMixerStatus == MIXER_TRACKS_READY) {
3669 // threadLoop_mix() sets mCurrentWriteLength
3670 threadLoop_mix();
3671 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3672 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003673 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003674 // must be written to HAL
3675 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003676 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003677 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003678
3679 // Tally underrun frames as we are inserting 0s here.
3680 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003681 if (track->mFillingUpStatus == Track::FS_ACTIVE
3682 && !track->isStopped()
3683 && !track->isPaused()
3684 && !track->isTerminated()) {
3685 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3686 __func__, track->id(), track->getTrackStateAsString(),
3687 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003688 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3689 }
3690 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003691 }
3692 }
Andy Hung98ef9782014-03-04 14:46:50 -08003693 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003694 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003695 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3696 // or mSinkBuffer (if there are no effects).
3697 //
3698 // This is done pre-effects computation; if effects change to
3699 // support higher precision, this needs to move.
3700 //
3701 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003702 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003703 if (mMixerBufferValid) {
3704 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3705 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3706
Andy Hung2ddee192015-12-18 17:34:44 -08003707 // mono blend occurs for mixer threads only (not direct or offloaded)
3708 // and is handled here if we're going directly to the sink.
3709 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003710 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3711 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003712 }
3713
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003714 if (!hasFastMixer()) {
3715 // Balance must take effect after mono conversion.
3716 // We do it here if there is no FastMixer.
3717 // mBalance detects zero balance within the class for speed (not needed here).
3718 mBalance.setBalance(mMasterBalance.load());
3719 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3720 }
3721
Andy Hung98ef9782014-03-04 14:46:50 -08003722 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003723 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3724
3725 // If we're going directly to the sink and there are haptic channels,
3726 // we should adjust channels as the sample data is partially interleaved
3727 // in this case.
3728 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3729 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3730 mChannelCount + mHapticChannelCount,
3731 audio_bytes_per_sample(format),
3732 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3733 }
Andy Hung98ef9782014-03-04 14:46:50 -08003734 }
3735
Eric Laurentbfb1b832013-01-07 09:53:42 -08003736 mBytesRemaining = mCurrentWriteLength;
3737 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003738 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3739 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3740 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3741 mBytesWritten += mBytesRemaining;
3742 mFramesWritten += framesRemaining;
3743 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003744 mBytesRemaining = 0;
3745 }
Eric Laurent81784c32012-11-19 14:55:58 -08003746
Eric Laurentbfb1b832013-01-07 09:53:42 -08003747 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003748 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003749 for (size_t i = 0; i < effectChains.size(); i ++) {
3750 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003751 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003752 if (activeHapticSessionId != AUDIO_SESSION_NONE
3753 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003754 // Haptic data is active in this case, copy it directly from
3755 // in buffer to out buffer.
3756 const size_t audioBufferSize = mNormalFrameCount
3757 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3758 memcpy_by_audio_format(
3759 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3760 EFFECT_BUFFER_FORMAT,
3761 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3762 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3763 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003764 }
Eric Laurent81784c32012-11-19 14:55:58 -08003765 }
3766 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003767 // Process effect chains for offloaded thread even if no audio
3768 // was read from audio track: process only updates effect state
3769 // and thus does have to be synchronized with audio writes but may have
3770 // to be called while waiting for async write callback
3771 if (mType == OFFLOAD) {
3772 for (size_t i = 0; i < effectChains.size(); i ++) {
3773 effectChains[i]->process_l();
3774 }
3775 }
Eric Laurent81784c32012-11-19 14:55:58 -08003776
Andy Hung98ef9782014-03-04 14:46:50 -08003777 // Only if the Effects buffer is enabled and there is data in the
3778 // Effects buffer (buffer valid), we need to
3779 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003780 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003781 if (mEffectBufferValid) {
3782 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003783
3784 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003785 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3786 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003787 }
3788
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003789 if (!hasFastMixer()) {
3790 // Balance must take effect after mono conversion.
3791 // We do it here if there is no FastMixer.
3792 // mBalance detects zero balance within the class for speed (not needed here).
3793 mBalance.setBalance(mMasterBalance.load());
3794 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3795 }
3796
Andy Hung98ef9782014-03-04 14:46:50 -08003797 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003798 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3799 // The sample data is partially interleaved when haptic channels exist,
3800 // we need to adjust channels here.
3801 if (mHapticChannelCount > 0) {
3802 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3803 mChannelCount + mHapticChannelCount,
3804 audio_bytes_per_sample(mFormat),
3805 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3806 }
Andy Hung98ef9782014-03-04 14:46:50 -08003807 }
3808
Eric Laurent81784c32012-11-19 14:55:58 -08003809 // enable changes in effect chain
3810 unlockEffectChains(effectChains);
3811
Eric Laurentbfb1b832013-01-07 09:53:42 -08003812 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003813 // mSleepTimeUs == 0 means we must write to audio hardware
3814 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003815 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003816 // writePeriodNs is updated >= 0 when ret > 0.
3817 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003818 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003819 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003820 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003821 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003822 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003823 if (ret < 0) {
3824 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003825 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003826 mBytesWritten += ret;
3827 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003828 const int64_t frames = ret / mFrameSize;
3829 mFramesWritten += frames;
3830
3831 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3832 // process information relating to write time.
3833 if (audio_has_proportional_frames(mFormat)) {
3834 // we are in a continuous mixing cycle
3835 if (mMixerStatus == MIXER_TRACKS_READY &&
3836 loopCount == lastLoopCountWritten + 1) {
3837
3838 const double jitterMs =
3839 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3840 {frames, writePeriodNs},
3841 {0, 0} /* lastTimestamp */, mSampleRate);
3842 const double processMs =
3843 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3844
3845 Mutex::Autolock _l(mLock);
3846 mIoJitterMs.add(jitterMs);
3847 mProcessTimeMs.add(processMs);
3848 }
3849
3850 // write blocked detection
3851 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3852 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3853 mNumDelayedWrites++;
3854 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3855 ATRACE_NAME("underrun");
3856 ALOGW("write blocked for %lld msecs, "
3857 "%d delayed writes, thread %d",
3858 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3859 mNumDelayedWrites, mId);
3860 lastWarning = lastIoEndNs;
3861 }
3862 }
3863 }
3864 // update timing info.
3865 mLastIoBeginNs = lastIoBeginNs;
3866 mLastIoEndNs = lastIoEndNs;
3867 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003868 }
3869 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3870 (mMixerStatus == MIXER_DRAIN_ALL)) {
3871 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003872 }
Andy Hung08fb1742015-05-31 23:22:10 -07003873 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003874
3875 if (mThreadThrottle
3876 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003877 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003878 // Limit MixerThread data processing to no more than twice the
3879 // expected processing rate.
3880 //
3881 // This helps prevent underruns with NuPlayer and other applications
3882 // which may set up buffers that are close to the minimum size, or use
3883 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3884 //
3885 // The throttle smooths out sudden large data drains from the device,
3886 // e.g. when it comes out of standby, which often causes problems with
3887 // (1) mixer threads without a fast mixer (which has its own warm-up)
3888 // (2) minimum buffer sized tracks (even if the track is full,
3889 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003890 //
3891 // Total time spent in last processing cycle equals time spent in
3892 // 1. threadLoop_write, as well as time spent in
3893 // 2. threadLoop_mix (significant for heavy mixing, especially
3894 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003895
Andy Hung446f4df2019-02-21 12:26:41 -08003896 // it's OK if deltaMs is an overestimate.
3897
3898 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003899
Ivan Lozanoea04d392017-11-07 14:37:07 -08003900 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003901 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07003902 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08003903
Andy Hung08fb1742015-05-31 23:22:10 -07003904 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003905 // notify of throttle start on verbose log
3906 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3907 "mixer(%p) throttle begin:"
3908 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003909 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003910 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003911 // Throttle must be attributed to the previous mixer loop's write time
3912 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003913 // This also ensures proper timing statistics.
3914 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003915 } else {
3916 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3917 if (diff > 0) {
3918 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003919 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07003920 ALOGD_IF(!isSingleDeviceType(
3921 outDeviceTypes(), audio_is_a2dp_out_device) &&
3922 !isSingleDeviceType(
3923 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003924 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003925 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3926 }
Andy Hung08fb1742015-05-31 23:22:10 -07003927 }
3928 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003929 }
Eric Laurent81784c32012-11-19 14:55:58 -08003930
Eric Laurentbfb1b832013-01-07 09:53:42 -08003931 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003932 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003933 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003934 // suspended requires accurate metering of sleep time.
3935 if (isSuspended()) {
3936 // advance by expected sleepTime
3937 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3938 const nsecs_t nowNs = systemTime();
3939
3940 // compute expected next time vs current time.
3941 // (negative deltas are treated as delays).
3942 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3943 if (deltaNs < -kMaxNextBufferDelayNs) {
3944 // Delays longer than the max allowed trigger a reset.
3945 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3946 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3947 timeLoopNextNs = nowNs + deltaNs;
3948 } else if (deltaNs < 0) {
3949 // Delays within the max delay allowed: zero the delta/sleepTime
3950 // to help the system catch up in the next iteration(s)
3951 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3952 deltaNs = 0;
3953 }
3954 // update sleep time (which is >= 0)
3955 mSleepTimeUs = deltaNs / 1000;
3956 }
Eric Laurente93cc032016-05-05 10:15:10 -07003957 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3958 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003959 }
Glenn Kastene7754022014-10-31 12:11:26 -07003960 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003961 }
Eric Laurent81784c32012-11-19 14:55:58 -08003962 }
3963
3964 // Finally let go of removed track(s), without the lock held
3965 // since we can't guarantee the destructors won't acquire that
3966 // same lock. This will also mutate and push a new fast mixer state.
3967 threadLoop_removeTracks(tracksToRemove);
3968 tracksToRemove.clear();
3969
3970 // FIXME I don't understand the need for this here;
3971 // it was in the original code but maybe the
3972 // assignment in saveOutputTracks() makes this unnecessary?
3973 clearOutputTracks();
3974
3975 // Effect chains will be actually deleted here if they were removed from
3976 // mEffectChains list during mixing or effects processing
3977 effectChains.clear();
3978
3979 // FIXME Note that the above .clear() is no longer necessary since effectChains
3980 // is now local to this block, but will keep it for now (at least until merge done).
3981 }
3982
Eric Laurentbfb1b832013-01-07 09:53:42 -08003983 threadLoop_exit();
3984
Eric Laurentcf817a22014-08-04 20:36:31 -07003985 if (!mStandby) {
3986 threadLoop_standby();
3987 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003988 }
3989
3990 releaseWakeLock();
3991
3992 ALOGV("Thread %p type %d exiting", this, mType);
3993 return false;
3994}
3995
Dean Wheatley12473e92021-03-18 23:00:55 +11003996void AudioFlinger::PlaybackThread::collectTimestamps_l()
3997{
3998 // Collect timestamp statistics for the Playback Thread types that support it.
3999 if (mType != MIXER
4000 && mType != DUPLICATING
4001 && mType != DIRECT
4002 && mType != OFFLOAD) {
4003 return;
4004 }
4005 if (mStandby) {
4006 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4007 return;
4008 } else if (mHwPaused) {
4009 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4010 return;
4011 }
4012
4013 // Gather the framesReleased counters for all active tracks,
4014 // and associate with the sink frames written out. We need
4015 // this to convert the sink timestamp to the track timestamp.
4016 bool kernelLocationUpdate = false;
4017 ExtendedTimestamp timestamp; // use private copy to fetch
4018
4019 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4020 // HAL may be draining some small duration buffered data for fade out.
4021 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4022 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4023 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4024 mSampleRate);
4025
4026 if (isTimestampCorrectionEnabled()) {
4027 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4028 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4029 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4030 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4031 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4032 = correctedTimestamp.mFrames;
4033 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4034 = correctedTimestamp.mTimeNs;
4035 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4036 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4037 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4038
4039 // Note: Downstream latency only added if timestamp correction enabled.
4040 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4041 const int64_t newPosition =
4042 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4043 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4044 // prevent retrograde
4045 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4046 newPosition,
4047 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4048 - mSuspendedFrames));
4049 }
4050 }
4051
4052 // We always fetch the timestamp here because often the downstream
4053 // sink will block while writing.
4054
4055 // We keep track of the last valid kernel position in case we are in underrun
4056 // and the normal mixer period is the same as the fast mixer period, or there
4057 // is some error from the HAL.
4058 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4059 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4060 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4061 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4062 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4063
4064 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4065 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4066 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4067 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4068 }
4069
4070 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4071 kernelLocationUpdate = true;
4072 } else {
4073 ALOGVV("getTimestamp error - no valid kernel position");
4074 }
4075
4076 // copy over kernel info
4077 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4078 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4079 + mSuspendedFrames; // add frames discarded when suspended
4080 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4081 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4082 } else {
4083 mTimestampVerifier.error();
4084 }
4085
4086 // mFramesWritten for non-offloaded tracks are contiguous
4087 // even after standby() is called. This is useful for the track frame
4088 // to sink frame mapping.
4089 bool serverLocationUpdate = false;
4090 if (mFramesWritten != mLastFramesWritten) {
4091 serverLocationUpdate = true;
4092 mLastFramesWritten = mFramesWritten;
4093 }
4094 // Only update timestamps if there is a meaningful change.
4095 // Either the kernel timestamp must be valid or we have written something.
4096 if (kernelLocationUpdate || serverLocationUpdate) {
4097 if (serverLocationUpdate) {
4098 // use the time before we called the HAL write - it is a bit more accurate
4099 // to when the server last read data than the current time here.
4100 //
4101 // If we haven't written anything, mLastIoBeginNs will be -1
4102 // and we use systemTime().
4103 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4104 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4105 ? systemTime() : mLastIoBeginNs;
4106 }
4107
4108 for (const sp<Track> &t : mActiveTracks) {
4109 if (!t->isFastTrack()) {
4110 t->updateTrackFrameInfo(
4111 t->mAudioTrackServerProxy->framesReleased(),
4112 mFramesWritten,
4113 mSampleRate,
4114 mTimestamp);
4115 }
4116 }
4117 }
4118
4119 if (audio_has_proportional_frames(mFormat)) {
4120 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4121 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4122 mLatencyMs.add(latencyMs);
4123 }
4124 }
4125#if 0
4126 // logFormat example
4127 if (z % 100 == 0) {
4128 timespec ts;
4129 clock_gettime(CLOCK_MONOTONIC, &ts);
4130 LOGT("This is an integer %d, this is a float %f, this is my "
4131 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4132 LOGT("A deceptive null-terminated string %\0");
4133 }
4134 ++z;
4135#endif
4136}
4137
Eric Laurentbfb1b832013-01-07 09:53:42 -08004138// removeTracks_l() must be called with ThreadBase::mLock held
4139void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4140{
Andy Hungfe726a62018-09-27 15:17:25 -07004141 for (const auto& track : tracksToRemove) {
4142 mActiveTracks.remove(track);
4143 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4144 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4145 if (chain != 0) {
4146 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4147 __func__, track->id(), chain.get(), track->sessionId());
4148 chain->decActiveTrackCnt();
4149 }
4150 // If an external client track, inform APM we're no longer active, and remove if needed.
4151 // We do this under lock so that the state is consistent if the Track is destroyed.
4152 if (track->isExternalTrack()) {
4153 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004154 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004155 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004156 }
4157 }
Andy Hungfe726a62018-09-27 15:17:25 -07004158 if (track->isTerminated()) {
4159 // remove from our tracks vector
4160 removeTrack_l(track);
4161 }
jiabineb3bda02020-06-30 14:07:03 -07004162 if (mHapticChannelCount > 0 &&
4163 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4164 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004165 mLock.unlock();
4166 // Unlock due to VibratorService will lock for this call and will
4167 // call Tracks.mute/unmute which also require thread's lock.
4168 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4169 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004170
4171 // When the track is stop, set the haptic intensity as MUTE
4172 // for the HapticGenerator effect.
4173 if (chain != nullptr) {
4174 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4175 }
jiabin245cdd92018-12-07 17:55:15 -08004176 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004177 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004178}
Eric Laurent81784c32012-11-19 14:55:58 -08004179
Eric Laurentaccc1472013-09-20 09:36:34 -07004180status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4181{
4182 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004183 ExtendedTimestamp ets;
4184 status_t status = mNormalSink->getTimestamp(ets);
4185 if (status == NO_ERROR) {
4186 status = ets.getBestTimestamp(&timestamp);
4187 }
4188 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004189 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004190 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004191 collectTimestamps_l();
4192 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4193 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004194 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004195 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4196 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4197 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4198 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4199 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004200 }
4201 return INVALID_OPERATION;
4202}
Eric Laurent1c333e22014-05-20 10:48:17 -07004203
Eric Laurenteab90452019-06-24 15:17:46 -07004204// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4205// still applied by the mixer.
4206// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4207// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4208// if more than one track are active
4209status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4210{
4211 status_t result = NO_ERROR;
4212 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4213 if (*volume != mLeftVolFloat) {
4214 result = mOutput->stream->setVolume(*volume, *volume);
4215 ALOGE_IF(result != OK,
4216 "Error when setting output stream volume: %d", result);
4217 if (result == NO_ERROR) {
4218 mLeftVolFloat = *volume;
4219 }
4220 }
4221 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4222 // remove stream volume contribution from software volume.
4223 if (mLeftVolFloat == *volume) {
4224 *volume = 1.0f;
4225 }
4226 }
4227 return result;
4228}
4229
Eric Laurent054d9d32015-04-24 08:48:48 -07004230status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4231 audio_patch_handle_t *handle)
4232{
Andy Hungf60abce2016-08-26 11:37:54 -07004233 status_t status;
4234 if (property_get_bool("af.patch_park", false /* default_value */)) {
4235 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4236 // or if HAL does not properly lock against access.
4237 AutoPark<FastMixer> park(mFastMixer);
4238 status = PlaybackThread::createAudioPatch_l(patch, handle);
4239 } else {
4240 status = PlaybackThread::createAudioPatch_l(patch, handle);
4241 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004242 return status;
4243}
4244
Eric Laurent1c333e22014-05-20 10:48:17 -07004245status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4246 audio_patch_handle_t *handle)
4247{
4248 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004249
4250 // store new device and send to effects
4251 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004252 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004253 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004254 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4255 && !mOutput->audioHwDev->supportsAudioPatches(),
4256 "Enumerated device type(%#x) must not be used "
4257 "as it does not support audio patches",
4258 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004259 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004260 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4261 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004262 }
4263
François Gaffie0c280aa2018-07-25 10:02:15 +02004264 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004265#ifdef ADD_BATTERY_DATA
4266 // when changing the audio output device, call addBatteryData to notify
4267 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004268 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004269 uint32_t params = 0;
4270 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004271 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004272 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004273 }
4274
Eric Laurent054d9d32015-04-24 08:48:48 -07004275 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004276 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004277 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4278 }
4279
4280 if (params != 0) {
4281 addBatteryData(params);
4282 }
4283 }
4284#endif
4285
4286 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004287 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004288 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004289
jiabinc52b1ff2019-10-31 17:20:42 -07004290 // mPatch.num_sinks is not set when the thread is created so that
4291 // the first patch creation triggers an ioConfigChanged callback
4292 bool configChanged = (mPatch.num_sinks == 0) ||
4293 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004294 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004295 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004296 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004297
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004298 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004299 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4300 status = hwDevice->createAudioPatch(patch->num_sources,
4301 patch->sources,
4302 patch->num_sinks,
4303 patch->sinks,
4304 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004305 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004306 char *address;
4307 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4308 //FIXME: we only support address on first sink with HAL version < 3.0
4309 address = audio_device_address_to_parameter(
4310 patch->sinks[0].ext.device.type,
4311 patch->sinks[0].ext.device.address);
4312 } else {
4313 address = (char *)calloc(1, 1);
4314 }
4315 AudioParameter param = AudioParameter(String8(address));
4316 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004317 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004318 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004319 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004320 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004321 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004322
4323 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004324 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004325 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004326 // also dispatch to active AudioTracks for MediaMetrics
4327 for (const auto &track : mActiveTracks) {
4328 track->logEndInterval();
4329 track->logBeginInterval(patchSinksAsString);
4330 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004331
Eric Laurente8726fe2015-06-26 09:39:24 -07004332 if (configChanged) {
4333 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4334 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004335 return status;
4336}
4337
Eric Laurent054d9d32015-04-24 08:48:48 -07004338status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4339{
Andy Hungf60abce2016-08-26 11:37:54 -07004340 status_t status;
4341 if (property_get_bool("af.patch_park", false /* default_value */)) {
4342 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4343 // or if HAL does not properly lock against access.
4344 AutoPark<FastMixer> park(mFastMixer);
4345 status = PlaybackThread::releaseAudioPatch_l(handle);
4346 } else {
4347 status = PlaybackThread::releaseAudioPatch_l(handle);
4348 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004349 return status;
4350}
4351
Eric Laurent1c333e22014-05-20 10:48:17 -07004352status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4353{
4354 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004355
jiabinc52b1ff2019-10-31 17:20:42 -07004356 mPatch = audio_patch{};
4357 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004358
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004359 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004360 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4361 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004362 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004363 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004364 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004365 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004366 }
4367 return status;
4368}
4369
Eric Laurent83b88082014-06-20 18:31:16 -07004370void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4371{
4372 Mutex::Autolock _l(mLock);
4373 mTracks.add(track);
4374}
4375
4376void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4377{
4378 Mutex::Autolock _l(mLock);
4379 destroyTrack_l(track);
4380}
4381
Mikhail Naganovdc769682018-05-04 15:34:08 -07004382void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004383{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004384 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004385 config->role = AUDIO_PORT_ROLE_SOURCE;
4386 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4387 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004388 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4389 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4390 config->flags.output = mOutput->flags;
4391 }
Eric Laurent83b88082014-06-20 18:31:16 -07004392}
4393
Eric Laurent81784c32012-11-19 14:55:58 -08004394// ----------------------------------------------------------------------------
4395
4396AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004397 audio_io_handle_t id, bool systemReady, type_t type)
4398 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004399 // mAudioMixer below
4400 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004401 mFastMixerFutex(0),
4402 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004403 // mOutputSink below
4404 // mPipeSink below
4405 // mNormalSink below
4406{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004407 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004408 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004409 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004410 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004411 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4412 mNormalFrameCount);
4413 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4414
Andy Hungfbfc3952015-01-15 13:33:51 -08004415 if (type == DUPLICATING) {
4416 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4417 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4418 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4419 return;
4420 }
Eric Laurent81784c32012-11-19 14:55:58 -08004421 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004422 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004423 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004424 const NBAIO_Format offers[1] = {Format_from_SR_C(
4425 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004426#if !LOG_NDEBUG
4427 ssize_t index =
4428#else
4429 (void)
4430#endif
4431 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004432 ALOG_ASSERT(index == 0);
4433
4434 // initialize fast mixer depending on configuration
4435 bool initFastMixer;
4436 switch (kUseFastMixer) {
4437 case FastMixer_Never:
4438 initFastMixer = false;
4439 break;
4440 case FastMixer_Always:
4441 initFastMixer = true;
4442 break;
4443 case FastMixer_Static:
4444 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004445 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4446 // where the period is less than an experimentally determined threshold that can be
4447 // scheduled reliably with CFS. However, the BT A2DP HAL is
4448 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4449 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004450 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004451 break;
4452 }
Andy Hungfda69402017-02-15 14:33:12 -08004453 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4454 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4455 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004456 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004457 audio_format_t fastMixerFormat;
4458 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4459 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4460 } else {
4461 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4462 }
4463 if (mFormat != fastMixerFormat) {
4464 // change our Sink format to accept our intermediate precision
4465 mFormat = fastMixerFormat;
4466 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004467 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004468 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4469 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4470 }
Eric Laurent81784c32012-11-19 14:55:58 -08004471
4472 // create a MonoPipe to connect our submix to FastMixer
4473 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004474
Andy Hung1258c1a2014-05-23 21:22:17 -07004475 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004476 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004477 format.mFormat = fastMixerFormat;
4478 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4479
Eric Laurent81784c32012-11-19 14:55:58 -08004480 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4481 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4482 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4483 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4484 const NBAIO_Format offers[1] = {format};
4485 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004486#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004487 ssize_t index =
4488#else
4489 (void)
4490#endif
4491 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004492 ALOG_ASSERT(index == 0);
4493 monoPipe->setAvgFrames((mScreenState & 1) ?
4494 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4495 mPipeSink = monoPipe;
4496
Eric Laurent81784c32012-11-19 14:55:58 -08004497 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004498 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004499 FastMixerStateQueue *sq = mFastMixer->sq();
4500#ifdef STATE_QUEUE_DUMP
4501 sq->setObserverDump(&mStateQueueObserverDump);
4502 sq->setMutatorDump(&mStateQueueMutatorDump);
4503#endif
4504 FastMixerState *state = sq->begin();
4505 FastTrack *fastTrack = &state->mFastTracks[0];
4506 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4507 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4508 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004509 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4510 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4511 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004512 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004513 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004514 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004515 fastTrack->mGeneration++;
4516 state->mFastTracksGen++;
4517 state->mTrackMask = 1;
4518 // fast mixer will use the HAL output sink
4519 state->mOutputSink = mOutputSink.get();
4520 state->mOutputSinkGen++;
4521 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004522 // specify sink channel mask when haptic channel mask present as it can not
4523 // be calculated directly from channel count
4524 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004525 ? AUDIO_CHANNEL_NONE
4526 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004527 state->mCommand = FastMixerState::COLD_IDLE;
4528 // already done in constructor initialization list
4529 //mFastMixerFutex = 0;
4530 state->mColdFutexAddr = &mFastMixerFutex;
4531 state->mColdGen++;
4532 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004533 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4534 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004535 sq->end();
4536 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4537
Eric Tan0513b5d2018-09-17 10:32:48 -07004538 NBLog::thread_info_t info;
4539 info.id = mId;
4540 info.type = NBLog::FASTMIXER;
4541 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4542
Eric Laurent81784c32012-11-19 14:55:58 -08004543 // start the fast mixer
4544 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4545 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004546 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004547 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004548
4549#ifdef AUDIO_WATCHDOG
4550 // create and start the watchdog
4551 mAudioWatchdog = new AudioWatchdog();
4552 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4553 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4554 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004555 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004556#endif
Andy Hung8946a282018-04-19 20:04:56 -07004557 } else {
4558#ifdef TEE_SINK
4559 // Only use the MixerThread tee if there is no FastMixer.
4560 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4561 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4562#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004563 }
4564
4565 switch (kUseFastMixer) {
4566 case FastMixer_Never:
4567 case FastMixer_Dynamic:
4568 mNormalSink = mOutputSink;
4569 break;
4570 case FastMixer_Always:
4571 mNormalSink = mPipeSink;
4572 break;
4573 case FastMixer_Static:
4574 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4575 break;
4576 }
4577}
4578
4579AudioFlinger::MixerThread::~MixerThread()
4580{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004581 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004582 FastMixerStateQueue *sq = mFastMixer->sq();
4583 FastMixerState *state = sq->begin();
4584 if (state->mCommand == FastMixerState::COLD_IDLE) {
4585 int32_t old = android_atomic_inc(&mFastMixerFutex);
4586 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004587 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004588 }
4589 }
4590 state->mCommand = FastMixerState::EXIT;
4591 sq->end();
4592 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4593 mFastMixer->join();
4594 // Though the fast mixer thread has exited, it's state queue is still valid.
4595 // We'll use that extract the final state which contains one remaining fast track
4596 // corresponding to our sub-mix.
4597 state = sq->begin();
4598 ALOG_ASSERT(state->mTrackMask == 1);
4599 FastTrack *fastTrack = &state->mFastTracks[0];
4600 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4601 delete fastTrack->mBufferProvider;
4602 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004603 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004604#ifdef AUDIO_WATCHDOG
4605 if (mAudioWatchdog != 0) {
4606 mAudioWatchdog->requestExit();
4607 mAudioWatchdog->requestExitAndWait();
4608 mAudioWatchdog.clear();
4609 }
4610#endif
4611 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004612 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004613 delete mAudioMixer;
4614}
4615
4616
4617uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4618{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004619 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004620 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4621 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4622 }
4623 return latency;
4624}
4625
Eric Laurentbfb1b832013-01-07 09:53:42 -08004626ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004627{
4628 // FIXME we should only do one push per cycle; confirm this is true
4629 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004630 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004631 FastMixerStateQueue *sq = mFastMixer->sq();
4632 FastMixerState *state = sq->begin();
4633 if (state->mCommand != FastMixerState::MIX_WRITE &&
4634 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4635 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004636
4637 // FIXME workaround for first HAL write being CPU bound on some devices
4638 ATRACE_BEGIN("write");
4639 mOutput->write((char *)mSinkBuffer, 0);
4640 ATRACE_END();
4641
Eric Laurent81784c32012-11-19 14:55:58 -08004642 int32_t old = android_atomic_inc(&mFastMixerFutex);
4643 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004644 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004645 }
4646#ifdef AUDIO_WATCHDOG
4647 if (mAudioWatchdog != 0) {
4648 mAudioWatchdog->resume();
4649 }
4650#endif
4651 }
4652 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004653#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004654 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004655 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004656#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004657 sq->end();
4658 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4659 if (kUseFastMixer == FastMixer_Dynamic) {
4660 mNormalSink = mPipeSink;
4661 }
4662 } else {
4663 sq->end(false /*didModify*/);
4664 }
4665 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004666 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004667}
4668
4669void AudioFlinger::MixerThread::threadLoop_standby()
4670{
4671 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004672 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004673 FastMixerStateQueue *sq = mFastMixer->sq();
4674 FastMixerState *state = sq->begin();
4675 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004676 // Report any frames trapped in the Monopipe
4677 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4678 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4679 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4680 "monoPipeWritten:%lld monoPipeLeft:%lld",
4681 (long long)mFramesWritten, (long long)mSuspendedFrames,
4682 (long long)mPipeSink->framesWritten(), pipeFrames);
4683 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4684
Eric Laurent81784c32012-11-19 14:55:58 -08004685 state->mCommand = FastMixerState::COLD_IDLE;
4686 state->mColdFutexAddr = &mFastMixerFutex;
4687 state->mColdGen++;
4688 mFastMixerFutex = 0;
4689 sq->end();
4690 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4691 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4692 if (kUseFastMixer == FastMixer_Dynamic) {
4693 mNormalSink = mOutputSink;
4694 }
4695#ifdef AUDIO_WATCHDOG
4696 if (mAudioWatchdog != 0) {
4697 mAudioWatchdog->pause();
4698 }
4699#endif
4700 } else {
4701 sq->end(false /*didModify*/);
4702 }
4703 }
4704 PlaybackThread::threadLoop_standby();
4705}
4706
Eric Laurentbfb1b832013-01-07 09:53:42 -08004707bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4708{
4709 return false;
4710}
4711
4712bool AudioFlinger::PlaybackThread::shouldStandby_l()
4713{
4714 return !mStandby;
4715}
4716
4717bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4718{
4719 Mutex::Autolock _l(mLock);
4720 return waitingAsyncCallback_l();
4721}
4722
Eric Laurent81784c32012-11-19 14:55:58 -08004723// shared by MIXER and DIRECT, overridden by DUPLICATING
4724void AudioFlinger::PlaybackThread::threadLoop_standby()
4725{
4726 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004727 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004728 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004729 // discard any pending drain or write ack by incrementing sequence
4730 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4731 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004732 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004733 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4734 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004736 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004737}
4738
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004739void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4740{
4741 ALOGV("signal playback thread");
4742 broadcast_l();
4743}
4744
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004745void AudioFlinger::PlaybackThread::onAsyncError()
4746{
4747 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4748 invalidateTracks((audio_stream_type_t)i);
4749 }
4750}
4751
Eric Laurent81784c32012-11-19 14:55:58 -08004752void AudioFlinger::MixerThread::threadLoop_mix()
4753{
Eric Laurent81784c32012-11-19 14:55:58 -08004754 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004755 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004756 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004757 // increase sleep time progressively when application underrun condition clears.
4758 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4759 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4760 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004761 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004762 sleepTimeShift--;
4763 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004764 mSleepTimeUs = 0;
4765 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004766 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004767
Eric Laurent81784c32012-11-19 14:55:58 -08004768}
4769
4770void AudioFlinger::MixerThread::threadLoop_sleepTime()
4771{
4772 // If no tracks are ready, sleep once for the duration of an output
4773 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004774 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004775 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004776 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4777 // Using the Monopipe availableToWrite, we estimate the
4778 // sleep time to retry for more data (before we underrun).
4779 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4780 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4781 const size_t pipeFrames = monoPipe->maxFrames();
4782 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4783 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4784 const size_t framesDelay = std::min(
4785 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4786 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4787 pipeFrames, framesLeft, framesDelay);
4788 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4789 } else {
4790 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4791 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4792 mSleepTimeUs = kMinThreadSleepTimeUs;
4793 }
4794 // reduce sleep time in case of consecutive application underruns to avoid
4795 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4796 // duration we would end up writing less data than needed by the audio HAL if
4797 // the condition persists.
4798 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4799 sleepTimeShift++;
4800 }
Eric Laurent81784c32012-11-19 14:55:58 -08004801 }
4802 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004803 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004804 }
4805 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004806 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4807 // before effects processing or output.
4808 if (mMixerBufferValid) {
4809 memset(mMixerBuffer, 0, mMixerBufferSize);
4810 } else {
4811 memset(mSinkBuffer, 0, mSinkBufferSize);
4812 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004813 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004814 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4815 "anticipated start");
4816 }
4817 // TODO add standby time extension fct of effect tail
4818}
4819
4820// prepareTracks_l() must be called with ThreadBase::mLock held
4821AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4822 Vector< sp<Track> > *tracksToRemove)
4823{
Andy Hungc0691382018-09-12 18:01:57 -07004824 // clean up deleted track ids in AudioMixer before allocating new tracks
4825 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4826 // for each trackId, destroy it in the AudioMixer
4827 if (mAudioMixer->exists(trackId)) {
4828 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004829 }
4830 });
Andy Hungc0691382018-09-12 18:01:57 -07004831 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004832
4833 mixer_state mixerStatus = MIXER_IDLE;
4834 // find out which tracks need to be processed
4835 size_t count = mActiveTracks.size();
4836 size_t mixedTracks = 0;
4837 size_t tracksWithEffect = 0;
4838 // counts only _active_ fast tracks
4839 size_t fastTracks = 0;
4840 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4841
4842 float masterVolume = mMasterVolume;
4843 bool masterMute = mMasterMute;
4844
4845 if (masterMute) {
4846 masterVolume = 0;
4847 }
4848 // Delegate master volume control to effect in output mix effect chain if needed
4849 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4850 if (chain != 0) {
4851 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4852 chain->setVolume_l(&v, &v);
4853 masterVolume = (float)((v + (1 << 23)) >> 24);
4854 chain.clear();
4855 }
4856
4857 // prepare a new state to push
4858 FastMixerStateQueue *sq = NULL;
4859 FastMixerState *state = NULL;
4860 bool didModify = false;
4861 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004862 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004863 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004864 sq = mFastMixer->sq();
4865 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004866 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004867 }
4868
Andy Hung69aed5f2014-02-25 17:24:40 -08004869 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004870 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004871
Andy Hungbd3b2b02018-05-21 10:53:11 -07004872 // DeferredOperations handles statistics after setting mixerStatus.
4873 class DeferredOperations {
4874 public:
Andy Hungea840382020-05-05 21:50:17 -07004875 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4876 : mMixerStatus(mixerStatus)
4877 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004878
4879 // when leaving scope, tally frames properly.
4880 ~DeferredOperations() {
4881 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4882 // because that is when the underrun occurs.
4883 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004884 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004885 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004886 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004887 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004888 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004889 }
4890 }
Andy Hungea840382020-05-05 21:50:17 -07004891 // send the max underrun frames for this mixer period
4892 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004893 }
4894
4895 // tallyUnderrunFrames() is called to update the track counters
4896 // with the number of underrun frames for a particular mixer period.
4897 // We defer tallying until we know the final mixer status.
4898 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4899 mUnderrunFrames.emplace_back(track, underrunFrames);
4900 }
4901
4902 private:
4903 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004904 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004905 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004906 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004907 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004908
jiabin245cdd92018-12-07 17:55:15 -08004909 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004910 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004911 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004912
4913 // this const just means the local variable doesn't change
4914 Track* const track = t.get();
4915
4916 // process fast tracks
4917 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004918 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4919 "%s(%d): FastTrack(%d) present without FastMixer",
4920 __func__, id(), track->id());
4921
jiabin245cdd92018-12-07 17:55:15 -08004922 if (track->getHapticPlaybackEnabled()) {
4923 noFastHapticTrack = false;
4924 }
Eric Laurent81784c32012-11-19 14:55:58 -08004925
4926 // It's theoretically possible (though unlikely) for a fast track to be created
4927 // and then removed within the same normal mix cycle. This is not a problem, as
4928 // the track never becomes active so it's fast mixer slot is never touched.
4929 // The converse, of removing an (active) track and then creating a new track
4930 // at the identical fast mixer slot within the same normal mix cycle,
4931 // is impossible because the slot isn't marked available until the end of each cycle.
4932 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004933 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004934 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4935 FastTrack *fastTrack = &state->mFastTracks[j];
4936
4937 // Determine whether the track is currently in underrun condition,
4938 // and whether it had a recent underrun.
4939 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4940 FastTrackUnderruns underruns = ftDump->mUnderruns;
4941 uint32_t recentFull = (underruns.mBitFields.mFull -
4942 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4943 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4944 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4945 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4946 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4947 uint32_t recentUnderruns = recentPartial + recentEmpty;
4948 track->mObservedUnderruns = underruns;
4949 // don't count underruns that occur while stopping or pausing
4950 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004951 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004952 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4953 recentUnderruns > 0) {
4954 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004955 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004956 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004957 // Immediately account for FastTrack underruns.
4958 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004959
4960 // This is similar to the state machine for normal tracks,
4961 // with a few modifications for fast tracks.
4962 bool isActive = true;
4963 switch (track->mState) {
4964 case TrackBase::STOPPING_1:
4965 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004966 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004967 track->mState = TrackBase::STOPPING_2;
4968 }
4969 break;
4970 case TrackBase::PAUSING:
4971 // ramp down is not yet implemented
4972 track->setPaused();
4973 break;
4974 case TrackBase::RESUMING:
4975 // ramp up is not yet implemented
4976 track->mState = TrackBase::ACTIVE;
4977 break;
4978 case TrackBase::ACTIVE:
4979 if (recentFull > 0 || recentPartial > 0) {
4980 // track has provided at least some frames recently: reset retry count
4981 track->mRetryCount = kMaxTrackRetries;
4982 }
4983 if (recentUnderruns == 0) {
4984 // no recent underruns: stay active
4985 break;
4986 }
4987 // there has recently been an underrun of some kind
4988 if (track->sharedBuffer() == 0) {
4989 // were any of the recent underruns "empty" (no frames available)?
4990 if (recentEmpty == 0) {
4991 // no, then ignore the partial underruns as they are allowed indefinitely
4992 break;
4993 }
4994 // there has recently been an "empty" underrun: decrement the retry counter
4995 if (--(track->mRetryCount) > 0) {
4996 break;
4997 }
4998 // indicate to client process that the track was disabled because of underrun;
4999 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005000 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005001 // remove from active list, but state remains ACTIVE [confusing but true]
5002 isActive = false;
5003 break;
5004 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005005 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005006 case TrackBase::STOPPING_2:
5007 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005008 case TrackBase::STOPPED:
5009 case TrackBase::FLUSHED: // flush() while active
5010 // Check for presentation complete if track is inactive
5011 // We have consumed all the buffers of this track.
5012 // This would be incomplete if we auto-paused on underrun
5013 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005014 uint32_t latency = 0;
5015 status_t result = mOutput->stream->getLatency(&latency);
5016 ALOGE_IF(result != OK,
5017 "Error when retrieving output stream latency: %d", result);
5018 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005019 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005020 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5021 // track stays in active list until presentation is complete
5022 break;
5023 }
5024 }
5025 if (track->isStopping_2()) {
5026 track->mState = TrackBase::STOPPED;
5027 }
5028 if (track->isStopped()) {
5029 // Can't reset directly, as fast mixer is still polling this track
5030 // track->reset();
5031 // So instead mark this track as needing to be reset after push with ack
5032 resetMask |= 1 << i;
5033 }
5034 isActive = false;
5035 break;
5036 case TrackBase::IDLE:
5037 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005038 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005039 }
5040
5041 if (isActive) {
5042 // was it previously inactive?
5043 if (!(state->mTrackMask & (1 << j))) {
5044 ExtendedAudioBufferProvider *eabp = track;
5045 VolumeProvider *vp = track;
5046 fastTrack->mBufferProvider = eabp;
5047 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005048 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005049 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005050 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005051 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005052 fastTrack->mGeneration++;
5053 state->mTrackMask |= 1 << j;
5054 didModify = true;
5055 // no acknowledgement required for newly active tracks
5056 }
Kevin Rocard12381092018-04-11 09:19:59 -07005057 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005058 float volume;
5059 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5060 volume = 0.f;
5061 } else {
5062 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5063 }
5064
5065 handleVoipVolume_l(&volume);
5066
Eric Laurent81784c32012-11-19 14:55:58 -08005067 // cache the combined master volume and stream type volume for fast mixer; this
5068 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005069 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005070 proxy->framesReleased()).first;
5071 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005072 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005073 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5074 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5075 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005076
Kevin Rocard12381092018-04-11 09:19:59 -07005077 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005078 ++fastTracks;
5079 } else {
5080 // was it previously active?
5081 if (state->mTrackMask & (1 << j)) {
5082 fastTrack->mBufferProvider = NULL;
5083 fastTrack->mGeneration++;
5084 state->mTrackMask &= ~(1 << j);
5085 didModify = true;
5086 // If any fast tracks were removed, we must wait for acknowledgement
5087 // because we're about to decrement the last sp<> on those tracks.
5088 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5089 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005090 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5091 // AudioTrack may start (which may not be with a start() but with a write()
5092 // after underrun) and immediately paused or released. In that case the
5093 // FastTrack state hasn't had time to update.
5094 // TODO Remove the ALOGW when this theory is confirmed.
5095 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005096 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5097 j, track->mState, state->mTrackMask, recentUnderruns,
5098 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005099 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005100 }
5101 tracksToRemove->add(track);
5102 // Avoids a misleading display in dumpsys
5103 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5104 }
jiabin245cdd92018-12-07 17:55:15 -08005105 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5106 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5107 didModify = true;
5108 }
Eric Laurent81784c32012-11-19 14:55:58 -08005109 continue;
5110 }
5111
5112 { // local variable scope to avoid goto warning
5113
5114 audio_track_cblk_t* cblk = track->cblk();
5115
5116 // The first time a track is added we wait
5117 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005118 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005119
5120 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005121 // use the trackId as the AudioMixer name.
5122 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005123 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005124 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005125 track->mChannelMask,
5126 track->mFormat,
5127 track->mSessionId);
5128 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005129 ALOGW("%s(): AudioMixer cannot create track(%d)"
5130 " mask %#x, format %#x, sessionId %d",
5131 __func__, trackId,
5132 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005133 tracksToRemove->add(track);
5134 track->invalidate(); // consider it dead.
5135 continue;
5136 }
5137 }
5138
Eric Laurent81784c32012-11-19 14:55:58 -08005139 // make sure that we have enough frames to mix one full buffer.
5140 // enforce this condition only once to enable draining the buffer in case the client
5141 // app does not call stop() and relies on underrun to stop:
5142 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5143 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005144 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005145 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005146 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005147
5148 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005149 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005150 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5151 // add frames already consumed but not yet released by the resampler
5152 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005153 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005154
Eric Laurent81784c32012-11-19 14:55:58 -08005155 uint32_t minFrames = 1;
5156 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5157 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005158 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005159 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005160
5161 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005162 if (ATRACE_ENABLED()) {
5163 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005164 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005165 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005166 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005167 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005168 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005169 !track->isPaused() && !track->isTerminated())
5170 {
Andy Hungc0691382018-09-12 18:01:57 -07005171 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005172
5173 mixedTracks++;
5174
Andy Hung69aed5f2014-02-25 17:24:40 -08005175 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5176 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005177 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005178 if (track->mainBuffer() != mSinkBuffer &&
5179 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005180 if (mEffectBufferEnabled) {
5181 mEffectBufferValid = true; // Later can set directly.
5182 }
Eric Laurent81784c32012-11-19 14:55:58 -08005183 chain = getEffectChain_l(track->sessionId());
5184 // Delegate volume control to effect in track effect chain if needed
5185 if (chain != 0) {
5186 tracksWithEffect++;
5187 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005188 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005189 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005190 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005191 }
5192 }
5193
5194
5195 int param = AudioMixer::VOLUME;
5196 if (track->mFillingUpStatus == Track::FS_FILLED) {
5197 // no ramp for the first volume setting
5198 track->mFillingUpStatus = Track::FS_ACTIVE;
5199 if (track->mState == TrackBase::RESUMING) {
5200 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005201 // If a new track is paused immediately after start, do not ramp on resume.
5202 if (cblk->mServer != 0) {
5203 param = AudioMixer::RAMP_VOLUME;
5204 }
Eric Laurent81784c32012-11-19 14:55:58 -08005205 }
Andy Hungc0691382018-09-12 18:01:57 -07005206 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005207 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005208 // FIXME should not make a decision based on mServer
5209 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005210 // If the track is stopped before the first frame was mixed,
5211 // do not apply ramp
5212 param = AudioMixer::RAMP_VOLUME;
5213 }
5214
5215 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005216 uint32_t vl, vr; // in U8.24 integer format
5217 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005218 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005219 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005220 // Always fetch volumeshaper volume to ensure state is updated.
5221 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5222 const float vh = track->getVolumeHandler()->getVolume(
5223 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005224
Eric Laurenteab90452019-06-24 15:17:46 -07005225 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5226 v = 0;
5227 }
5228
5229 handleVoipVolume_l(&v);
5230
5231 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005232 vl = vr = 0;
5233 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005234 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005235 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005236 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005237 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5238 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005239 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005240 if (vlf > GAIN_FLOAT_UNITY) {
5241 ALOGV("Track left volume out of range: %.3g", vlf);
5242 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005243 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005244 if (vrf > GAIN_FLOAT_UNITY) {
5245 ALOGV("Track right volume out of range: %.3g", vrf);
5246 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005247 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005248 // now apply the master volume and stream type volume and shaper volume
5249 vlf *= v * vh;
5250 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005251 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005252 // then derive vl and vr as U8.24 versions for the effect chain
5253 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5254 vl = (uint32_t) (scaleto8_24 * vlf);
5255 vr = (uint32_t) (scaleto8_24 * vrf);
5256 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005257 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005258 // send level comes from shared memory and so may be corrupt
5259 if (sendLevel > MAX_GAIN_INT) {
5260 ALOGV("Track send level out of range: %04X", sendLevel);
5261 sendLevel = MAX_GAIN_INT;
5262 }
Andy Hung6be49402014-05-30 10:42:03 -07005263 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5264 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005265 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005266
Kevin Rocard12381092018-04-11 09:19:59 -07005267 track->setFinalVolume((vrf + vlf) / 2.f);
5268
Eric Laurent81784c32012-11-19 14:55:58 -08005269 // Delegate volume control to effect in track effect chain if needed
5270 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5271 // Do not ramp volume if volume is controlled by effect
5272 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005273 // Update remaining floating point volume levels
5274 vlf = (float)vl / (1 << 24);
5275 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005276 track->mHasVolumeController = true;
5277 } else {
5278 // force no volume ramp when volume controller was just disabled or removed
5279 // from effect chain to avoid volume spike
5280 if (track->mHasVolumeController) {
5281 param = AudioMixer::VOLUME;
5282 }
5283 track->mHasVolumeController = false;
5284 }
5285
Eric Laurent81784c32012-11-19 14:55:58 -08005286 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005287 mAudioMixer->setBufferProvider(trackId, track);
5288 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005289
Andy Hungc0691382018-09-12 18:01:57 -07005290 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5291 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5292 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005293 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005294 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005295 AudioMixer::TRACK,
5296 AudioMixer::FORMAT, (void *)track->format());
5297 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005298 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005299 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005300 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005301 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005302 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005303 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005304 AudioMixer::MIXER_CHANNEL_MASK,
5305 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005306 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005307 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005308 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005309 if (reqSampleRate == 0) {
5310 reqSampleRate = mSampleRate;
5311 } else if (reqSampleRate > maxSampleRate) {
5312 reqSampleRate = maxSampleRate;
5313 }
Eric Laurent81784c32012-11-19 14:55:58 -08005314 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005315 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005316 AudioMixer::RESAMPLE,
5317 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005318 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005319
Andy Hung333ab962019-05-28 20:23:35 -07005320 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005321 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005322 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005323 AudioMixer::TIMESTRETCH,
5324 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005325 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005326
Andy Hung69aed5f2014-02-25 17:24:40 -08005327 /*
5328 * Select the appropriate output buffer for the track.
5329 *
Andy Hung98ef9782014-03-04 14:46:50 -08005330 * Tracks with effects go into their own effects chain buffer
5331 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005332 *
5333 * Other tracks can use mMixerBuffer for higher precision
5334 * channel accumulation. If this buffer is enabled
5335 * (mMixerBufferEnabled true), then selected tracks will accumulate
5336 * into it.
5337 *
5338 */
5339 if (mMixerBufferEnabled
5340 && (track->mainBuffer() == mSinkBuffer
5341 || track->mainBuffer() == mMixerBuffer)) {
5342 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005343 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005344 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005345 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005346 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005347 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005348 AudioMixer::TRACK,
5349 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5350 // TODO: override track->mainBuffer()?
5351 mMixerBufferValid = true;
5352 } else {
5353 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005354 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005355 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005356 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005357 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005358 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005359 AudioMixer::TRACK,
5360 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5361 }
Eric Laurent81784c32012-11-19 14:55:58 -08005362 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005363 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005364 AudioMixer::TRACK,
5365 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005366 mAudioMixer->setParameter(
5367 trackId,
5368 AudioMixer::TRACK,
5369 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005370 mAudioMixer->setParameter(
5371 trackId,
5372 AudioMixer::TRACK,
5373 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005374
5375 // reset retry count
5376 track->mRetryCount = kMaxTrackRetries;
5377
5378 // If one track is ready, set the mixer ready if:
5379 // - the mixer was not ready during previous round OR
5380 // - no other track is not ready
5381 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5382 mixerStatus != MIXER_TRACKS_ENABLED) {
5383 mixerStatus = MIXER_TRACKS_READY;
5384 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005385
5386 // Enable the next few lines to instrument a test for underrun log handling.
5387 // TODO: Remove when we have a better way of testing the underrun log.
5388#if 0
5389 static int i;
5390 if ((++i & 0xf) == 0) {
5391 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5392 }
5393#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005394 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005395 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005396 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005397 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5398 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005399 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005400 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005401 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005402
Eric Laurent81784c32012-11-19 14:55:58 -08005403 // clear effect chain input buffer if an active track underruns to avoid sending
5404 // previous audio buffer again to effects
5405 chain = getEffectChain_l(track->sessionId());
5406 if (chain != 0) {
5407 chain->clearInputBuffer();
5408 }
5409
Andy Hungc0691382018-09-12 18:01:57 -07005410 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005411 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5412 track->isStopped() || track->isPaused()) {
5413 // We have consumed all the buffers of this track.
5414 // Remove it from the list of active tracks.
5415 // TODO: use actual buffer filling status instead of latency when available from
5416 // audio HAL
5417 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005418 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005419 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5420 if (track->isStopped()) {
5421 track->reset();
5422 }
5423 tracksToRemove->add(track);
5424 }
5425 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005426 // No buffers for this track. Give it a few chances to
5427 // fill a buffer, then remove it from active list.
5428 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005429 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5430 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005431 tracksToRemove->add(track);
5432 // indicate to client process that the track was disabled because of underrun;
5433 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005434 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005435 // If one track is not ready, mark the mixer also not ready if:
5436 // - the mixer was ready during previous round OR
5437 // - no other track is ready
5438 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5439 mixerStatus != MIXER_TRACKS_READY) {
5440 mixerStatus = MIXER_TRACKS_ENABLED;
5441 }
5442 }
Andy Hungc0691382018-09-12 18:01:57 -07005443 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005444 }
5445
5446 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005447
5448 }
5449
jiabin245cdd92018-12-07 17:55:15 -08005450 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5451 // When there is no fast track playing haptic and FastMixer exists,
5452 // enabling the first FastTrack, which provides mixed data from normal
5453 // tracks, to play haptic data.
5454 FastTrack *fastTrack = &state->mFastTracks[0];
5455 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5456 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5457 didModify = true;
5458 }
5459 }
5460
Eric Laurent81784c32012-11-19 14:55:58 -08005461 // Push the new FastMixer state if necessary
5462 bool pauseAudioWatchdog = false;
5463 if (didModify) {
5464 state->mFastTracksGen++;
5465 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5466 if (kUseFastMixer == FastMixer_Dynamic &&
5467 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5468 state->mCommand = FastMixerState::COLD_IDLE;
5469 state->mColdFutexAddr = &mFastMixerFutex;
5470 state->mColdGen++;
5471 mFastMixerFutex = 0;
5472 if (kUseFastMixer == FastMixer_Dynamic) {
5473 mNormalSink = mOutputSink;
5474 }
5475 // If we go into cold idle, need to wait for acknowledgement
5476 // so that fast mixer stops doing I/O.
5477 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5478 pauseAudioWatchdog = true;
5479 }
Eric Laurent81784c32012-11-19 14:55:58 -08005480 }
5481 if (sq != NULL) {
5482 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005483 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5484 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5485 // when bringing the output sink into standby.)
5486 //
5487 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5488 //
5489 // This occurs with BT suspend when we idle the FastMixer with
5490 // active tracks, which may be added or removed.
5491 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005492 }
5493#ifdef AUDIO_WATCHDOG
5494 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5495 mAudioWatchdog->pause();
5496 }
5497#endif
5498
5499 // Now perform the deferred reset on fast tracks that have stopped
5500 while (resetMask != 0) {
5501 size_t i = __builtin_ctz(resetMask);
5502 ALOG_ASSERT(i < count);
5503 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005504 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005505 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5506 track->reset();
5507 }
5508
Andy Hung80d03d22018-04-10 10:32:11 -07005509 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5510 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5511 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5512 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5513 // See also the implementation of destroyTrack_l().
5514 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005515 const int trackId = track->id();
5516 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5517 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005518 }
5519 }
5520
Eric Laurent81784c32012-11-19 14:55:58 -08005521 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005522 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005523
Eric Laurent97d547d2014-09-02 14:45:53 -07005524 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5525 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005526 }
5527
5528 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005529 // as long as there are effects we should clear the effects buffer, to avoid
5530 // passing a non-clean buffer to the effect chain
5531 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005532 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005533 // sink or mix buffer must be cleared if all tracks are connected to an
5534 // effect chain as in this case the mixer will not write to the sink or mix buffer
5535 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005536 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5537 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005538 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005539 if (mMixerBufferValid) {
5540 memset(mMixerBuffer, 0, mMixerBufferSize);
5541 // TODO: In testing, mSinkBuffer below need not be cleared because
5542 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5543 // after mixing.
5544 //
5545 // To enforce this guarantee:
5546 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5547 // (mixedTracks == 0 && fastTracks > 0))
5548 // must imply MIXER_TRACKS_READY.
5549 // Later, we may clear buffers regardless, and skip much of this logic.
5550 }
Andy Hung98ef9782014-03-04 14:46:50 -08005551 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005552 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005553 }
5554
5555 // if any fast tracks, then status is ready
5556 mMixerStatusIgnoringFastTracks = mixerStatus;
5557 if (fastTracks > 0) {
5558 mixerStatus = MIXER_TRACKS_READY;
5559 }
5560 return mixerStatus;
5561}
5562
Eric Laurentad7dd962016-09-22 12:38:37 -07005563// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005564uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005565{
5566 uint32_t trackCount = 0;
5567 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005568 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005569 trackCount++;
5570 }
5571 }
5572 return trackCount;
5573}
5574
Andy Hung1bc088a2018-02-09 15:57:31 -08005575// isTrackAllowed_l() must be called with ThreadBase::mLock held
5576bool AudioFlinger::MixerThread::isTrackAllowed_l(
5577 audio_channel_mask_t channelMask, audio_format_t format,
5578 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005579{
Andy Hung1bc088a2018-02-09 15:57:31 -08005580 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5581 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005582 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005583 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005584 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005585 ALOGW("%s: invalid format: %#x", __func__, format);
5586 return false;
5587 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005588 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005589 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5590 return false;
5591 }
5592 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005593}
5594
Eric Laurent10351942014-05-08 18:49:52 -07005595// checkForNewParameter_l() must be called with ThreadBase::mLock held
5596bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5597 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005598{
Eric Laurent81784c32012-11-19 14:55:58 -08005599 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005600 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005601
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005602 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005603
Eric Laurent10351942014-05-08 18:49:52 -07005604 AudioParameter param = AudioParameter(keyValuePair);
5605 int value;
5606 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5607 reconfig = true;
5608 }
5609 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005610 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005611 status = BAD_VALUE;
5612 } else {
5613 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005614 reconfig = true;
5615 }
Eric Laurent10351942014-05-08 18:49:52 -07005616 }
5617 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005618 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005619 status = BAD_VALUE;
5620 } else {
5621 // no need to save value, since it's constant
5622 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005623 }
Eric Laurent10351942014-05-08 18:49:52 -07005624 }
5625 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5626 // do not accept frame count changes if tracks are open as the track buffer
5627 // size depends on frame count and correct behavior would not be guaranteed
5628 // if frame count is changed after track creation
5629 if (!mTracks.isEmpty()) {
5630 status = INVALID_OPERATION;
5631 } else {
5632 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005633 }
Eric Laurent10351942014-05-08 18:49:52 -07005634 }
5635 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005636 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005637 }
Eric Laurent81784c32012-11-19 14:55:58 -08005638
Eric Laurent10351942014-05-08 18:49:52 -07005639 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005640 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005641 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005642 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005643 if (!mStandby) {
5644 mThreadMetrics.logEndInterval();
5645 mStandby = true;
5646 }
Eric Laurent10351942014-05-08 18:49:52 -07005647 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005648 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005649 }
Eric Laurent10351942014-05-08 18:49:52 -07005650 if (status == NO_ERROR && reconfig) {
5651 readOutputParameters_l();
5652 delete mAudioMixer;
5653 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005654 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005655 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005656 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005657 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005658 track->mChannelMask,
5659 track->mFormat,
5660 track->mSessionId);
5661 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005662 "%s(): AudioMixer cannot create track(%d)"
5663 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005664 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005665 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005666 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005667 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005668 }
Eric Laurent81784c32012-11-19 14:55:58 -08005669 }
5670
Dean Wheatley68918102021-03-19 22:09:19 +11005671 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005672}
5673
5674
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005675void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005676{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005677 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005678 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005679 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005680 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005681 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5682 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5683 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005684 if (hasFastMixer()) {
5685 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5686
5687 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5688 // while we are dumping it. It may be inconsistent, but it won't mutate!
5689 // This is a large object so we place it on the heap.
5690 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005691 const std::unique_ptr<FastMixerDumpState> copy =
5692 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005693 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005694
5695#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005696 // Similar for state queue
5697 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5698 observerCopy.dump(fd);
5699 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5700 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005701#endif
5702
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005703#ifdef AUDIO_WATCHDOG
5704 if (mAudioWatchdog != 0) {
5705 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5706 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5707 wdCopy.dump(fd);
5708 }
5709#endif
5710
5711 } else {
5712 dprintf(fd, " No FastMixer\n");
5713 }
Eric Laurent81784c32012-11-19 14:55:58 -08005714}
5715
5716uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5717{
5718 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5719}
5720
5721uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5722{
5723 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5724}
5725
5726void AudioFlinger::MixerThread::cacheParameters_l()
5727{
5728 PlaybackThread::cacheParameters_l();
5729
5730 // FIXME: Relaxed timing because of a certain device that can't meet latency
5731 // Should be reduced to 2x after the vendor fixes the driver issue
5732 // increase threshold again due to low power audio mode. The way this warning
5733 // threshold is calculated and its usefulness should be reconsidered anyway.
5734 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5735}
5736
5737// ----------------------------------------------------------------------------
5738
5739AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005740 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5741 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005742{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005743 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005744}
5745
Eric Laurent81784c32012-11-19 14:55:58 -08005746AudioFlinger::DirectOutputThread::~DirectOutputThread()
5747{
5748}
5749
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005750void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005751{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005752 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005753 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5754 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5755}
5756
5757void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5758{
5759 Mutex::Autolock _l(mLock);
5760 if (mMasterBalance != balance) {
5761 mMasterBalance.store(balance);
5762 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5763 broadcast_l();
5764 }
5765}
5766
Eric Laurent5850c4c2016-11-10 13:04:31 -08005767void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005768{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005769 float left, right;
5770
Andy Hung333ab962019-05-28 20:23:35 -07005771 // Ensure volumeshaper state always advances even when muted.
5772 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5773 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5774 proxy->framesReleased());
5775 mVolumeShaperActive = shaperActive;
5776
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005777 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005778 left = right = 0;
5779 } else {
5780 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005781 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005782
Glenn Kastenc56f3422014-03-21 17:53:17 -07005783 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5784 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5785 if (left > GAIN_FLOAT_UNITY) {
5786 left = GAIN_FLOAT_UNITY;
5787 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005788 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005789 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5790 if (right > GAIN_FLOAT_UNITY) {
5791 right = GAIN_FLOAT_UNITY;
5792 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005793 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005794 }
5795
5796 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005797 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005798 if (left != mLeftVolFloat || right != mRightVolFloat) {
5799 mLeftVolFloat = left;
5800 mRightVolFloat = right;
5801
Eric Laurentbfb1b832013-01-07 09:53:42 -08005802 // Delegate volume control to effect in track effect chain if needed
5803 // only one effect chain can be present on DirectOutputThread, so if
5804 // there is one, the track is connected to it
5805 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005806 // if effect chain exists, volume is handled by it.
5807 // Convert volumes from float to 8.24
5808 uint32_t vl = (uint32_t)(left * (1 << 24));
5809 uint32_t vr = (uint32_t)(right * (1 << 24));
5810 // Direct/Offload effect chains set output volume in setVolume_l().
5811 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5812 } else {
5813 // otherwise we directly set the volume.
5814 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005815 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005816 }
5817 }
5818}
5819
Phil Burk43b4dcc2015-06-09 16:53:44 -07005820void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5821{
5822 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005823 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005824
Eric Laurent0f0631e2015-07-06 18:01:25 -07005825 if (previousTrack != 0 && latestTrack != 0) {
5826 if (mType == DIRECT) {
5827 if (previousTrack.get() != latestTrack.get()) {
5828 mFlushPending = true;
5829 }
5830 } else /* mType == OFFLOAD */ {
5831 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5832 mFlushPending = true;
5833 }
5834 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005835 } else if (previousTrack == 0) {
5836 // there could be an old track added back during track transition for direct
5837 // output, so always issues flush to flush data of the previous track if it
5838 // was already destroyed with HAL paused, then flush can resume the playback
5839 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005840 }
5841 PlaybackThread::onAddNewTrack_l();
5842}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005843
Eric Laurent81784c32012-11-19 14:55:58 -08005844AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5845 Vector< sp<Track> > *tracksToRemove
5846)
5847{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005848 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005849 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005850 bool doHwPause = false;
5851 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005852
5853 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005854 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005855 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005856 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005857 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005858 continue;
5859 }
5860
Eric Laurent5850c4c2016-11-10 13:04:31 -08005861 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005862#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005863 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005864#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005865 // Only consider last track started for volume and mixer state control.
5866 // In theory an older track could underrun and restart after the new one starts
5867 // but as we only care about the transition phase between two tracks on a
5868 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005869 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005870 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005871
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005872 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005873 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005874 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005875 doHwPause = true;
5876 mHwPaused = true;
5877 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005878 } else if (track->isFlushPending()) {
5879 track->flushAck();
5880 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005881 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005882 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005883 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005884 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005885 if (last) {
5886 mLeftVolFloat = mRightVolFloat = -1.0;
5887 if (mHwPaused) {
5888 doHwResume = true;
5889 mHwPaused = false;
5890 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005891 }
5892 }
5893
Eric Laurent81784c32012-11-19 14:55:58 -08005894 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005895 // for all its buffers to be filled before processing it.
5896 // Allow draining the buffer in case the client
5897 // app does not call stop() and relies on underrun to stop:
5898 // hence the test on (track->mRetryCount > 1).
5899 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005900 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005901 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005902 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005903 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005904 minFrames = mNormalFrameCount;
5905 } else {
5906 minFrames = 1;
5907 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005908
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005909 const size_t framesReady = track->framesReady();
5910 const int trackId = track->id();
5911 if (ATRACE_ENABLED()) {
5912 std::string traceName("nRdy");
5913 traceName += std::to_string(trackId);
5914 ATRACE_INT(traceName.c_str(), framesReady);
5915 }
5916 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005917 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005918 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005919 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005920
5921 if (track->mFillingUpStatus == Track::FS_FILLED) {
5922 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005923 if (last) {
5924 // make sure processVolume_l() will apply new volume even if 0
5925 mLeftVolFloat = mRightVolFloat = -1.0;
5926 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005927 if (!mHwSupportsPause) {
5928 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005929 }
5930 }
5931
5932 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005933 processVolume_l(track, last);
5934 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005935 sp<Track> previousTrack = mPreviousTrack.promote();
5936 if (previousTrack != 0) {
5937 if (track != previousTrack.get()) {
5938 // Flush any data still being written from last track
5939 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005940 // Invalidate previous track to force a seek when resuming.
5941 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005942 }
5943 }
5944 mPreviousTrack = track;
5945
Eric Laurentd595b7c2013-04-03 17:27:56 -07005946 // reset retry count
5947 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005948 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005949 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005950 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005951 doHwResume = true;
5952 mHwPaused = false;
5953 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005954 }
Eric Laurent81784c32012-11-19 14:55:58 -08005955 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005956 // clear effect chain input buffer if the last active track started underruns
5957 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005958 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005959 mEffectChains[0]->clearInputBuffer();
5960 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005961 if (track->isStopping_1()) {
5962 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005963 if (last && mHwPaused) {
5964 doHwResume = true;
5965 mHwPaused = false;
5966 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005967 }
5968 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5969 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005970 // We have consumed all the buffers of this track.
5971 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005972 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005973 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005974 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5975 } else {
5976 audioHALFrames = 0;
5977 }
5978
Andy Hung818e7a32016-02-16 18:08:07 -08005979 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005980 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005981 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08005982 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005983 if (track->isStopping_2()) {
5984 track->mState = TrackBase::STOPPED;
5985 }
Eric Laurent81784c32012-11-19 14:55:58 -08005986 if (track->isStopped()) {
5987 track->reset();
5988 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005989 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005990 }
5991 } else {
5992 // No buffers for this track. Give it a few chances to
5993 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005994 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005995 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005996 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005997 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005998 // indicate to client process that the track was disabled because of underrun;
5999 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006000 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006001 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07006002 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6003 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006004 framesReady, minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08006005 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07006006 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006007 doHwPause = true;
6008 mHwPaused = true;
6009 }
Eric Laurent81784c32012-11-19 14:55:58 -08006010 }
6011 }
6012 }
6013 }
6014
Eric Laurentd1f69b02014-12-15 14:33:13 -08006015 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006016 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006017 for (size_t i = 0; i < mTracks.size(); i++) {
6018 if (mTracks[i]->isFlushPending()) {
6019 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006020 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006021 }
6022 }
6023 }
6024
6025 // make sure the pause/flush/resume sequence is executed in the right order.
6026 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6027 // before flush and then resume HW. This can happen in case of pause/flush/resume
6028 // if resume is received before pause is executed.
6029 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006030 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006031 status_t result = mOutput->stream->pause();
6032 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006033 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006034 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006035 flushHw_l();
6036 }
6037 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006038 status_t result = mOutput->stream->resume();
6039 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006040 }
Eric Laurent81784c32012-11-19 14:55:58 -08006041 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006042 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006043
6044 return mixerStatus;
6045}
6046
6047void AudioFlinger::DirectOutputThread::threadLoop_mix()
6048{
Eric Laurent81784c32012-11-19 14:55:58 -08006049 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006050 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006051 // output audio to hardware
6052 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006053 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006054 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006055 status_t status = mActiveTrack->getNextBuffer(&buffer);
6056 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006057 // no need to pad with 0 for compressed audio
6058 if (audio_has_proportional_frames(mFormat)) {
6059 memset(curBuf, 0, frameCount * mFrameSize);
6060 }
Eric Laurent81784c32012-11-19 14:55:58 -08006061 break;
6062 }
6063 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6064 frameCount -= buffer.frameCount;
6065 curBuf += buffer.frameCount * mFrameSize;
6066 mActiveTrack->releaseBuffer(&buffer);
6067 }
Andy Hung2098f272014-02-27 14:00:06 -08006068 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006069 mSleepTimeUs = 0;
6070 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006071 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006072}
6073
6074void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6075{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006076 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006077 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006078 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006079 return;
6080 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006081 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006082 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07006083 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006084 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006085 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006086 }
Phil Burkfdb3c072016-02-09 10:47:02 -08006087 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08006088 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006089 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006090 }
6091}
6092
Eric Laurentd1f69b02014-12-15 14:33:13 -08006093void AudioFlinger::DirectOutputThread::threadLoop_exit()
6094{
6095 {
6096 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006097 for (size_t i = 0; i < mTracks.size(); i++) {
6098 if (mTracks[i]->isFlushPending()) {
6099 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006100 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006101 }
6102 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006103 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006104 flushHw_l();
6105 }
6106 }
6107 PlaybackThread::threadLoop_exit();
6108}
6109
6110// must be called with thread mutex locked
6111bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6112{
6113 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006114 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006115
6116 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6117 // after a timeout and we will enter standby then.
6118 if (mTracks.size() > 0) {
6119 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006120 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6121 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006122 }
6123
Eric Laurent5cff4032015-05-26 13:49:58 -07006124 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006125}
6126
Eric Laurent10351942014-05-08 18:49:52 -07006127// checkForNewParameter_l() must be called with ThreadBase::mLock held
6128bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6129 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006130{
6131 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006132 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006133
Eric Laurent10351942014-05-08 18:49:52 -07006134 AudioParameter param = AudioParameter(keyValuePair);
6135 int value;
6136 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006137 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006138 }
Eric Laurent10351942014-05-08 18:49:52 -07006139 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6140 // do not accept frame count changes if tracks are open as the track buffer
6141 // size depends on frame count and correct behavior would not be garantied
6142 // if frame count is changed after track creation
6143 if (!mTracks.isEmpty()) {
6144 status = INVALID_OPERATION;
6145 } else {
6146 reconfig = true;
6147 }
6148 }
6149 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006150 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006151 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006152 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006153 if (!mStandby) {
6154 mThreadMetrics.logEndInterval();
6155 mStandby = true;
6156 }
Eric Laurent10351942014-05-08 18:49:52 -07006157 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006158 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006159 }
6160 if (status == NO_ERROR && reconfig) {
6161 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006162 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006163 }
6164 }
6165
Dean Wheatley68918102021-03-19 22:09:19 +11006166 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006167}
6168
6169uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6170{
6171 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006172 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006173 time = PlaybackThread::activeSleepTimeUs();
6174 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006175 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006176 }
6177 return time;
6178}
6179
6180uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6181{
6182 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006183 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006184 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6185 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006186 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006187 }
6188 return time;
6189}
6190
6191uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6192{
6193 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006194 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006195 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6196 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006197 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006198 }
6199 return time;
6200}
6201
6202void AudioFlinger::DirectOutputThread::cacheParameters_l()
6203{
6204 PlaybackThread::cacheParameters_l();
6205
6206 // use shorter standby delay as on normal output to release
6207 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006208 // no delay on outputs with HW A/V sync
6209 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006210 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006211 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006212 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006213 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006214 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006215 }
Eric Laurent81784c32012-11-19 14:55:58 -08006216}
6217
Eric Laurente659ef42014-09-29 13:06:46 -07006218void AudioFlinger::DirectOutputThread::flushHw_l()
6219{
Phil Burk062e67a2015-02-11 13:40:50 -08006220 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006221 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006222 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006223 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006224 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006225}
6226
Andy Hung10cbff12017-02-21 17:30:14 -08006227int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6228 // If a VolumeShaper is active, we must wake up periodically to update volume.
6229 const int64_t NS_PER_MS = 1000000;
6230 return mVolumeShaperActive ?
6231 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6232}
6233
Eric Laurent81784c32012-11-19 14:55:58 -08006234// ----------------------------------------------------------------------------
6235
Eric Laurentbfb1b832013-01-07 09:53:42 -08006236AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006237 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006238 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006239 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006240 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006241 mDrainSequence(0),
6242 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006243{
6244}
6245
6246AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6247{
6248}
6249
6250void AudioFlinger::AsyncCallbackThread::onFirstRef()
6251{
6252 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6253}
6254
6255bool AudioFlinger::AsyncCallbackThread::threadLoop()
6256{
6257 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006258 uint32_t writeAckSequence;
6259 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006260 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006261
6262 {
6263 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006264 while (!((mWriteAckSequence & 1) ||
6265 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006266 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006267 exitPending())) {
6268 mWaitWorkCV.wait(mLock);
6269 }
6270
Eric Laurentbfb1b832013-01-07 09:53:42 -08006271 if (exitPending()) {
6272 break;
6273 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006274 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6275 mWriteAckSequence, mDrainSequence);
6276 writeAckSequence = mWriteAckSequence;
6277 mWriteAckSequence &= ~1;
6278 drainSequence = mDrainSequence;
6279 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006280 asyncError = mAsyncError;
6281 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006282 }
6283 {
Eric Laurent4de95592013-09-26 15:28:21 -07006284 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6285 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006286 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006287 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006288 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006289 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006290 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006291 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006292 if (asyncError) {
6293 playbackThread->onAsyncError();
6294 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006295 }
6296 }
6297 }
6298 return false;
6299}
6300
6301void AudioFlinger::AsyncCallbackThread::exit()
6302{
6303 ALOGV("AsyncCallbackThread::exit");
6304 Mutex::Autolock _l(mLock);
6305 requestExit();
6306 mWaitWorkCV.broadcast();
6307}
6308
Eric Laurent3b4529e2013-09-05 18:09:19 -07006309void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006310{
6311 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006312 // bit 0 is cleared
6313 mWriteAckSequence = sequence << 1;
6314}
6315
6316void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6317{
6318 Mutex::Autolock _l(mLock);
6319 // ignore unexpected callbacks
6320 if (mWriteAckSequence & 2) {
6321 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006322 mWaitWorkCV.signal();
6323 }
6324}
6325
Eric Laurent3b4529e2013-09-05 18:09:19 -07006326void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006327{
6328 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006329 // bit 0 is cleared
6330 mDrainSequence = sequence << 1;
6331}
6332
6333void AudioFlinger::AsyncCallbackThread::resetDraining()
6334{
6335 Mutex::Autolock _l(mLock);
6336 // ignore unexpected callbacks
6337 if (mDrainSequence & 2) {
6338 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006339 mWaitWorkCV.signal();
6340 }
6341}
6342
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006343void AudioFlinger::AsyncCallbackThread::setAsyncError()
6344{
6345 Mutex::Autolock _l(mLock);
6346 mAsyncError = true;
6347 mWaitWorkCV.signal();
6348}
6349
Eric Laurentbfb1b832013-01-07 09:53:42 -08006350
6351// ----------------------------------------------------------------------------
6352AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006353 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6354 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006355 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6356 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006357{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006358 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006359 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006360 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006361}
6362
Eric Laurentbfb1b832013-01-07 09:53:42 -08006363void AudioFlinger::OffloadThread::threadLoop_exit()
6364{
6365 if (mFlushPending || mHwPaused) {
6366 // If a flush is pending or track was paused, just discard buffered data
6367 flushHw_l();
6368 } else {
6369 mMixerStatus = MIXER_DRAIN_ALL;
6370 threadLoop_drain();
6371 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006372 if (mUseAsyncWrite) {
6373 ALOG_ASSERT(mCallbackThread != 0);
6374 mCallbackThread->exit();
6375 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006376 PlaybackThread::threadLoop_exit();
6377}
6378
6379AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6380 Vector< sp<Track> > *tracksToRemove
6381)
6382{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006383 size_t count = mActiveTracks.size();
6384
6385 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006386 bool doHwPause = false;
6387 bool doHwResume = false;
6388
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006389 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006390
Eric Laurentbfb1b832013-01-07 09:53:42 -08006391 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006392 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006393 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006394#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006395 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006396#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006397 // Only consider last track started for volume and mixer state control.
6398 // In theory an older track could underrun and restart after the new one starts
6399 // but as we only care about the transition phase between two tracks on a
6400 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006401 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006402 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006403
Haynes Mathew George7844f672014-01-15 12:32:55 -08006404 if (track->isInvalid()) {
6405 ALOGW("An invalidated track shouldn't be in active list");
6406 tracksToRemove->add(track);
6407 continue;
6408 }
6409
6410 if (track->mState == TrackBase::IDLE) {
6411 ALOGW("An idle track shouldn't be in active list");
6412 continue;
6413 }
6414
Eric Laurentbfb1b832013-01-07 09:53:42 -08006415 if (track->isPausing()) {
6416 track->setPaused();
6417 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006418 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006419 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006420 mHwPaused = true;
6421 }
6422 // If we were part way through writing the mixbuffer to
6423 // the HAL we must save this until we resume
6424 // BUG - this will be wrong if a different track is made active,
6425 // in that case we want to discard the pending data in the
6426 // mixbuffer and tell the client to present it again when the
6427 // track is resumed
6428 mPausedWriteLength = mCurrentWriteLength;
6429 mPausedBytesRemaining = mBytesRemaining;
6430 mBytesRemaining = 0; // stop writing
6431 }
6432 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006433 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006434 if (track->isStopping_1()) {
6435 track->mRetryCount = kMaxTrackStopRetriesOffload;
6436 } else {
6437 track->mRetryCount = kMaxTrackRetriesOffload;
6438 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006439 track->flushAck();
6440 if (last) {
6441 mFlushPending = true;
6442 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006443 } else if (track->isResumePending()){
6444 track->resumeAck();
6445 if (last) {
6446 if (mPausedBytesRemaining) {
6447 // Need to continue write that was interrupted
6448 mCurrentWriteLength = mPausedWriteLength;
6449 mBytesRemaining = mPausedBytesRemaining;
6450 mPausedBytesRemaining = 0;
6451 }
6452 if (mHwPaused) {
6453 doHwResume = true;
6454 mHwPaused = false;
6455 // threadLoop_mix() will handle the case that we need to
6456 // resume an interrupted write
6457 }
6458 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006459 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006460
Eric Laurent3df841a2016-07-15 15:15:40 -07006461 mLeftVolFloat = mRightVolFloat = -1.0;
6462
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006463 // Do not handle new data in this iteration even if track->framesReady()
6464 mixerStatus = MIXER_TRACKS_ENABLED;
6465 }
6466 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006467 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006468 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006469 if (track->mFillingUpStatus == Track::FS_FILLED) {
6470 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006471 if (last) {
6472 // make sure processVolume_l() will apply new volume even if 0
6473 mLeftVolFloat = mRightVolFloat = -1.0;
6474 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006475 }
6476
6477 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006478 sp<Track> previousTrack = mPreviousTrack.promote();
6479 if (previousTrack != 0) {
6480 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006481 // Flush any data still being written from last track
6482 mBytesRemaining = 0;
6483 if (mPausedBytesRemaining) {
6484 // Last track was paused so we also need to flush saved
6485 // mixbuffer state and invalidate track so that it will
6486 // re-submit that unwritten data when it is next resumed
6487 mPausedBytesRemaining = 0;
6488 // Invalidate is a bit drastic - would be more efficient
6489 // to have a flag to tell client that some of the
6490 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006491 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006492 }
6493 // flush data already sent to the DSP if changing audio session as audio
6494 // comes from a different source. Also invalidate previous track to force a
6495 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006496 if (previousTrack->sessionId() != track->sessionId()) {
6497 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006498 }
6499 }
6500 }
6501 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006502 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006503 if (track->isStopping_1()) {
6504 track->mRetryCount = kMaxTrackStopRetriesOffload;
6505 } else {
6506 track->mRetryCount = kMaxTrackRetriesOffload;
6507 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006508 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006509 mixerStatus = MIXER_TRACKS_READY;
6510 }
6511 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006512 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006513 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006514 if (--(track->mRetryCount) <= 0) {
6515 // Hardware buffer can hold a large amount of audio so we must
6516 // wait for all current track's data to drain before we say
6517 // that the track is stopped.
6518 if (mBytesRemaining == 0) {
6519 // Only start draining when all data in mixbuffer
6520 // has been written
6521 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6522 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6523 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6524 if (last && !mStandby) {
6525 // do not modify drain sequence if we are already draining. This happens
6526 // when resuming from pause after drain.
6527 if ((mDrainSequence & 1) == 0) {
6528 mSleepTimeUs = 0;
6529 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6530 mixerStatus = MIXER_DRAIN_TRACK;
6531 mDrainSequence += 2;
6532 }
6533 if (mHwPaused) {
6534 // It is possible to move from PAUSED to STOPPING_1 without
6535 // a resume so we must ensure hardware is running
6536 doHwResume = true;
6537 mHwPaused = false;
6538 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006539 }
6540 }
Eric Laurente93cc032016-05-05 10:15:10 -07006541 } else if (last) {
6542 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6543 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006544 }
6545 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006546 // Drain has completed or we are in standby, signal presentation complete
6547 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006548 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006549 uint32_t latency = 0;
6550 status_t result = mOutput->stream->getLatency(&latency);
6551 ALOGE_IF(result != OK,
6552 "Error when retrieving output stream latency: %d", result);
6553 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006554 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006555 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006556 track->presentationComplete(framesWritten, audioHALFrames);
6557 track->reset();
6558 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006559 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006560 if (!mUseAsyncWrite) {
6561 // If we don't get explicit drain notification we must
6562 // register discontinuity regardless of whether this is
6563 // the previous (!last) or the upcoming (last) track
6564 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006565 mTimestampVerifier.discontinuity(
6566 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006567 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006568 }
6569 } else {
6570 // No buffers for this track. Give it a few chances to
6571 // fill a buffer, then remove it from active list.
6572 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006573 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006574 uint64_t position = 0;
6575 struct timespec unused;
6576 // The running check restarts the retry counter at least once.
6577 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6578 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6579 running = true;
6580 mOffloadUnderrunPosition = position;
6581 }
6582 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006583 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6584 (long long)position, (long long)mOffloadUnderrunPosition);
6585 }
6586 if (running) { // still running, give us more time.
6587 track->mRetryCount = kMaxTrackRetriesOffload;
6588 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006589 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6590 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006591 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006592 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006593 // it will then automatically call start() when data is available
6594 track->disable();
6595 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006596 } else if (last){
6597 mixerStatus = MIXER_TRACKS_ENABLED;
6598 }
6599 }
6600 }
6601 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006602 if (track->isReady()) { // check ready to prevent premature start.
6603 processVolume_l(track, last);
6604 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006605 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006606
Eric Laurentea0fade2013-10-04 16:23:48 -07006607 // make sure the pause/flush/resume sequence is executed in the right order.
6608 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6609 // before flush and then resume HW. This can happen in case of pause/flush/resume
6610 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006611 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006612 status_t result = mOutput->stream->pause();
6613 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006614 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006615 if (mFlushPending) {
6616 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006617 }
Eric Laurentfd477972013-10-25 18:10:40 -07006618 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006619 status_t result = mOutput->stream->resume();
6620 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006621 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006622
Eric Laurentbfb1b832013-01-07 09:53:42 -08006623 // remove all the tracks that need to be...
6624 removeTracks_l(*tracksToRemove);
6625
6626 return mixerStatus;
6627}
6628
Eric Laurentbfb1b832013-01-07 09:53:42 -08006629// must be called with thread mutex locked
6630bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6631{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006632 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6633 mWriteAckSequence, mDrainSequence);
6634 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006635 return true;
6636 }
6637 return false;
6638}
6639
Eric Laurentbfb1b832013-01-07 09:53:42 -08006640bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6641{
6642 Mutex::Autolock _l(mLock);
6643 return waitingAsyncCallback_l();
6644}
6645
6646void AudioFlinger::OffloadThread::flushHw_l()
6647{
Eric Laurente659ef42014-09-29 13:06:46 -07006648 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006649 // Flush anything still waiting in the mixbuffer
6650 mCurrentWriteLength = 0;
6651 mBytesRemaining = 0;
6652 mPausedWriteLength = 0;
6653 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006654 // reset bytes written count to reflect that DSP buffers are empty after flush.
6655 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006656 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006657
Eric Laurentbfb1b832013-01-07 09:53:42 -08006658 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006659 // discard any pending drain or write ack by incrementing sequence
6660 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6661 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006662 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006663 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6664 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006665 }
6666}
6667
Haynes Mathew George05317d22016-05-03 16:34:26 -07006668void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6669{
6670 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006671 if (PlaybackThread::invalidateTracks_l(streamType)) {
6672 mFlushPending = true;
6673 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006674}
6675
Eric Laurentbfb1b832013-01-07 09:53:42 -08006676// ----------------------------------------------------------------------------
6677
Eric Laurent81784c32012-11-19 14:55:58 -08006678AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006679 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006680 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006681 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006682 mWaitTimeMs(UINT_MAX)
6683{
6684 addOutputTrack(mainThread);
6685}
6686
6687AudioFlinger::DuplicatingThread::~DuplicatingThread()
6688{
6689 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6690 mOutputTracks[i]->destroy();
6691 }
6692}
6693
6694void AudioFlinger::DuplicatingThread::threadLoop_mix()
6695{
6696 // mix buffers...
6697 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006698 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006699 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006700 if (mMixerBufferValid) {
6701 memset(mMixerBuffer, 0, mMixerBufferSize);
6702 } else {
6703 memset(mSinkBuffer, 0, mSinkBufferSize);
6704 }
Eric Laurent81784c32012-11-19 14:55:58 -08006705 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006706 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006707 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006708 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006709 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006710}
6711
6712void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6713{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006714 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006715 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006716 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006717 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006718 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006719 }
6720 } else if (mBytesWritten != 0) {
6721 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6722 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006723 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006724 } else {
6725 // flush remaining overflow buffers in output tracks
6726 writeFrames = 0;
6727 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006728 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006729 }
6730}
6731
Eric Laurentbfb1b832013-01-07 09:53:42 -08006732ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006733{
6734 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006735 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6736
6737 // Consider the first OutputTrack for timestamp and frame counting.
6738
6739 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6740 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6741 // we always claim success.
6742 if (i == 0) {
6743 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6744 ALOGD_IF(correction != 0 && writeFrames != 0,
6745 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6746 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6747 mFramesWritten -= correction;
6748 }
6749
6750 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006751 }
Andy Hungcf10d742020-04-28 15:38:24 -07006752 if (mStandby) {
6753 mThreadMetrics.logBeginInterval();
6754 mStandby = false;
6755 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006756 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006757}
6758
6759void AudioFlinger::DuplicatingThread::threadLoop_standby()
6760{
6761 // DuplicatingThread implements standby by stopping all tracks
6762 for (size_t i = 0; i < outputTracks.size(); i++) {
6763 outputTracks[i]->stop();
6764 }
6765}
6766
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006767void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006768{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006769 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006770
6771 std::stringstream ss;
6772 const size_t numTracks = mOutputTracks.size();
6773 ss << " " << numTracks << " OutputTracks";
6774 if (numTracks > 0) {
6775 ss << ":";
6776 for (const auto &track : mOutputTracks) {
6777 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006778 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006779 if (thread.get() != nullptr) {
6780 ss << thread.get() << ", " << thread->id();
6781 } else {
6782 ss << "null";
6783 }
6784 ss << ")";
6785 }
6786 }
6787 ss << "\n";
6788 std::string result = ss.str();
6789 write(fd, result.c_str(), result.size());
6790}
6791
Eric Laurent81784c32012-11-19 14:55:58 -08006792void AudioFlinger::DuplicatingThread::saveOutputTracks()
6793{
6794 outputTracks = mOutputTracks;
6795}
6796
6797void AudioFlinger::DuplicatingThread::clearOutputTracks()
6798{
6799 outputTracks.clear();
6800}
6801
6802void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6803{
6804 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006805 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6806 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6807 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6808 const size_t frameCount =
6809 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6810 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6811 // from different OutputTracks and their associated MixerThreads (e.g. one may
6812 // nearly empty and the other may be dropping data).
6813
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006814 // TODO b/182392769: use identity util, move to server edge
6815 Identity identity = Identity();
6816 identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
6817 IPCThreadState::self()->getCallingUid()));
6818 identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
6819 IPCThreadState::self()->getCallingPid()));
Andy Hungc25b84a2015-01-14 19:04:10 -08006820 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006821 this,
6822 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006823 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006824 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006825 frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006826 identity);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006827 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6828 if (status != NO_ERROR) {
6829 ALOGE("addOutputTrack() initCheck failed %d", status);
6830 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006831 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006832 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6833 mOutputTracks.add(outputTrack);
6834 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6835 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006836}
6837
6838void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6839{
6840 Mutex::Autolock _l(mLock);
6841 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6842 if (mOutputTracks[i]->thread() == thread) {
6843 mOutputTracks[i]->destroy();
6844 mOutputTracks.removeAt(i);
6845 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006846 if (thread->getOutput() == mOutput) {
6847 mOutput = NULL;
6848 }
Eric Laurent81784c32012-11-19 14:55:58 -08006849 return;
6850 }
6851 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006852 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006853}
6854
6855// caller must hold mLock
6856void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6857{
6858 mWaitTimeMs = UINT_MAX;
6859 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6860 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6861 if (strong != 0) {
6862 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6863 if (waitTimeMs < mWaitTimeMs) {
6864 mWaitTimeMs = waitTimeMs;
6865 }
6866 }
6867 }
6868}
6869
6870
6871bool AudioFlinger::DuplicatingThread::outputsReady(
6872 const SortedVector< sp<OutputTrack> > &outputTracks)
6873{
6874 for (size_t i = 0; i < outputTracks.size(); i++) {
6875 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6876 if (thread == 0) {
6877 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6878 outputTracks[i].get());
6879 return false;
6880 }
6881 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6882 // see note at standby() declaration
6883 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6884 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6885 thread.get());
6886 return false;
6887 }
6888 }
6889 return true;
6890}
6891
Kevin Rocard12381092018-04-11 09:19:59 -07006892void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6893 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006894{
Kevin Rocard12381092018-04-11 09:19:59 -07006895 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6896 outputTrack->setMetadatas(metadata.tracks);
6897 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006898}
6899
Eric Laurent81784c32012-11-19 14:55:58 -08006900uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6901{
6902 return (mWaitTimeMs * 1000) / 2;
6903}
6904
6905void AudioFlinger::DuplicatingThread::cacheParameters_l()
6906{
6907 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6908 updateWaitTime_l();
6909
6910 MixerThread::cacheParameters_l();
6911}
6912
Eric Laurent6acd1d42017-01-04 14:23:29 -08006913
Eric Laurent81784c32012-11-19 14:55:58 -08006914// ----------------------------------------------------------------------------
6915// Record
6916// ----------------------------------------------------------------------------
6917
6918AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6919 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006920 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006921 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006922 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006923 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006924 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006925 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006926 mActiveTracks(&this->mLocalLog),
6927 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006928 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006929 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006930 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6931 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006932 // mFastCapture below
6933 , mFastCaptureFutex(0)
6934 // mInputSource
6935 // mPipeSink
6936 // mPipeSource
6937 , mPipeFramesP2(0)
6938 // mPipeMemory
6939 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006940 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006941 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006942{
Glenn Kastend7dca052015-03-05 16:05:54 -08006943 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6944 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006945
George Burgess IVa8f90c12020-05-14 11:27:19 -07006946 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07006947 mIsMsdDevice = strcmp(
6948 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6949 }
6950
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006951 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006952
Andy Hungc8fddf32018-08-08 18:32:37 -07006953 // TODO: We may also match on address as well as device type for
6954 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07006955 // TODO: This property should be ensure that only contains one single device type.
6956 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6957 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006958 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6959 : AUDIO_DEVICE_NONE));
6960
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006961 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006962 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006963 size_t numCounterOffers = 0;
6964 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006965#if !LOG_NDEBUG
6966 ssize_t index =
6967#else
6968 (void)
6969#endif
6970 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006971 ALOG_ASSERT(index == 0);
6972
6973 // initialize fast capture depending on configuration
6974 bool initFastCapture;
6975 switch (kUseFastCapture) {
6976 case FastCapture_Never:
6977 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006978 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006979 break;
6980 case FastCapture_Always:
6981 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006982 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006983 break;
6984 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006985 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006986 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6987 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6988 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006989 break;
6990 // case FastCapture_Dynamic:
6991 }
6992
6993 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006994 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006995 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006996 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6997 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006998 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006999 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007000 const sp<MemoryDealer> roHeap(readOnlyHeap());
7001 sp<IMemory> pipeMemory;
7002 if ((roHeap == 0) ||
7003 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007004 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007005 ALOGE("not enough memory for pipe buffer size=%zu; "
7006 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7007 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7008 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007009 goto failed;
7010 }
7011 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7012 memset(pipeBuffer, 0, pipeSize);
7013 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7014 const NBAIO_Format offers[1] = {format};
7015 size_t numCounterOffers = 0;
7016 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7017 ALOG_ASSERT(index == 0);
7018 mPipeSink = pipe;
7019 PipeReader *pipeReader = new PipeReader(*pipe);
7020 numCounterOffers = 0;
7021 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7022 ALOG_ASSERT(index == 0);
7023 mPipeSource = pipeReader;
7024 mPipeFramesP2 = pipeFramesP2;
7025 mPipeMemory = pipeMemory;
7026
7027 // create fast capture
7028 mFastCapture = new FastCapture();
7029 FastCaptureStateQueue *sq = mFastCapture->sq();
7030#ifdef STATE_QUEUE_DUMP
7031 // FIXME
7032#endif
7033 FastCaptureState *state = sq->begin();
7034 state->mCblk = NULL;
7035 state->mInputSource = mInputSource.get();
7036 state->mInputSourceGen++;
7037 state->mPipeSink = pipe;
7038 state->mPipeSinkGen++;
7039 state->mFrameCount = mFrameCount;
7040 state->mCommand = FastCaptureState::COLD_IDLE;
7041 // already done in constructor initialization list
7042 //mFastCaptureFutex = 0;
7043 state->mColdFutexAddr = &mFastCaptureFutex;
7044 state->mColdGen++;
7045 state->mDumpState = &mFastCaptureDumpState;
7046#ifdef TEE_SINK
7047 // FIXME
7048#endif
7049 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7050 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7051 sq->end();
7052 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7053
7054 // start the fast capture
7055 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7056 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007057 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007058 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007059#ifdef AUDIO_WATCHDOG
7060 // FIXME
7061#endif
7062
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007063 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007064 }
Andy Hung8946a282018-04-19 20:04:56 -07007065#ifdef TEE_SINK
7066 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7067 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7068#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007069failed: ;
7070
7071 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007072}
7073
Eric Laurent81784c32012-11-19 14:55:58 -08007074AudioFlinger::RecordThread::~RecordThread()
7075{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007076 if (mFastCapture != 0) {
7077 FastCaptureStateQueue *sq = mFastCapture->sq();
7078 FastCaptureState *state = sq->begin();
7079 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7080 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7081 if (old == -1) {
7082 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7083 }
7084 }
7085 state->mCommand = FastCaptureState::EXIT;
7086 sq->end();
7087 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7088 mFastCapture->join();
7089 mFastCapture.clear();
7090 }
7091 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007092 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007093 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007094}
7095
7096void AudioFlinger::RecordThread::onFirstRef()
7097{
Glenn Kastend7dca052015-03-05 16:05:54 -08007098 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007099}
7100
Eric Laurent555530a2017-02-07 18:17:24 -08007101void AudioFlinger::RecordThread::preExit()
7102{
7103 ALOGV(" preExit()");
7104 Mutex::Autolock _l(mLock);
7105 for (size_t i = 0; i < mTracks.size(); i++) {
7106 sp<RecordTrack> track = mTracks[i];
7107 track->invalidate();
7108 }
7109 mActiveTracks.clear();
7110 mStartStopCond.broadcast();
7111}
7112
Eric Laurent81784c32012-11-19 14:55:58 -08007113bool AudioFlinger::RecordThread::threadLoop()
7114{
Eric Laurent81784c32012-11-19 14:55:58 -08007115 nsecs_t lastWarning = 0;
7116
7117 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007118
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007119reacquire_wakelock:
7120 sp<RecordTrack> activeTrack;
7121 {
7122 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007123 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007124 }
7125
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007126 // used to request a deferred sleep, to be executed later while mutex is unlocked
7127 uint32_t sleepUs = 0;
7128
Andy Hung446f4df2019-02-21 12:26:41 -08007129 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7130
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007131 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007132 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007133 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007134
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007135 // activeTracks accumulates a copy of a subset of mActiveTracks
7136 Vector< sp<RecordTrack> > activeTracks;
7137
Glenn Kasten735f45f2014-08-18 15:51:59 -07007138 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007139 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007140
Glenn Kasten735f45f2014-08-18 15:51:59 -07007141 // reference to a fast track which is about to be removed
7142 sp<RecordTrack> fastTrackToRemove;
7143
Eric Laurent33403f02020-05-29 18:35:06 -07007144 bool silenceFastCapture = false;
7145
Eric Laurent81784c32012-11-19 14:55:58 -08007146 { // scope for mLock
7147 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007148
Eric Laurent021cf962014-05-13 10:18:14 -07007149 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007150
Eric Laurent000a4192014-01-29 15:17:32 -08007151 // check exitPending here because checkForNewParameters_l() and
7152 // checkForNewParameters_l() can temporarily release mLock
7153 if (exitPending()) {
7154 break;
7155 }
7156
Eric Laurent5c25d562016-07-13 17:17:45 -07007157 // sleep with mutex unlocked
7158 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007159 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007160 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7161 ATRACE_END();
7162 sleepUs = 0;
7163 continue;
7164 }
7165
Glenn Kasten2b806402013-11-20 16:37:38 -08007166 // if no active track(s), then standby and release wakelock
7167 size_t size = mActiveTracks.size();
7168 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007169 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007170 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007171 releaseWakeLock_l();
7172 ALOGV("RecordThread: loop stopping");
7173 // go to sleep
7174 mWaitWorkCV.wait(mLock);
7175 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007176 goto reacquire_wakelock;
7177 }
7178
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007179 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007180 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007181 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007182
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007183 activeTrack = mActiveTracks[i];
7184 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007185 if (activeTrack->isFastTrack()) {
7186 ALOG_ASSERT(fastTrackToRemove == 0);
7187 fastTrackToRemove = activeTrack;
7188 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007189 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007190 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007191 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007192 continue;
7193 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007194
7195 TrackBase::track_state activeTrackState = activeTrack->mState;
7196 switch (activeTrackState) {
7197
7198 case TrackBase::PAUSING:
7199 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007200 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007201 doBroadcast = true;
7202 size--;
7203 continue;
7204
7205 case TrackBase::STARTING_1:
7206 sleepUs = 10000;
7207 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007208 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007209 continue;
7210
7211 case TrackBase::STARTING_2:
7212 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007213 if (mStandby) {
7214 mThreadMetrics.logBeginInterval();
7215 mStandby = false;
7216 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007217 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007218 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007219 break;
7220
7221 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007222 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007223 break;
7224
Andy Hungce685402018-10-05 17:23:27 -07007225 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7226 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7227 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007228 default:
Andy Hungce685402018-10-05 17:23:27 -07007229 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7230 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007231 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007232
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007233 if (activeTrack->isFastTrack()) {
7234 ALOG_ASSERT(!mFastTrackAvail);
7235 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007236 // if the active fast track is silenced either:
7237 // 1) silence the whole capture from fast capture buffer if this is
7238 // the only active track
7239 // 2) invalidate this track: this will cause the client to reconnect and possibly
7240 // be invalidated again until unsilenced
7241 if (activeTrack->isSilenced()) {
7242 if (size > 1) {
7243 activeTrack->invalidate();
7244 ALOG_ASSERT(fastTrackToRemove == 0);
7245 fastTrackToRemove = activeTrack;
7246 removeTrack_l(activeTrack);
7247 mActiveTracks.remove(activeTrack);
7248 size--;
7249 continue;
7250 } else {
7251 silenceFastCapture = true;
7252 }
7253 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007254 fastTrack = activeTrack;
7255 }
Eric Laurent33403f02020-05-29 18:35:06 -07007256
7257 activeTracks.add(activeTrack);
7258 i++;
7259
Glenn Kasten9e982352013-08-14 14:39:50 -07007260 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007261
Andy Hungdae27702016-10-31 14:01:16 -07007262 mActiveTracks.updatePowerState(this);
7263
Kevin Rocard069c2712018-03-29 19:09:14 -07007264 updateMetadata_l();
7265
Eric Laurent5c25d562016-07-13 17:17:45 -07007266 if (allStopped) {
7267 standbyIfNotAlreadyInStandby();
7268 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007269 if (doBroadcast) {
7270 mStartStopCond.broadcast();
7271 }
7272
7273 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007274 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007275 if (sleepUs == 0) {
7276 sleepUs = kRecordThreadSleepUs;
7277 }
7278 continue;
7279 }
7280 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007281
Eric Laurent81784c32012-11-19 14:55:58 -08007282 lockEffectChains_l(effectChains);
7283 }
7284
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007285 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007286
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007287 size_t size = effectChains.size();
7288 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007289 // thread mutex is not locked, but effect chain is locked
7290 effectChains[i]->process_l();
7291 }
7292
Glenn Kasten735f45f2014-08-18 15:51:59 -07007293 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007294 if (mFastCapture != 0) {
7295 FastCaptureStateQueue *sq = mFastCapture->sq();
7296 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007297 bool didModify = false;
7298 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007299 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7300 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7301 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7302 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7303 if (old == -1) {
7304 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7305 }
7306 }
7307 state->mCommand = FastCaptureState::READ_WRITE;
7308#if 0 // FIXME
7309 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007310 FastThreadDumpState::kSamplingNforLowRamDevice :
7311 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007312#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007313 didModify = true;
7314 }
7315 audio_track_cblk_t *cblkOld = state->mCblk;
7316 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7317 if (cblkNew != cblkOld) {
7318 state->mCblk = cblkNew;
7319 // block until acked if removing a fast track
7320 if (cblkOld != NULL) {
7321 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7322 }
7323 didModify = true;
7324 }
jiabin01c8f562018-07-19 17:47:28 -07007325 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7326 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7327 if (state->mFastPatchRecordBufferProvider != abp) {
7328 state->mFastPatchRecordBufferProvider = abp;
7329 state->mFastPatchRecordFormat = fastTrack == 0 ?
7330 AUDIO_FORMAT_INVALID : fastTrack->format();
7331 didModify = true;
7332 }
Eric Laurent33403f02020-05-29 18:35:06 -07007333 if (state->mSilenceCapture != silenceFastCapture) {
7334 state->mSilenceCapture = silenceFastCapture;
7335 didModify = true;
7336 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007337 sq->end(didModify);
7338 if (didModify) {
7339 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007340#if 0
7341 if (kUseFastCapture == FastCapture_Dynamic) {
7342 mNormalSource = mPipeSource;
7343 }
7344#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007345 }
7346 }
7347
Glenn Kasten735f45f2014-08-18 15:51:59 -07007348 // now run the fast track destructor with thread mutex unlocked
7349 fastTrackToRemove.clear();
7350
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007351 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7352 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7353 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7354 // If destination is non-contiguous, first read past the nominal end of buffer, then
7355 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007356
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007357 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007358 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007359 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007360
7361 // If an NBAIO source is present, use it to read the normal capture's data
7362 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007363 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007364
7365 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7366 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7367 // we immediately retry the read() to get data and prevent another overflow.
7368 for (int retries = 0; retries <= 2; ++retries) {
7369 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7370 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7371 framesToRead);
7372 if (framesRead != OVERRUN) break;
7373 }
7374
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007375 const ssize_t availableToRead = mPipeSource->availableToRead();
7376 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007377 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007378 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7379 "more frames to read than fifo size, %zd > %zu",
7380 availableToRead, mPipeFramesP2);
7381 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7382 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7383 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7384 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007385 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7386 }
7387 if (framesRead < 0) {
7388 status_t status = (status_t) framesRead;
7389 switch (status) {
7390 case OVERRUN:
7391 ALOGW("overrun on read from pipe");
7392 framesRead = 0;
7393 break;
7394 case NEGOTIATE:
7395 ALOGE("re-negotiation is needed");
7396 framesRead = -1; // Will cause an attempt to recover.
7397 break;
7398 default:
7399 ALOGE("unknown error %d on read from pipe", status);
7400 break;
7401 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007402 }
7403 // otherwise use the HAL / AudioStreamIn directly
7404 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007405 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007406 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007407 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007408 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007409 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007410 if (result < 0) {
7411 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007412 } else {
7413 framesRead = bytesRead / mFrameSize;
7414 }
7415 }
7416
Andy Hung446f4df2019-02-21 12:26:41 -08007417 const int64_t lastIoEndNs = systemTime(); // end IO timing
7418
Andy Hung3f0c9022016-01-15 17:49:46 -08007419 // Update server timestamp with server stats
7420 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007421 if (framesRead >= 0) {
7422 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7423 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7424 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007425
7426 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007427 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007428 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007429 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007430 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7431 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7432 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007433 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007434 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7435
7436 mTimestampVerifier.add(position, time, mSampleRate);
7437
7438 // Correct timestamps
7439 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007440 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007441 id(), (long long)time, (long long)position);
7442 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7443 position = correctedTimestamp.mFrames;
7444 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007445 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007446 id(), (long long)time, (long long)position);
7447 }
7448
Andy Hung3f0c9022016-01-15 17:49:46 -08007449 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7450 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7451 // Note: In general record buffers should tend to be empty in
7452 // a properly running pipeline.
7453 //
7454 // Also, it is not advantageous to call get_presentation_position during the read
7455 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007456 } else {
7457 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007458 }
7459 }
Andy Hunge6c37112019-02-26 17:38:10 -08007460
7461 // From the timestamp, input read latency is negative output write latency.
7462 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7463 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7464 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7465 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7466 mLatencyMs.add(latencyMs);
7467 }
7468
Andy Hung3f0c9022016-01-15 17:49:46 -08007469 // Use this to track timestamp information
7470 // ALOGD("%s", mTimestamp.toString().c_str());
7471
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007472 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007473 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007474 // Force input into standby so that it tries to recover at next read attempt
7475 inputStandBy();
7476 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007477 }
7478 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007479 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007480 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007481 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007482 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007483
Andy Hung8946a282018-04-19 20:04:56 -07007484#ifdef TEE_SINK
7485 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7486#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007487 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007488 {
7489 size_t part1 = mRsmpInFramesP2 - rear;
7490 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007491 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007492 (framesRead - part1) * mFrameSize);
7493 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007494 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007495 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007496
7497 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007498
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007499 // loop over each active track
7500 for (size_t i = 0; i < size; i++) {
7501 activeTrack = activeTracks[i];
7502
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007503 // skip fast tracks, as those are handled directly by FastCapture
7504 if (activeTrack->isFastTrack()) {
7505 continue;
7506 }
7507
Andy Hung73c02e42015-03-29 01:13:58 -07007508 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007509 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7510
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007511 enum {
7512 OVERRUN_UNKNOWN,
7513 OVERRUN_TRUE,
7514 OVERRUN_FALSE
7515 } overrun = OVERRUN_UNKNOWN;
7516
7517 // loop over getNextBuffer to handle circular sink
7518 for (;;) {
7519
7520 activeTrack->mSink.frameCount = ~0;
7521 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7522 size_t framesOut = activeTrack->mSink.frameCount;
7523 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7524
Andy Hung73c02e42015-03-29 01:13:58 -07007525 // check available frames and handle overrun conditions
7526 // if the record track isn't draining fast enough.
7527 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007528 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007529 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7530 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007531 overrun = OVERRUN_TRUE;
7532 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007533 if (framesOut == 0 || framesIn == 0) {
7534 break;
7535 }
7536
Andy Hung6770c6f2015-04-07 13:43:36 -07007537 // Don't allow framesOut to be larger than what is possible with resampling
7538 // from framesIn.
7539 // This isn't strictly necessary but helps limit buffer resizing in
7540 // RecordBufferConverter. TODO: remove when no longer needed.
7541 framesOut = min(framesOut,
7542 destinationFramesPossible(
7543 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007544
7545 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007546 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007547 // straight from RecordThread buffer to RecordTrack buffer.
7548 AudioBufferProvider::Buffer buffer;
7549 buffer.frameCount = framesOut;
7550 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7551 if (status == OK && buffer.frameCount != 0) {
7552 ALOGV_IF(buffer.frameCount != framesOut,
7553 "%s() read less than expected (%zu vs %zu)",
7554 __func__, buffer.frameCount, framesOut);
7555 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007556 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007557 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7558 } else {
7559 framesOut = 0;
7560 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7561 __func__, status, buffer.frameCount);
7562 }
7563 } else {
7564 // process frames from the RecordThread buffer provider to the RecordTrack
7565 // buffer
7566 framesOut = activeTrack->mRecordBufferConverter->convert(
7567 activeTrack->mSink.raw,
7568 activeTrack->mResamplerBufferProvider,
7569 framesOut);
7570 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007571
7572 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7573 overrun = OVERRUN_FALSE;
7574 }
7575
7576 if (activeTrack->mFramesToDrop == 0) {
7577 if (framesOut > 0) {
7578 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007579 // Sanitize before releasing if the track has no access to the source data
7580 // An idle UID receives silence from non virtual devices until active
7581 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007582 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007583 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007584 activeTrack->releaseBuffer(&activeTrack->mSink);
7585 }
7586 } else {
7587 // FIXME could do a partial drop of framesOut
7588 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007589 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007590 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007591 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007592 }
7593 } else {
7594 activeTrack->mFramesToDrop += framesOut;
7595 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7596 activeTrack->mSyncStartEvent->isCancelled()) {
7597 ALOGW("Synced record %s, session %d, trigger session %d",
7598 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7599 activeTrack->sessionId(),
7600 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007601 activeTrack->mSyncStartEvent->triggerSession() :
7602 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007603 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007604 }
7605 }
7606 }
7607
7608 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007609 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007610 }
7611 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007612
7613 switch (overrun) {
7614 case OVERRUN_TRUE:
7615 // client isn't retrieving buffers fast enough
7616 if (!activeTrack->setOverflow()) {
7617 nsecs_t now = systemTime();
7618 // FIXME should lastWarning per track?
7619 if ((now - lastWarning) > kWarningThrottleNs) {
7620 ALOGW("RecordThread: buffer overflow");
7621 lastWarning = now;
7622 }
7623 }
7624 break;
7625 case OVERRUN_FALSE:
7626 activeTrack->clearOverflow();
7627 break;
7628 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007629 break;
7630 }
7631
Andy Hung3f0c9022016-01-15 17:49:46 -08007632 // update frame information and push timestamp out
7633 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007634 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007635 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7636 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007637 }
7638
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007639unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007640 // enable changes in effect chain
7641 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007642 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007643 if (audio_has_proportional_frames(mFormat)
7644 && loopCount == lastLoopCountRead + 1) {
7645 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7646 const double jitterMs =
7647 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7648 {framesRead, readPeriodNs},
7649 {0, 0} /* lastTimestamp */, mSampleRate);
7650 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7651
7652 Mutex::Autolock _l(mLock);
7653 mIoJitterMs.add(jitterMs);
7654 mProcessTimeMs.add(processMs);
7655 }
7656 // update timing info.
7657 mLastIoBeginNs = lastIoBeginNs;
7658 mLastIoEndNs = lastIoEndNs;
7659 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007660 }
7661
Glenn Kasten93e471f2013-08-19 08:40:07 -07007662 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007663
7664 {
7665 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007666 for (size_t i = 0; i < mTracks.size(); i++) {
7667 sp<RecordTrack> track = mTracks[i];
7668 track->invalidate();
7669 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007670 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007671 mStartStopCond.broadcast();
7672 }
7673
7674 releaseWakeLock();
7675
7676 ALOGV("RecordThread %p exiting", this);
7677 return false;
7678}
7679
Glenn Kasten93e471f2013-08-19 08:40:07 -07007680void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007681{
7682 if (!mStandby) {
7683 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007684 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007685 mStandby = true;
7686 }
7687}
7688
7689void AudioFlinger::RecordThread::inputStandBy()
7690{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007691 // Idle the fast capture if it's currently running
7692 if (mFastCapture != 0) {
7693 FastCaptureStateQueue *sq = mFastCapture->sq();
7694 FastCaptureState *state = sq->begin();
7695 if (!(state->mCommand & FastCaptureState::IDLE)) {
7696 state->mCommand = FastCaptureState::COLD_IDLE;
7697 state->mColdFutexAddr = &mFastCaptureFutex;
7698 state->mColdGen++;
7699 mFastCaptureFutex = 0;
7700 sq->end();
7701 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7702 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7703#if 0
7704 if (kUseFastCapture == FastCapture_Dynamic) {
7705 // FIXME
7706 }
7707#endif
7708#ifdef AUDIO_WATCHDOG
7709 // FIXME
7710#endif
7711 } else {
7712 sq->end(false /*didModify*/);
7713 }
7714 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007715 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007716 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007717
7718 // If going into standby, flush the pipe source.
7719 if (mPipeSource.get() != nullptr) {
7720 const ssize_t flushed = mPipeSource->flush();
7721 if (flushed > 0) {
7722 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7723 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7724 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7725 }
7726 }
Eric Laurent81784c32012-11-19 14:55:58 -08007727}
7728
Glenn Kasten05997e22014-03-13 15:08:33 -07007729// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007730sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007731 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007732 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007733 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007734 audio_format_t format,
7735 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007736 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007737 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007738 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007739 pid_t creatorPid,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007740 const Identity& identity,
Eric Laurent05067782016-06-01 18:27:28 -07007741 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007742 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007743 status_t *status,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007744 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007745{
Glenn Kasten74935e42013-12-19 08:56:45 -08007746 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007747 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007748 sp<RecordTrack> track;
7749 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007750 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007751 audio_input_flags_t requestedFlags = *flags;
7752 uint32_t sampleRate;
7753
7754 lStatus = initCheck();
7755 if (lStatus != NO_ERROR) {
7756 ALOGE("createRecordTrack_l() audio driver not initialized");
7757 goto Exit;
7758 }
7759
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007760 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7761 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7762 lStatus = BAD_VALUE;
7763 goto Exit;
7764 }
7765
Eric Laurentf14db3c2017-12-08 14:20:36 -08007766 if (*pSampleRate == 0) {
7767 *pSampleRate = mSampleRate;
7768 }
7769 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007770
7771 // special case for FAST flag considered OK if fast capture is present
7772 if (hasFastCapture()) {
7773 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7774 }
7775
Eric Laurentf14db3c2017-12-08 14:20:36 -08007776 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007777 if ((*flags & inputFlags) != *flags) {
7778 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7779 " input flags (%08x)",
7780 *flags, inputFlags);
7781 *flags = (audio_input_flags_t)(*flags & inputFlags);
7782 }
Eric Laurent81784c32012-11-19 14:55:58 -08007783
Glenn Kasten90e58b12013-07-31 16:16:02 -07007784 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007785 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007786 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007787 // we formerly checked for a callback handler (non-0 tid),
7788 // but that is no longer required for TRANSFER_OBTAIN mode
7789 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007790 // Frame count is not specified (0), or is less than or equal the pipe depth.
7791 // It is OK to provide a higher capacity than requested.
7792 // We will force it to mPipeFramesP2 below.
7793 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007794 // PCM data
7795 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007796 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007797 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007798 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007799 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007800 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007801 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007802 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007803 hasFastCapture() &&
7804 // there are sufficient fast track slots available
7805 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007806 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007807 // check compatibility with audio effects.
7808 Mutex::Autolock _l(mLock);
7809 // Do not accept FAST flag if the session has software effects
7810 sp<EffectChain> chain = getEffectChain_l(sessionId);
7811 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007812 audio_input_flags_t old = *flags;
7813 chain->checkInputFlagCompatibility(flags);
7814 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007815 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7816 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007817 }
7818 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007819 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007820 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7821 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007822 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007823 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7824 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007825 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007826 this, frameCount, mFrameCount, mPipeFramesP2,
7827 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007828 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007829 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007830 }
7831 }
7832
Eric Laurentf14db3c2017-12-08 14:20:36 -08007833 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7834 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7835 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7836 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7837 lStatus = BAD_TYPE;
7838 goto Exit;
7839 }
7840
Glenn Kasten74105912014-07-03 12:28:53 -07007841 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007842 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007843 // fast track: frame count is exactly the pipe depth
7844 frameCount = mPipeFramesP2;
7845 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007846 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007847 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007848 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7849 // or 20 ms if there is a fast capture
7850 // TODO This could be a roundupRatio inline, and const
7851 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7852 * sampleRate + mSampleRate - 1) / mSampleRate;
7853 // minimum number of notification periods is at least kMinNotifications,
7854 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7855 static const size_t kMinNotifications = 3;
7856 static const uint32_t kMinMs = 30;
7857 // TODO This could be a roundupRatio inline
7858 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7859 // TODO This could be a roundupRatio inline
7860 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7861 maxNotificationFrames;
7862 const size_t minFrameCount = maxNotificationFrames *
7863 max(kMinNotifications, minNotificationsByMs);
7864 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007865 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7866 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007867 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007868 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007869 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007870 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007871
7872 { // scope for mLock
7873 Mutex::Autolock _l(mLock);
7874
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007875 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007876 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007877 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
7878 identity, *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007879
Glenn Kasten03003332013-08-06 15:40:54 -07007880 lStatus = track->initCheck();
7881 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007882 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007883 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007884 goto Exit;
7885 }
7886 mTracks.add(track);
7887
Eric Laurent05067782016-06-01 18:27:28 -07007888 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007889 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7890 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7891 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007892 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007893 }
Eric Laurent81784c32012-11-19 14:55:58 -08007894 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007895
Eric Laurent81784c32012-11-19 14:55:58 -08007896 lStatus = NO_ERROR;
7897
7898Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007899 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007900 return track;
7901}
7902
7903status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7904 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007905 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007906{
7907 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7908 sp<ThreadBase> strongMe = this;
7909 status_t status = NO_ERROR;
7910
7911 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007912 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007913 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007914 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007915 triggerSession,
7916 recordTrack->sessionId(),
7917 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007918 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007919 // Sync event can be cancelled by the trigger session if the track is not in a
7920 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007921 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007922 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007923 } else {
7924 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007925 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007926 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007927 }
7928 }
7929
7930 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007931 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007932 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007933 if (recordTrack->isInvalid()) {
7934 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07007935 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
7936 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07007937 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007938 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7939 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007940 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7941 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007942 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007943 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007944 } else {
7945 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007946 }
7947 return status;
7948 }
7949
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007950 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7951 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7952 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007953 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007954 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007955 status_t status = NO_ERROR;
7956 if (recordTrack->isExternalTrack()) {
7957 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007958 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007959 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007960 if (recordTrack->isInvalid()) {
7961 recordTrack->clearSyncStartEvent();
7962 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7963 recordTrack->mState = TrackBase::STARTING_2;
7964 // STARTING_2 forces destroy to call stopInput.
7965 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07007966 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
7967 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07007968 }
7969 if (recordTrack->mState != TrackBase::STARTING_1) {
7970 ALOGW("%s(%d): unsynchronized mState:%d change",
7971 __func__, recordTrack->id(), recordTrack->mState);
7972 // Someone else has changed state, let them take over,
7973 // leave mState in the new state.
7974 recordTrack->clearSyncStartEvent();
7975 return INVALID_OPERATION;
7976 }
7977 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007978 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007979 ALOGW("%s(%d): startInput failed, status %d",
7980 __func__, recordTrack->id(), status);
7981 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7982 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007983 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007984 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007985 return status;
7986 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07007987 sendIoConfigEvent_l(
7988 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08007989 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07007990
7991 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
7992
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007993 // Catch up with current buffer indices if thread is already running.
7994 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7995 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7996 // see previously buffered data before it called start(), but with greater risk of overrun.
7997
Andy Hung73c02e42015-03-29 01:13:58 -07007998 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007999 if (!recordTrack->isDirect()) {
8000 // clear any converter state as new data will be discontinuous
8001 recordTrack->mRecordBufferConverter->reset();
8002 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008003 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008004 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008005 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008006 return status;
8007 }
Eric Laurent81784c32012-11-19 14:55:58 -08008008}
8009
Eric Laurent81784c32012-11-19 14:55:58 -08008010void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8011{
8012 sp<SyncEvent> strongEvent = event.promote();
8013
8014 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008015 sp<RefBase> ptr = strongEvent->cookie().promote();
8016 if (ptr != 0) {
8017 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8018 recordTrack->handleSyncStartEvent(strongEvent);
8019 }
Eric Laurent81784c32012-11-19 14:55:58 -08008020 }
8021}
8022
Glenn Kastena8356f62013-07-25 14:37:52 -07008023bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008024 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008025 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008026 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008027 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008028 return false;
8029 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008030 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008031 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008032
Andy Hungabfab202019-03-07 19:45:54 -08008033 // NOTE: Waiting here is important to keep stop synchronous.
8034 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008035 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8036 mWaitWorkCV.broadcast(); // signal thread to stop
8037 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008038 }
Andy Hungce685402018-10-05 17:23:27 -07008039
8040 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008041 ALOGV("Record stopped OK");
8042 return true;
8043 }
Andy Hungce685402018-10-05 17:23:27 -07008044
8045 // don't handle anything - we've been invalidated or restarted and in a different state
8046 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8047 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008048 return false;
8049}
8050
Glenn Kasten0f11b512014-01-31 16:18:54 -08008051bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008052{
8053 return false;
8054}
8055
Glenn Kasten0f11b512014-01-31 16:18:54 -08008056status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008057{
8058#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8059 if (!isValidSyncEvent(event)) {
8060 return BAD_VALUE;
8061 }
8062
Glenn Kastend848eb42016-03-08 13:42:11 -08008063 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008064 status_t ret = NAME_NOT_FOUND;
8065
8066 Mutex::Autolock _l(mLock);
8067
8068 for (size_t i = 0; i < mTracks.size(); i++) {
8069 sp<RecordTrack> track = mTracks[i];
8070 if (eventSession == track->sessionId()) {
8071 (void) track->setSyncEvent(event);
8072 ret = NO_ERROR;
8073 }
8074 }
8075 return ret;
8076#else
8077 return BAD_VALUE;
8078#endif
8079}
8080
jiabin653cc0a2018-01-17 17:54:10 -08008081status_t AudioFlinger::RecordThread::getActiveMicrophones(
8082 std::vector<media::MicrophoneInfo>* activeMicrophones)
8083{
8084 ALOGV("RecordThread::getActiveMicrophones");
8085 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07008086 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8087 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008088}
8089
Paul McLean12340082019-03-19 09:35:05 -06008090status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8091 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008092{
Paul McLean12340082019-03-19 09:35:05 -06008093 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008094 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008095 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008096}
8097
Paul McLean12340082019-03-19 09:35:05 -06008098status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008099{
Paul McLean12340082019-03-19 09:35:05 -06008100 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008101 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008102 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008103}
8104
Kevin Rocard069c2712018-03-29 19:09:14 -07008105void AudioFlinger::RecordThread::updateMetadata_l()
8106{
8107 if (mInput == nullptr || mInput->stream == nullptr ||
8108 !mActiveTracks.readAndClearHasChanged()) {
8109 return;
8110 }
8111 StreamInHalInterface::SinkMetadata metadata;
8112 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008113 // Do not forward PatchRecord metadata to audio HAL
8114 if (track->isPatchTrack()) {
8115 continue;
8116 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008117 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008118 record_track_metadata_v7_t trackMetadata;
8119 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008120 .source = track->attributes().source,
8121 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008122 };
8123 trackMetadata.channel_mask = track->channelMask(),
8124 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8125
8126 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008127 }
8128 mInput->stream->updateSinkMetadata(metadata);
8129}
8130
Eric Laurent81784c32012-11-19 14:55:58 -08008131// destroyTrack_l() must be called with ThreadBase::mLock held
8132void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8133{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008134 track->terminate();
8135 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08008136 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008137 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008138 removeTrack_l(track);
8139 }
8140}
8141
8142void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8143{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008144 String8 result;
8145 track->appendDump(result, false /* active */);
8146 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8147
Eric Laurent81784c32012-11-19 14:55:58 -08008148 mTracks.remove(track);
8149 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008150 if (track->isFastTrack()) {
8151 ALOG_ASSERT(!mFastTrackAvail);
8152 mFastTrackAvail = true;
8153 }
Eric Laurent81784c32012-11-19 14:55:58 -08008154}
8155
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008156void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008157{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008158 AudioStreamIn *input = mInput;
8159 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8160 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008161 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008162 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008163 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008164 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008165 }
Andy Hungbfa64962017-06-12 14:43:19 -07008166
8167 if (input != nullptr) {
8168 dprintf(fd, " Hal stream dump:\n");
8169 (void)input->stream->dump(fd);
8170 }
8171
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008172 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008173 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008174
Glenn Kasten2f90c512015-12-02 11:40:09 -08008175 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8176 // while we are dumping it. It may be inconsistent, but it won't mutate!
8177 // This is a large object so we place it on the heap.
8178 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008179 const std::unique_ptr<FastCaptureDumpState> copy =
8180 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008181 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008182}
8183
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008184void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008185{
Eric Laurent81784c32012-11-19 14:55:58 -08008186 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008187 size_t numtracks = mTracks.size();
8188 size_t numactive = mActiveTracks.size();
8189 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008190 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008191 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008192 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008193 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008194 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008195 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008196 for (size_t i = 0; i < numtracks ; ++i) {
8197 sp<RecordTrack> track = mTracks[i];
8198 if (track != 0) {
8199 bool active = mActiveTracks.indexOf(track) >= 0;
8200 if (active) {
8201 numactiveseen++;
8202 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008203 result.append(prefix);
8204 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008205 }
Eric Laurent81784c32012-11-19 14:55:58 -08008206 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008207 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008208 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008209 }
8210
Marco Nelissenb2208842014-02-07 14:00:50 -08008211 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008212 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008213 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008214 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008215 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008216 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008217 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008218 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008219 result.append(prefix);
8220 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008221 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008222 }
Eric Laurent81784c32012-11-19 14:55:58 -08008223
8224 }
8225 write(fd, result.string(), result.size());
8226}
8227
Eric Laurent5ada82e2019-08-29 17:53:54 -07008228void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008229{
8230 Mutex::Autolock _l(mLock);
8231 for (size_t i = 0; i < mTracks.size() ; i++) {
8232 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008233 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008234 track->setSilenced(silenced);
8235 }
8236 }
8237}
Andy Hung73c02e42015-03-29 01:13:58 -07008238
8239void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8240{
8241 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8242 RecordThread *recordThread = (RecordThread *) threadBase.get();
8243 mRsmpInFront = recordThread->mRsmpInRear;
8244 mRsmpInUnrel = 0;
8245}
8246
8247void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8248 size_t *framesAvailable, bool *hasOverrun)
8249{
8250 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8251 RecordThread *recordThread = (RecordThread *) threadBase.get();
8252 const int32_t rear = recordThread->mRsmpInRear;
8253 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008254 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008255
8256 size_t framesIn;
8257 bool overrun = false;
8258 if (filled < 0) {
8259 // should not happen, but treat like a massive overrun and re-sync
8260 framesIn = 0;
8261 mRsmpInFront = rear;
8262 overrun = true;
8263 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8264 framesIn = (size_t) filled;
8265 } else {
8266 // client is not keeping up with server, but give it latest data
8267 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008268 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8269 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008270 overrun = true;
8271 }
8272 if (framesAvailable != NULL) {
8273 *framesAvailable = framesIn;
8274 }
8275 if (hasOverrun != NULL) {
8276 *hasOverrun = overrun;
8277 }
8278}
8279
Eric Laurent81784c32012-11-19 14:55:58 -08008280// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008281status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008282 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008283{
Andy Hung73c02e42015-03-29 01:13:58 -07008284 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008285 if (threadBase == 0) {
8286 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008287 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008288 return NOT_ENOUGH_DATA;
8289 }
8290 RecordThread *recordThread = (RecordThread *) threadBase.get();
8291 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008292 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008293 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008294 // FIXME should not be P2 (don't want to increase latency)
8295 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008296 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008297 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008298 front &= recordThread->mRsmpInFramesP2 - 1;
8299 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008300 if (part1 > (size_t) filled) {
8301 part1 = filled;
8302 }
8303 size_t ask = buffer->frameCount;
8304 ALOG_ASSERT(ask > 0);
8305 if (part1 > ask) {
8306 part1 = ask;
8307 }
8308 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008309 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008310 buffer->raw = NULL;
8311 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008312 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008313 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008314 }
8315
Andy Hung57446612015-04-19 23:56:46 -07008316 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008317 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008318 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008319 return NO_ERROR;
8320}
8321
8322// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008323void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8324 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008325{
Hongwei Wang95e37682019-04-12 11:13:36 -07008326 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008327 if (stepCount == 0) {
8328 return;
8329 }
Andy Hung73c02e42015-03-29 01:13:58 -07008330 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8331 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008332 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008333 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008334 buffer->frameCount = 0;
8335}
8336
Eric Laurentd8365c52017-07-16 15:27:05 -07008337void AudioFlinger::RecordThread::checkBtNrec()
8338{
8339 Mutex::Autolock _l(mLock);
8340 checkBtNrec_l();
8341}
8342
8343void AudioFlinger::RecordThread::checkBtNrec_l()
8344{
8345 // disable AEC and NS if the device is a BT SCO headset supporting those
8346 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008347 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008348 mAudioFlinger->btNrecIsOff();
8349 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8350 for (size_t i = 0; i < mEffectChains.size(); i++) {
8351 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8352 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8353 }
8354 }
8355}
8356
Andy Hung97a893e2015-03-29 01:03:07 -07008357
Eric Laurent10351942014-05-08 18:49:52 -07008358bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8359 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008360{
8361 bool reconfig = false;
8362
Eric Laurent10351942014-05-08 18:49:52 -07008363 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008364
Eric Laurent10351942014-05-08 18:49:52 -07008365 audio_format_t reqFormat = mFormat;
8366 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008367 // 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 -07008368 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8369
8370 AudioParameter param = AudioParameter(keyValuePair);
8371 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008372
8373 // scope for AutoPark extends to end of method
8374 AutoPark<FastCapture> park(mFastCapture);
8375
Eric Laurent10351942014-05-08 18:49:52 -07008376 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8377 // channel count change can be requested. Do we mandate the first client defines the
8378 // HAL sampling rate and channel count or do we allow changes on the fly?
8379 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8380 samplingRate = value;
8381 reconfig = true;
8382 }
8383 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008384 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008385 status = BAD_VALUE;
8386 } else {
8387 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008388 reconfig = true;
8389 }
Eric Laurent10351942014-05-08 18:49:52 -07008390 }
8391 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8392 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008393 if (!audio_is_input_channel(mask) ||
8394 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008395 status = BAD_VALUE;
8396 } else {
8397 channelMask = mask;
8398 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008399 }
Eric Laurent10351942014-05-08 18:49:52 -07008400 }
8401 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8402 // do not accept frame count changes if tracks are open as the track buffer
8403 // size depends on frame count and correct behavior would not be guaranteed
8404 // if frame count is changed after track creation
8405 if (mActiveTracks.size() > 0) {
8406 status = INVALID_OPERATION;
8407 } else {
8408 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008409 }
Eric Laurent10351942014-05-08 18:49:52 -07008410 }
8411 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008412 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008413 }
8414 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8415 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008416 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008417 }
Glenn Kastene198c362013-08-13 09:13:36 -07008418
Eric Laurent10351942014-05-08 18:49:52 -07008419 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008420 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008421 if (status == INVALID_OPERATION) {
8422 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008423 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008424 }
8425 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008426 if (status == BAD_VALUE) {
8427 uint32_t sRate;
8428 audio_channel_mask_t channelMask;
8429 audio_format_t format;
8430 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8431 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8432 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8433 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8434 status = NO_ERROR;
8435 }
Eric Laurent81784c32012-11-19 14:55:58 -08008436 }
Eric Laurent10351942014-05-08 18:49:52 -07008437 if (status == NO_ERROR) {
8438 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008439 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008440 }
8441 }
Eric Laurent81784c32012-11-19 14:55:58 -08008442 }
Eric Laurent10351942014-05-08 18:49:52 -07008443
Eric Laurent81784c32012-11-19 14:55:58 -08008444 return reconfig;
8445}
8446
8447String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8448{
Eric Laurent81784c32012-11-19 14:55:58 -08008449 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008450 if (initCheck() == NO_ERROR) {
8451 String8 out_s8;
8452 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8453 return out_s8;
8454 }
Eric Laurent81784c32012-11-19 14:55:58 -08008455 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008456 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008457}
8458
Eric Laurent09f1ed22019-04-24 17:45:17 -07008459void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8460 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008461 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8462
8463 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008464
8465 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008466 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008467 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008468 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008469 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008470 desc->mChannelMask = mChannelMask;
8471 desc->mSamplingRate = mSampleRate;
8472 desc->mFormat = mFormat;
8473 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008474 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008475 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008476 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008477 case AUDIO_CLIENT_STARTED:
8478 desc->mPatch = mPatch;
8479 desc->mPortId = portId;
8480 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008481 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008482 default:
8483 break;
8484 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008485 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008486}
8487
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008488void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008489{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008490 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8491 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008492 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008493 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8494 if (audio_is_linear_pcm(mFormat)) {
8495 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8496 mChannelCount, FCC_8);
8497 } else {
8498 // Can have more that FCC_8 channels in encoded streams.
8499 ALOGI("HAL format %#x is not linear pcm", mFormat);
8500 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008501 result = mInput->stream->getFrameSize(&mFrameSize);
8502 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008503 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8504 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008505 result = mInput->stream->getBufferSize(&mBufferSize);
8506 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008507 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008508 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8509 "mBufferSize=%zu, mFrameCount=%zu",
8510 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008511 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008512 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
Glenn Kasten85948432013-08-19 12:09:05 -07008513 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008514 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008515 // A larger value should allow more old data to be read after a track calls start(),
8516 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008517 //
8518 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008519 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008520 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008521 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008522 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008523
8524 // TODO optimize audio capture buffer sizes ...
8525 // Here we calculate the size of the sliding buffer used as a source
8526 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8527 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8528 // be better to have it derived from the pipe depth in the long term.
8529 // The current value is higher than necessary. However it should not add to latency.
8530
Glenn Kasten85948432013-08-19 12:09:05 -07008531 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008532 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8533 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008534 // if posix_memalign fails, will segv here.
8535 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008536
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008537 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8538 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008539
8540 audio_input_flags_t flags = mInput->flags;
8541 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8542 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8543 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8544 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8545 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8546 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8547 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8548 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8549 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008550}
8551
Glenn Kasten5f972c02014-01-13 09:59:31 -08008552uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008553{
8554 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008555 uint32_t result;
8556 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8557 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008558 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008559 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008560}
8561
Glenn Kastend848eb42016-03-08 13:42:11 -08008562KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008563{
Glenn Kastend848eb42016-03-08 13:42:11 -08008564 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008565 Mutex::Autolock _l(mLock);
8566 for (size_t j = 0; j < mTracks.size(); ++j) {
8567 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008568 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008569 if (ids.indexOfKey(sessionId) < 0) {
8570 ids.add(sessionId, true);
8571 }
8572 }
8573 return ids;
8574}
8575
8576AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8577{
8578 Mutex::Autolock _l(mLock);
8579 AudioStreamIn *input = mInput;
8580 mInput = NULL;
8581 return input;
8582}
8583
8584// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008585sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008586{
8587 if (mInput == NULL) {
8588 return NULL;
8589 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008590 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008591}
8592
8593status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8594{
Eric Laurent81784c32012-11-19 14:55:58 -08008595 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008596 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008597 chain->setInBuffer(NULL);
8598 chain->setOutBuffer(NULL);
8599
8600 checkSuspendOnAddEffectChain_l(chain);
8601
Eric Laurent1b928682014-10-02 19:41:47 -07008602 // make sure enabled pre processing effects state is communicated to the HAL as we
8603 // just moved them to a new input stream.
8604 chain->syncHalEffectsState();
8605
Eric Laurent81784c32012-11-19 14:55:58 -08008606 mEffectChains.add(chain);
8607
8608 return NO_ERROR;
8609}
8610
8611size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8612{
8613 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008614
8615 for (size_t i = 0; i < mEffectChains.size(); i++) {
8616 if (chain == mEffectChains[i]) {
8617 mEffectChains.removeAt(i);
8618 break;
8619 }
Eric Laurent81784c32012-11-19 14:55:58 -08008620 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008621 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008622}
8623
Eric Laurent1c333e22014-05-20 10:48:17 -07008624status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8625 audio_patch_handle_t *handle)
8626{
8627 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008628
8629 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008630 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008631 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008632 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008633 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008634 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008635 }
8636
Eric Laurentd8365c52017-07-16 15:27:05 -07008637 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008638
8639 // store new source and send to effects
8640 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8641 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008642 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008643 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008644 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008645 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008646
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008647 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008648 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8649 status = hwDevice->createAudioPatch(patch->num_sources,
8650 patch->sources,
8651 patch->num_sinks,
8652 patch->sinks,
8653 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008654 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008655 char *address;
8656 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8657 address = audio_device_address_to_parameter(
8658 patch->sources[0].ext.device.type,
8659 patch->sources[0].ext.device.address);
8660 } else {
8661 address = (char *)calloc(1, 1);
8662 }
8663 AudioParameter param = AudioParameter(String8(address));
8664 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008665 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008666 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008667 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008668 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008669 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008670 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008671 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008672
jiabinc52b1ff2019-10-31 17:20:42 -07008673 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008674 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008675 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008676 }
Eric Laurent296fb132015-05-01 11:38:42 -07008677
Andy Hungc2b11cb2020-04-22 09:04:01 -07008678 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008679 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008680 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008681 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008682 // also dispatch to active AudioRecords
8683 for (const auto &track : mActiveTracks) {
8684 track->logEndInterval();
8685 track->logBeginInterval(pathSourcesAsString);
8686 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008687 return status;
8688}
8689
8690status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8691{
8692 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008693
jiabinc52b1ff2019-10-31 17:20:42 -07008694 mPatch = audio_patch{};
8695 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008696
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008697 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008698 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8699 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008700 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008701 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008702 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008703 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008704 }
8705 return status;
8706}
8707
jiabinc52b1ff2019-10-31 17:20:42 -07008708void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8709{
wendy lin56aa82b2020-12-02 15:19:55 +08008710 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07008711 mOutDevices = outDevices;
8712 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8713 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008714 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008715 }
8716}
8717
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008718void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008719{
8720 Mutex::Autolock _l(mLock);
8721 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008722 if (record->getSource()) {
8723 mSource = record->getSource();
8724 }
Eric Laurent83b88082014-06-20 18:31:16 -07008725}
8726
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008727void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008728{
8729 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008730 if (mSource == record->getSource()) {
8731 mSource = mInput;
8732 }
Eric Laurent83b88082014-06-20 18:31:16 -07008733 destroyTrack_l(record);
8734}
8735
Mikhail Naganovdc769682018-05-04 15:34:08 -07008736void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008737{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008738 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008739 config->role = AUDIO_PORT_ROLE_SINK;
8740 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8741 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008742 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8743 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8744 config->flags.input = mInput->flags;
8745 }
Eric Laurent83b88082014-06-20 18:31:16 -07008746}
Eric Laurent1c333e22014-05-20 10:48:17 -07008747
Eric Laurent6acd1d42017-01-04 14:23:29 -08008748// ----------------------------------------------------------------------------
8749// Mmap
8750// ----------------------------------------------------------------------------
8751
8752AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8753 : mThread(thread)
8754{
Phil Burk9fabbf82017-08-03 12:02:00 -07008755 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008756}
8757
8758AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8759{
Phil Burk9fabbf82017-08-03 12:02:00 -07008760 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008761}
8762
8763status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8764 struct audio_mmap_buffer_info *info)
8765{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008766 return mThread->createMmapBuffer(minSizeFrames, info);
8767}
8768
8769status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8770{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008771 return mThread->getMmapPosition(position);
8772}
8773
jiabinb7d8c5a2020-08-26 17:24:52 -07008774status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
8775 int64_t *timeNanos) {
8776 return mThread->getExternalPosition(position, timeNanos);
8777}
8778
Eric Laurenta54f1282017-07-01 19:39:32 -07008779status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008780 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008781
8782{
jiabind1f1cb62020-03-24 11:57:57 -07008783 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008784}
8785
8786status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8787{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008788 return mThread->stop(handle);
8789}
8790
Eric Laurent18b57012017-02-13 16:23:52 -08008791status_t AudioFlinger::MmapThreadHandle::standby()
8792{
Eric Laurent18b57012017-02-13 16:23:52 -08008793 return mThread->standby();
8794}
8795
Eric Laurent6acd1d42017-01-04 14:23:29 -08008796
8797AudioFlinger::MmapThread::MmapThread(
8798 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07008799 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07008800 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008801 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008802 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008803 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008804 mActiveTracks(&this->mLocalLog),
8805 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8806 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008807{
Eric Laurent18b57012017-02-13 16:23:52 -08008808 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008809 readHalParameters_l();
8810}
8811
8812AudioFlinger::MmapThread::~MmapThread()
8813{
8814}
8815
8816void AudioFlinger::MmapThread::onFirstRef()
8817{
8818 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8819}
8820
8821void AudioFlinger::MmapThread::disconnect()
8822{
Eric Laurent331679c2018-04-16 17:03:16 -07008823 ActiveTracks<MmapTrack> activeTracks;
8824 {
8825 Mutex::Autolock _l(mLock);
8826 for (const sp<MmapTrack> &t : mActiveTracks) {
8827 activeTracks.add(t);
8828 }
8829 }
8830 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008831 stop(t->portId());
8832 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008833 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008834 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008835 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008836 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008837 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008838 }
8839}
8840
8841
8842void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8843 audio_stream_type_t streamType __unused,
8844 audio_session_t sessionId,
8845 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008846 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008847 audio_port_handle_t portId)
8848{
8849 mAttr = *attr;
8850 mSessionId = sessionId;
8851 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008852 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008853 mPortId = portId;
8854}
8855
8856status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8857 struct audio_mmap_buffer_info *info)
8858{
8859 if (mHalStream == 0) {
8860 return NO_INIT;
8861 }
Eric Laurent18b57012017-02-13 16:23:52 -08008862 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008863 return mHalStream->createMmapBuffer(minSizeFrames, info);
8864}
8865
8866status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8867{
8868 if (mHalStream == 0) {
8869 return NO_INIT;
8870 }
8871 return mHalStream->getMmapPosition(position);
8872}
8873
Eric Laurent331679c2018-04-16 17:03:16 -07008874status_t AudioFlinger::MmapThread::exitStandby()
8875{
8876 status_t ret = mHalStream->start();
8877 if (ret != NO_ERROR) {
8878 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8879 return ret;
8880 }
Andy Hungcf10d742020-04-28 15:38:24 -07008881 if (mStandby) {
8882 mThreadMetrics.logBeginInterval();
8883 mStandby = false;
8884 }
Eric Laurent331679c2018-04-16 17:03:16 -07008885 return NO_ERROR;
8886}
8887
Eric Laurenta54f1282017-07-01 19:39:32 -07008888status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008889 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008890 audio_port_handle_t *handle)
8891{
Eric Laurenta54f1282017-07-01 19:39:32 -07008892 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008893 client.identity.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008894 if (mHalStream == 0) {
8895 return NO_INIT;
8896 }
8897
8898 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008899
Eric Laurenta54f1282017-07-01 19:39:32 -07008900 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00008901 // For the first track, reuse portId and session allocated when the stream was opened.
8902 ret = exitStandby();
8903 if (ret == NO_ERROR) {
8904 acquireWakeLock();
8905 }
8906 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07008907 }
8908
8909 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8910
8911 audio_io_handle_t io = mId;
8912 if (isOutput()) {
8913 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8914 config.sample_rate = mSampleRate;
8915 config.channel_mask = mChannelMask;
8916 config.format = mFormat;
8917 audio_stream_type_t stream = streamType();
8918 audio_output_flags_t flags =
8919 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008920 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008921 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008922 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8923 mSessionId,
8924 &stream,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008925 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07008926 &config,
8927 flags,
8928 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008929 &portId,
8930 &secondaryOutputs);
8931 ALOGD_IF(!secondaryOutputs.empty(),
8932 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008933 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008934 audio_config_base_t config;
8935 config.sample_rate = mSampleRate;
8936 config.channel_mask = mChannelMask;
8937 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008938 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008939 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07008940 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07008941 mSessionId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008942 client.identity,
Eric Laurenta54f1282017-07-01 19:39:32 -07008943 &config,
8944 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8945 &deviceId,
8946 &portId);
8947 }
8948 // APM should not chose a different input or output stream for the same set of attributes
8949 // and audo configuration
8950 if (ret != NO_ERROR || io != mId) {
8951 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8952 __FUNCTION__, ret, io, mId);
8953 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008954 }
8955
8956 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008957 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008958 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008959 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008960 }
8961
Eric Laurent331679c2018-04-16 17:03:16 -07008962 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008963 // abort if start is rejected by audio policy manager
8964 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008965 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008966 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008967 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008968 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008969 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008970 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008971 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008972 }
Eric Laurent331679c2018-04-16 17:03:16 -07008973 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008974 } else {
8975 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008976 }
8977 return PERMISSION_DENIED;
8978 }
8979
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008980 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07008981 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008982 mChannelMask, mSessionId, isOutput(), client.identity,
8983 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008984
Eric Laurent4eb58f12018-12-07 16:41:02 -08008985 if (isOutput()) {
8986 // force volume update when a new track is added
8987 mHalVolFloat = -1.0f;
8988 } else if (!track->isSilenced_l()) {
8989 for (const sp<MmapTrack> &t : mActiveTracks) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008990 if (t->isSilenced_l() && t->uid() != client.identity.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08008991 t->invalidate();
8992 }
8993 }
8994
8995
Eric Laurent6acd1d42017-01-04 14:23:29 -08008996 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008997 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008998 if (chain != 0) {
8999 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
9000 chain->incTrackCnt();
9001 chain->incActiveTrackCnt();
9002 }
9003
Andy Hungc2b11cb2020-04-22 09:04:01 -07009004 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009005 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009006 broadcast_l();
9007
Eric Laurenta54f1282017-07-01 19:39:32 -07009008 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009009
9010 return NO_ERROR;
9011}
9012
9013status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9014{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009015 ALOGV("%s handle %d", __FUNCTION__, handle);
9016
9017 if (mHalStream == 0) {
9018 return NO_INIT;
9019 }
9020
Eric Laurenta54f1282017-07-01 19:39:32 -07009021 if (handle == mPortId) {
9022 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009023 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009024 return NO_ERROR;
9025 }
9026
Eric Laurent331679c2018-04-16 17:03:16 -07009027 Mutex::Autolock _l(mLock);
9028
Eric Laurent6acd1d42017-01-04 14:23:29 -08009029 sp<MmapTrack> track;
9030 for (const sp<MmapTrack> &t : mActiveTracks) {
9031 if (handle == t->portId()) {
9032 track = t;
9033 break;
9034 }
9035 }
9036 if (track == 0) {
9037 return BAD_VALUE;
9038 }
9039
9040 mActiveTracks.remove(track);
9041
Eric Laurent331679c2018-04-16 17:03:16 -07009042 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009043 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009044 AudioSystem::stopOutput(track->portId());
9045 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009046 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009047 AudioSystem::stopInput(track->portId());
9048 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009049 }
Eric Laurent331679c2018-04-16 17:03:16 -07009050 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009051
9052 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9053 if (chain != 0) {
9054 chain->decActiveTrackCnt();
9055 chain->decTrackCnt();
9056 }
9057
9058 broadcast_l();
9059
Eric Laurent6acd1d42017-01-04 14:23:29 -08009060 return NO_ERROR;
9061}
9062
Eric Laurent18b57012017-02-13 16:23:52 -08009063status_t AudioFlinger::MmapThread::standby()
9064{
9065 ALOGV("%s", __FUNCTION__);
9066
9067 if (mHalStream == 0) {
9068 return NO_INIT;
9069 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009070 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009071 return INVALID_OPERATION;
9072 }
9073 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009074 if (!mStandby) {
9075 mThreadMetrics.logEndInterval();
9076 mStandby = true;
9077 }
Eric Laurent18b57012017-02-13 16:23:52 -08009078 releaseWakeLock();
9079 return NO_ERROR;
9080}
9081
Eric Laurent6acd1d42017-01-04 14:23:29 -08009082
9083void AudioFlinger::MmapThread::readHalParameters_l()
9084{
9085 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9086 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9087 mFormat = mHALFormat;
9088 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9089 result = mHalStream->getFrameSize(&mFrameSize);
9090 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009091 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9092 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009093 result = mHalStream->getBufferSize(&mBufferSize);
9094 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9095 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009096
Andy Hungcf10d742020-04-28 15:38:24 -07009097 // TODO: make a readHalParameters call?
9098 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009099 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9100 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9101 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9102 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9103 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9104 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9105 /*
9106 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9107 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9108 (int32_t)mHapticChannelMask)
9109 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9110 (int32_t)mHapticChannelCount)
9111 */
9112 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9113 formatToString(mHALFormat).c_str())
9114 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9115 (int32_t)mFrameCount) // sic - added HAL
9116 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009117}
9118
9119bool AudioFlinger::MmapThread::threadLoop()
9120{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009121 checkSilentMode_l();
9122
9123 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9124
9125 while (!exitPending())
9126 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009127 Vector< sp<EffectChain> > effectChains;
9128
Andy Hung13850be2019-03-14 11:33:09 -07009129 { // under Thread lock
9130 Mutex::Autolock _l(mLock);
9131
Eric Laurent6acd1d42017-01-04 14:23:29 -08009132 if (mSignalPending) {
9133 // A signal was raised while we were unlocked
9134 mSignalPending = false;
9135 } else {
9136 if (mConfigEvents.isEmpty()) {
9137 // we're about to wait, flush the binder command buffer
9138 IPCThreadState::self()->flushCommands();
9139
9140 if (exitPending()) {
9141 break;
9142 }
9143
Eric Laurent6acd1d42017-01-04 14:23:29 -08009144 // wait until we have something to do...
9145 ALOGV("%s going to sleep", myName.string());
9146 mWaitWorkCV.wait(mLock);
9147 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009148
9149 checkSilentMode_l();
9150
9151 continue;
9152 }
9153 }
9154
9155 processConfigEvents_l();
9156
9157 processVolume_l();
9158
9159 checkInvalidTracks_l();
9160
9161 mActiveTracks.updatePowerState(this);
9162
Kevin Rocard069c2712018-03-29 19:09:14 -07009163 updateMetadata_l();
9164
Eric Laurent6acd1d42017-01-04 14:23:29 -08009165 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009166 } // release Thread lock
9167
Eric Laurent6acd1d42017-01-04 14:23:29 -08009168 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009169 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009170 }
Andy Hung13850be2019-03-14 11:33:09 -07009171
9172 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009173 unlockEffectChains(effectChains);
9174 // Effect chains will be actually deleted here if they were removed from
9175 // mEffectChains list during mixing or effects processing
9176 }
9177
9178 threadLoop_exit();
9179
9180 if (!mStandby) {
9181 threadLoop_standby();
9182 mStandby = true;
9183 }
9184
Eric Laurent6acd1d42017-01-04 14:23:29 -08009185 ALOGV("Thread %p type %d exiting", this, mType);
9186 return false;
9187}
9188
9189// checkForNewParameter_l() must be called with ThreadBase::mLock held
9190bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9191 status_t& status)
9192{
9193 AudioParameter param = AudioParameter(keyValuePair);
9194 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009195 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009196 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009197 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009198 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009199 if (sendToHal) {
9200 status = mHalStream->setParameters(keyValuePair);
9201 } else {
9202 status = NO_ERROR;
9203 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009204
9205 return false;
9206}
9207
9208String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9209{
9210 Mutex::Autolock _l(mLock);
9211 String8 out_s8;
9212 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9213 return out_s8;
9214 }
9215 return String8();
9216}
9217
Eric Laurent09f1ed22019-04-24 17:45:17 -07009218void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9219 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009220 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9221
9222 desc->mIoHandle = mId;
9223
9224 switch (event) {
9225 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009226 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009227 case AUDIO_INPUT_CONFIG_CHANGED:
9228 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009229 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009230 case AUDIO_OUTPUT_CONFIG_CHANGED:
9231 desc->mPatch = mPatch;
9232 desc->mChannelMask = mChannelMask;
9233 desc->mSamplingRate = mSampleRate;
9234 desc->mFormat = mFormat;
9235 desc->mFrameCount = mFrameCount;
9236 desc->mFrameCountHAL = mFrameCount;
9237 desc->mLatency = 0;
9238 break;
9239
9240 case AUDIO_INPUT_CLOSED:
9241 case AUDIO_OUTPUT_CLOSED:
9242 default:
9243 break;
9244 }
9245 mAudioFlinger->ioConfigChanged(event, desc, pid);
9246}
9247
9248status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9249 audio_patch_handle_t *handle)
9250{
9251 status_t status = NO_ERROR;
9252
9253 // store new device and send to effects
9254 audio_devices_t type = AUDIO_DEVICE_NONE;
9255 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009256 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9257 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9258 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009259 if (isOutput()) {
9260 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009261 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9262 && !mAudioHwDev->supportsAudioPatches(),
9263 "Enumerated device type(%#x) must not be used "
9264 "as it does not support audio patches",
9265 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009266 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009267 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9268 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009269 }
9270 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009271 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009272 } else {
9273 type = patch->sources[0].ext.device.type;
9274 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009275 numDevices = mPatch.num_sources;
9276 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009277 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009278 }
9279
9280 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009281 if (isOutput()) {
9282 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9283 } else {
9284 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9285 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009286 }
9287
jiabinc52b1ff2019-10-31 17:20:42 -07009288 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009289 // store new source and send to effects
9290 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9291 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9292 for (size_t i = 0; i < mEffectChains.size(); i++) {
9293 mEffectChains[i]->setAudioSource_l(mAudioSource);
9294 }
9295 }
9296 }
9297
9298 if (mAudioHwDev->supportsAudioPatches()) {
9299 status = mHalDevice->createAudioPatch(patch->num_sources,
9300 patch->sources,
9301 patch->num_sinks,
9302 patch->sinks,
9303 handle);
9304 } else {
9305 char *address;
9306 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9307 //FIXME: we only support address on first sink with HAL version < 3.0
9308 address = audio_device_address_to_parameter(
9309 patch->sinks[0].ext.device.type,
9310 patch->sinks[0].ext.device.address);
9311 } else {
9312 address = (char *)calloc(1, 1);
9313 }
9314 AudioParameter param = AudioParameter(String8(address));
9315 free(address);
9316 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9317 if (!isOutput()) {
9318 param.addInt(String8(AudioParameter::keyInputSource),
9319 (int)patch->sinks[0].ext.mix.usecase.source);
9320 }
9321 status = mHalStream->setParameters(param.toString());
9322 *handle = AUDIO_PATCH_HANDLE_NONE;
9323 }
9324
jiabinc52b1ff2019-10-31 17:20:42 -07009325 if (numDevices == 0 || mDeviceId != deviceId) {
9326 if (isOutput()) {
9327 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9328 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009329 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009330 } else {
9331 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9332 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9333 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009334 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009335 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009336 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009337 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009338 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009339 }
jiabinc52b1ff2019-10-31 17:20:42 -07009340 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009341 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009342 }
9343 return status;
9344}
9345
9346status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9347{
9348 status_t status = NO_ERROR;
9349
jiabinc52b1ff2019-10-31 17:20:42 -07009350 mPatch = audio_patch{};
9351 mOutDeviceTypeAddrs.clear();
9352 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009353
9354 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9355 supportsAudioPatches : false;
9356
9357 if (supportsAudioPatches) {
9358 status = mHalDevice->releaseAudioPatch(handle);
9359 } else {
9360 AudioParameter param;
9361 param.addInt(String8(AudioParameter::keyRouting), 0);
9362 status = mHalStream->setParameters(param.toString());
9363 }
9364 return status;
9365}
9366
Mikhail Naganovdc769682018-05-04 15:34:08 -07009367void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009368{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009369 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009370 if (isOutput()) {
9371 config->role = AUDIO_PORT_ROLE_SOURCE;
9372 config->ext.mix.hw_module = mAudioHwDev->handle();
9373 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9374 } else {
9375 config->role = AUDIO_PORT_ROLE_SINK;
9376 config->ext.mix.hw_module = mAudioHwDev->handle();
9377 config->ext.mix.usecase.source = mAudioSource;
9378 }
9379}
9380
9381status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9382{
9383 audio_session_t session = chain->sessionId();
9384
9385 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9386 // Attach all tracks with same session ID to this chain.
9387 // indicate all active tracks in the chain
9388 for (const sp<MmapTrack> &track : mActiveTracks) {
9389 if (session == track->sessionId()) {
9390 chain->incTrackCnt();
9391 chain->incActiveTrackCnt();
9392 }
9393 }
9394
9395 chain->setThread(this);
9396 chain->setInBuffer(nullptr);
9397 chain->setOutBuffer(nullptr);
9398 chain->syncHalEffectsState();
9399
9400 mEffectChains.add(chain);
9401 checkSuspendOnAddEffectChain_l(chain);
9402 return NO_ERROR;
9403}
9404
9405size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9406{
9407 audio_session_t session = chain->sessionId();
9408
9409 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9410
9411 for (size_t i = 0; i < mEffectChains.size(); i++) {
9412 if (chain == mEffectChains[i]) {
9413 mEffectChains.removeAt(i);
9414 // detach all active tracks from the chain
9415 // detach all tracks with same session ID from this chain
9416 for (const sp<MmapTrack> &track : mActiveTracks) {
9417 if (session == track->sessionId()) {
9418 chain->decActiveTrackCnt();
9419 chain->decTrackCnt();
9420 }
9421 }
9422 break;
9423 }
9424 }
9425 return mEffectChains.size();
9426}
9427
Eric Laurent6acd1d42017-01-04 14:23:29 -08009428void AudioFlinger::MmapThread::threadLoop_standby()
9429{
9430 mHalStream->standby();
9431}
9432
9433void AudioFlinger::MmapThread::threadLoop_exit()
9434{
Phil Burk7dce7282017-09-27 13:51:41 -07009435 // Do not call callback->onTearDown() because it is redundant for thread exit
9436 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009437}
9438
9439status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9440{
9441 return BAD_VALUE;
9442}
9443
9444bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9445{
9446 return false;
9447}
9448
9449status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9450 const effect_descriptor_t *desc, audio_session_t sessionId)
9451{
9452 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009453 if (audio_is_global_session(sessionId)) {
9454 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009455 desc->name, mThreadName);
9456 return BAD_VALUE;
9457 }
9458
9459 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9460 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9461 desc->name);
9462 return BAD_VALUE;
9463 }
9464 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009465 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9466 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009467 return BAD_VALUE;
9468 }
9469
9470 // Only allow effects without processing load or latency
9471 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9472 return BAD_VALUE;
9473 }
9474
jiabineb3bda02020-06-30 14:07:03 -07009475 if (EffectModule::isHapticGenerator(&desc->type)) {
9476 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9477 return BAD_VALUE;
9478 }
9479
Eric Laurent6acd1d42017-01-04 14:23:29 -08009480 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009481}
9482
9483void AudioFlinger::MmapThread::checkInvalidTracks_l()
9484{
9485 for (const sp<MmapTrack> &track : mActiveTracks) {
9486 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009487 sp<MmapStreamCallback> callback = mCallback.promote();
9488 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009489 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009490 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009491 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009492 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9493 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9494 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009495 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009496 }
9497 }
9498}
9499
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009500void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009501{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009502 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9503 mAttr.content_type, mAttr.usage, mAttr.source);
9504 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009505 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009506 dprintf(fd, " No active clients\n");
9507 }
9508}
9509
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009510void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009511{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009512 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009513 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009514 dprintf(fd, " %zu Tracks\n", numtracks);
9515 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009516 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009517 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009518 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009519 for (size_t i = 0; i < numtracks ; ++i) {
9520 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009521 result.append(prefix);
9522 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009523 }
9524 } else {
9525 dprintf(fd, "\n");
9526 }
9527 write(fd, result.string(), result.size());
9528}
9529
9530AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9531 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009532 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009533 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009534 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009535 mStreamVolume(1.0),
9536 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009537 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009538{
9539 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9540 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9541 mMasterVolume = audioFlinger->masterVolume_l();
9542 mMasterMute = audioFlinger->masterMute_l();
9543 if (mAudioHwDev) {
9544 if (mAudioHwDev->canSetMasterVolume()) {
9545 mMasterVolume = 1.0;
9546 }
9547
9548 if (mAudioHwDev->canSetMasterMute()) {
9549 mMasterMute = false;
9550 }
9551 }
9552}
9553
9554void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9555 audio_stream_type_t streamType,
9556 audio_session_t sessionId,
9557 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009558 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009559 audio_port_handle_t portId)
9560{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009561 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009562 mStreamType = streamType;
9563}
9564
9565AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9566{
9567 Mutex::Autolock _l(mLock);
9568 AudioStreamOut *output = mOutput;
9569 mOutput = NULL;
9570 return output;
9571}
9572
9573void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9574{
9575 Mutex::Autolock _l(mLock);
9576 // Don't apply master volume in SW if our HAL can do it for us.
9577 if (mAudioHwDev &&
9578 mAudioHwDev->canSetMasterVolume()) {
9579 mMasterVolume = 1.0;
9580 } else {
9581 mMasterVolume = value;
9582 }
9583}
9584
9585void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9586{
9587 Mutex::Autolock _l(mLock);
9588 // Don't apply master mute in SW if our HAL can do it for us.
9589 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9590 mMasterMute = false;
9591 } else {
9592 mMasterMute = muted;
9593 }
9594}
9595
9596void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9597{
9598 Mutex::Autolock _l(mLock);
9599 if (stream == mStreamType) {
9600 mStreamVolume = value;
9601 broadcast_l();
9602 }
9603}
9604
9605float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9606{
9607 Mutex::Autolock _l(mLock);
9608 if (stream == mStreamType) {
9609 return mStreamVolume;
9610 }
9611 return 0.0f;
9612}
9613
9614void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9615{
9616 Mutex::Autolock _l(mLock);
9617 if (stream == mStreamType) {
9618 mStreamMute= muted;
9619 broadcast_l();
9620 }
9621}
9622
9623void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9624{
9625 Mutex::Autolock _l(mLock);
9626 if (streamType == mStreamType) {
9627 for (const sp<MmapTrack> &track : mActiveTracks) {
9628 track->invalidate();
9629 }
9630 broadcast_l();
9631 }
9632}
9633
9634void AudioFlinger::MmapPlaybackThread::processVolume_l()
9635{
9636 float volume;
9637
9638 if (mMasterMute || mStreamMute) {
9639 volume = 0;
9640 } else {
9641 volume = mMasterVolume * mStreamVolume;
9642 }
9643
9644 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009645
9646 // Convert volumes from float to 8.24
9647 uint32_t vol = (uint32_t)(volume * (1 << 24));
9648
9649 // Delegate volume control to effect in track effect chain if needed
9650 // only one effect chain can be present on DirectOutputThread, so if
9651 // there is one, the track is connected to it
9652 if (!mEffectChains.isEmpty()) {
9653 mEffectChains[0]->setVolume_l(&vol, &vol);
9654 volume = (float)vol / (1 << 24);
9655 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009656 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009657 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9658 mHalVolFloat = volume; // HW volume control worked, so update value.
9659 mNoCallbackWarningCount = 0;
9660 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009661 sp<MmapStreamCallback> callback = mCallback.promote();
9662 if (callback != 0) {
9663 int channelCount;
9664 if (isOutput()) {
9665 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9666 } else {
9667 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9668 }
9669 Vector<float> values;
9670 for (int i = 0; i < channelCount; i++) {
9671 values.add(volume);
9672 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009673 mHalVolFloat = volume; // SW volume control worked, so update value.
9674 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009675 mLock.unlock();
9676 callback->onVolumeChanged(mChannelMask, values);
9677 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009678 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009679 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9680 ALOGW("Could not set MMAP stream volume: no volume callback!");
9681 mNoCallbackWarningCount++;
9682 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009683 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009684 }
9685 }
9686}
9687
Kevin Rocard069c2712018-03-29 19:09:14 -07009688void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9689{
9690 if (mOutput == nullptr || mOutput->stream == nullptr ||
9691 !mActiveTracks.readAndClearHasChanged()) {
9692 return;
9693 }
9694 StreamOutHalInterface::SourceMetadata metadata;
9695 for (const sp<MmapTrack> &track : mActiveTracks) {
9696 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01009697 playback_track_metadata_v7_t trackMetadata;
9698 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009699 .usage = track->attributes().usage,
9700 .content_type = track->attributes().content_type,
9701 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +01009702 };
9703 trackMetadata.channel_mask = track->channelMask(),
9704 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9705 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009706 }
9707 mOutput->stream->updateSourceMetadata(metadata);
9708}
9709
Eric Laurent6acd1d42017-01-04 14:23:29 -08009710void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9711{
9712 if (!mMasterMute) {
9713 char value[PROPERTY_VALUE_MAX];
9714 if (property_get("ro.audio.silent", value, "0") > 0) {
9715 char *endptr;
9716 unsigned long ul = strtoul(value, &endptr, 0);
9717 if (*endptr == '\0' && ul != 0) {
9718 ALOGD("Silence is golden");
9719 // The setprop command will not allow a property to be changed after
9720 // the first time it is set, so we don't have to worry about un-muting.
9721 setMasterMute_l(true);
9722 }
9723 }
9724 }
9725}
9726
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009727void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9728{
9729 MmapThread::toAudioPortConfig(config);
9730 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9731 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9732 config->flags.output = mOutput->flags;
9733 }
9734}
9735
jiabinb7d8c5a2020-08-26 17:24:52 -07009736status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
9737 int64_t *timeNanos)
9738{
9739 if (mOutput == nullptr) {
9740 return NO_INIT;
9741 }
9742 struct timespec timestamp;
9743 status_t status = mOutput->getPresentationPosition(position, &timestamp);
9744 if (status == NO_ERROR) {
9745 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
9746 }
9747 return status;
9748}
9749
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009750void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009751{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009752 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009753
Glenn Kastend3bb6452016-12-05 18:14:37 -08009754 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9755 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009756 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9757}
9758
9759AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9760 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009761 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009762 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009763 mInput(input)
9764{
9765 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9766 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9767}
9768
Eric Laurent331679c2018-04-16 17:03:16 -07009769status_t AudioFlinger::MmapCaptureThread::exitStandby()
9770{
Phil Burkf054fc32018-12-06 09:45:59 -08009771 {
9772 // mInput might have been cleared by clearInput()
9773 Mutex::Autolock _l(mLock);
9774 if (mInput != nullptr && mInput->stream != nullptr) {
9775 mInput->stream->setGain(1.0f);
9776 }
9777 }
Eric Laurent331679c2018-04-16 17:03:16 -07009778 return MmapThread::exitStandby();
9779}
9780
Eric Laurent6acd1d42017-01-04 14:23:29 -08009781AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9782{
9783 Mutex::Autolock _l(mLock);
9784 AudioStreamIn *input = mInput;
9785 mInput = NULL;
9786 return input;
9787}
Kevin Rocard069c2712018-03-29 19:09:14 -07009788
Eric Laurent331679c2018-04-16 17:03:16 -07009789
9790void AudioFlinger::MmapCaptureThread::processVolume_l()
9791{
9792 bool changed = false;
9793 bool silenced = false;
9794
9795 sp<MmapStreamCallback> callback = mCallback.promote();
9796 if (callback == 0) {
9797 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9798 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9799 mNoCallbackWarningCount++;
9800 }
9801 }
9802
9803 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9804 // track is silenced and unmute otherwise
9805 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9806 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9807 changed = true;
9808 silenced = mActiveTracks[i]->isSilenced_l();
9809 }
9810 }
9811
9812 if (changed) {
9813 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9814 }
9815}
9816
Kevin Rocard069c2712018-03-29 19:09:14 -07009817void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9818{
9819 if (mInput == nullptr || mInput->stream == nullptr ||
9820 !mActiveTracks.readAndClearHasChanged()) {
9821 return;
9822 }
9823 StreamInHalInterface::SinkMetadata metadata;
9824 for (const sp<MmapTrack> &track : mActiveTracks) {
9825 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01009826 record_track_metadata_v7_t trackMetadata;
9827 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009828 .source = track->attributes().source,
9829 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01009830 };
9831 trackMetadata.channel_mask = track->channelMask(),
9832 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9833 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009834 }
9835 mInput->stream->updateSinkMetadata(metadata);
9836}
9837
Eric Laurent5ada82e2019-08-29 17:53:54 -07009838void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -07009839{
9840 Mutex::Autolock _l(mLock);
9841 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07009842 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -07009843 mActiveTracks[i]->setSilenced_l(silenced);
9844 broadcast_l();
9845 }
9846 }
9847}
9848
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009849void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9850{
9851 MmapThread::toAudioPortConfig(config);
9852 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9853 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9854 config->flags.input = mInput->flags;
9855 }
9856}
9857
jiabinb7d8c5a2020-08-26 17:24:52 -07009858status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
9859 uint64_t *position, int64_t *timeNanos)
9860{
9861 if (mInput == nullptr) {
9862 return NO_INIT;
9863 }
9864 return mInput->getCapturePosition((int64_t*)position, timeNanos);
9865}
9866
Glenn Kasten63238ef2015-03-02 15:50:29 -08009867} // namespace android