blob: 90f7a6152b7ee96d846bc646b6f06f181dc7ad38 [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();
629 mTimestampVerifier.discontinuity();
630
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).
2751 mTimestampVerifier.discontinuity();
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.
3443 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003444
3445 // MIXER
3446 nsecs_t lastWarning = 0;
3447
3448 // DUPLICATING
3449 // FIXME could this be made local to while loop?
3450 writeFrames = 0;
3451
3452 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003453 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003454
3455 if (mType == MIXER) {
3456 sleepTimeShift = 0;
3457 }
3458
3459 CpuStats cpuStats;
3460 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3461
3462 acquireWakeLock();
3463
Glenn Kasteneef598c2017-04-03 14:41:13 -07003464 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3465 // thread associated with this PlaybackThread.
3466 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3467 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003468 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3469 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003470 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003471 const char *logString = NULL;
3472
rago1bb90822017-05-02 18:31:48 -07003473 // Estimated time for next buffer to be written to hal. This is used only on
3474 // suspended mode (for now) to help schedule the wait time until next iteration.
3475 nsecs_t timeLoopNextNs = 0;
3476
Eric Laurent664539d2013-09-23 18:24:31 -07003477 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003478
Andy Hungf3234512018-07-03 14:51:47 -07003479 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3480 // TODO: add confirmation checks:
3481 // 1) DIRECT threads and linear PCM format really resets to 0?
3482 // 2) Is frame count really valid if not linear pcm?
3483 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3484 if (mType == OFFLOAD || mType == DIRECT) {
3485 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3486 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003487 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003488
Andy Hung446f4df2019-02-21 12:26:41 -08003489 // loopCount is used for statistics and diagnostics.
3490 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003491 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003492 // Log merge requests are performed during AudioFlinger binder transactions, but
3493 // that does not cover audio playback. It's requested here for that reason.
3494 mAudioFlinger->requestLogMerge();
3495
Eric Laurent81784c32012-11-19 14:55:58 -08003496 cpuStats.sample(myName);
3497
3498 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003499 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003500 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003501
Andy Hung2dbffc22018-08-08 18:50:41 -07003502 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3503 //
jiabinc52b1ff2019-10-31 17:20:42 -07003504 // Note: we access outDeviceTypes() outside of mLock.
3505 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003506 // Here, we try for the AF lock, but do not block on it as the latency
3507 // is more informational.
3508 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3509 std::vector<PatchPanel::SoftwarePatch> swPatches;
3510 double latencyMs;
3511 status_t status = INVALID_OPERATION;
3512 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3513 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3514 && swPatches.size() > 0) {
3515 status = swPatches[0].getLatencyMs_l(&latencyMs);
3516 downstreamPatchHandle = swPatches[0].getPatchHandle();
3517 }
3518 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003519 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003520 lastDownstreamPatchHandle = downstreamPatchHandle;
3521 }
3522 if (status == OK) {
3523 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003524 // latency of 5 seconds).
3525 const double minLatency = 0., maxLatency = 5000.;
3526 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003527 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003528 } else {
3529 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003530 if (latencyMs < minLatency) latencyMs = minLatency;
3531 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003532 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003533 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003534 }
3535 mAudioFlinger->mLock.unlock();
3536 }
3537 } else {
3538 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3539 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003540 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003541 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3542 }
3543 }
3544
Eric Laurent81784c32012-11-19 14:55:58 -08003545 { // scope for mLock
3546
3547 Mutex::Autolock _l(mLock);
3548
Eric Laurent021cf962014-05-13 10:18:14 -07003549 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003550
Glenn Kasteneef598c2017-04-03 14:41:13 -07003551 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003552 if (logString != NULL) {
3553 mNBLogWriter->logTimestamp();
3554 mNBLogWriter->log(logString);
3555 logString = NULL;
3556 }
3557
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003558 // Collect timestamp statistics for the Playback Thread types that support it.
3559 if (mType == MIXER
3560 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003561 || mType == DIRECT
3562 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003563 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003564 // and associate with the sink frames written out. We need
3565 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003566 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003567 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003568 if (mStandby) {
3569 mTimestampVerifier.discontinuity();
3570 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3571 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3572 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3573 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003574
3575 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003576 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
Andy Hungc8fddf32018-08-08 18:32:37 -07003577 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3578 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3579 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3580 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3581 = correctedTimestamp.mFrames;
3582 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3583 = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10003584 ALOGVV("TS_AFTER: %d %lld %lld", id(),
Andy Hungc8fddf32018-08-08 18:32:37 -07003585 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3586 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003587
3588 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003589 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003590 const int64_t newPosition =
3591 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003592 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003593 // prevent retrograde
3594 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3595 newPosition,
3596 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3597 - mSuspendedFrames));
3598 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003599 }
3600
Andy Hung818e7a32016-02-16 18:08:07 -08003601 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003602 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003603
3604 // We keep track of the last valid kernel position in case we are in underrun
3605 // and the normal mixer period is the same as the fast mixer period, or there
3606 // is some error from the HAL.
3607 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3608 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3609 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3610 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3611 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3612
3613 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3614 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3615 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3616 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003617 }
3618
3619 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3620 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003621 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003622 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003623 }
3624
Andy Hung818e7a32016-02-16 18:08:07 -08003625 // copy over kernel info
3626 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003627 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3628 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003629 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3630 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003631 } else {
3632 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003633 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003634
Andy Hungc54b1ff2016-02-23 14:07:07 -08003635 // mFramesWritten for non-offloaded tracks are contiguous
3636 // even after standby() is called. This is useful for the track frame
3637 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003638 bool serverLocationUpdate = false;
3639 if (mFramesWritten != lastFramesWritten) {
3640 serverLocationUpdate = true;
3641 lastFramesWritten = mFramesWritten;
3642 }
3643 // Only update timestamps if there is a meaningful change.
3644 // Either the kernel timestamp must be valid or we have written something.
3645 if (kernelLocationUpdate || serverLocationUpdate) {
3646 if (serverLocationUpdate) {
3647 // use the time before we called the HAL write - it is a bit more accurate
3648 // to when the server last read data than the current time here.
3649 //
Andy Hung446f4df2019-02-21 12:26:41 -08003650 // If we haven't written anything, mLastIoBeginNs will be -1
Andy Hung69488c42016-05-16 18:43:33 -07003651 // and we use systemTime().
3652 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
Andy Hung446f4df2019-02-21 12:26:41 -08003653 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
3654 ? systemTime() : mLastIoBeginNs;
Andy Hung69488c42016-05-16 18:43:33 -07003655 }
Andy Hungdae27702016-10-31 14:01:16 -07003656
3657 for (const sp<Track> &t : mActiveTracks) {
3658 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003659 t->updateTrackFrameInfo(
3660 t->mAudioTrackServerProxy->framesReleased(),
3661 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003662 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003663 mTimestamp);
3664 }
Andy Hunge10393e2015-06-12 13:59:33 -07003665 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003666 }
Andy Hunge6c37112019-02-26 17:38:10 -08003667
3668 if (audio_has_proportional_frames(mFormat)) {
3669 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
3670 if (latencyMs != 0.) { // note 0. means timestamp is empty.
3671 mLatencyMs.add(latencyMs);
3672 }
3673 }
3674
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003675 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003676#if 0
3677 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003678 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003679 timespec ts;
3680 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003681 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003682 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003683 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003684 }
3685 ++z;
3686#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003687 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003688 if (mSignalPending) {
3689 // A signal was raised while we were unlocked
3690 mSignalPending = false;
3691 } else if (waitingAsyncCallback_l()) {
3692 if (exitPending()) {
3693 break;
3694 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003695 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003696 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003697 releaseWakeLock_l();
3698 released = true;
3699 }
Andy Hung10cbff12017-02-21 17:30:14 -08003700
3701 const int64_t waitNs = computeWaitTimeNs_l();
3702 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3703 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3704 if (status == TIMED_OUT) {
3705 mSignalPending = true; // if timeout recheck everything
3706 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003707 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003708 if (released) {
3709 acquireWakeLock_l();
3710 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003711 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3712 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003713
3714 continue;
3715 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003716 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003717 isSuspended()) {
3718 // put audio hardware into standby after short delay
3719 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003720
3721 threadLoop_standby();
3722
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003723 // This is where we go into standby
3724 if (!mStandby) {
3725 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003726 mThreadMetrics.logEndInterval();
3727 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003728 }
Andy Hungd0979812019-02-21 15:51:44 -08003729 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003730 }
3731
Eric Tan39ec8d62018-07-24 09:49:29 -07003732 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003733 // we're about to wait, flush the binder command buffer
3734 IPCThreadState::self()->flushCommands();
3735
3736 clearOutputTracks();
3737
3738 if (exitPending()) {
3739 break;
3740 }
3741
3742 releaseWakeLock_l();
3743 // wait until we have something to do...
3744 ALOGV("%s going to sleep", myName.string());
3745 mWaitWorkCV.wait(mLock);
3746 ALOGV("%s waking up", myName.string());
3747 acquireWakeLock_l();
3748
3749 mMixerStatus = MIXER_IDLE;
3750 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3751 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003752 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003753 checkSilentMode_l();
3754
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003755 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3756 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003757 if (mType == MIXER) {
3758 sleepTimeShift = 0;
3759 }
3760
3761 continue;
3762 }
3763 }
Eric Laurent81784c32012-11-19 14:55:58 -08003764 // mMixerStatusIgnoringFastTracks is also updated internally
3765 mMixerStatus = prepareTracks_l(&tracksToRemove);
3766
Andy Hungdae27702016-10-31 14:01:16 -07003767 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003768
Kevin Rocard069c2712018-03-29 19:09:14 -07003769 updateMetadata_l();
3770
Eric Laurent81784c32012-11-19 14:55:58 -08003771 // prevent any changes in effect chain list and in each effect chain
3772 // during mixing and effect process as the audio buffers could be deleted
3773 // or modified if an effect is created or deleted
3774 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003775
3776 // Determine which session to pick up haptic data.
3777 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003778 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003779 // TODO: Write haptic data directly to sink buffer when mixing.
3780 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3781 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003782 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3783 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3784 activeHapticSessionId = track->sessionId();
3785 break;
3786 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003787 if (track->getHapticPlaybackEnabled()) {
3788 activeHapticSessionId = track->sessionId();
3789 break;
3790 }
3791 }
3792 }
3793
Andy Hungc1646382019-04-30 16:12:10 -07003794 // Acquire a local copy of active tracks with lock (release w/o lock).
3795 //
3796 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3797 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3798 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3799 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003800 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003801
Eric Laurentbfb1b832013-01-07 09:53:42 -08003802 if (mBytesRemaining == 0) {
3803 mCurrentWriteLength = 0;
3804 if (mMixerStatus == MIXER_TRACKS_READY) {
3805 // threadLoop_mix() sets mCurrentWriteLength
3806 threadLoop_mix();
3807 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3808 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003809 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003810 // must be written to HAL
3811 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003812 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003813 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003814
3815 // Tally underrun frames as we are inserting 0s here.
3816 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003817 if (track->mFillingUpStatus == Track::FS_ACTIVE
3818 && !track->isStopped()
3819 && !track->isPaused()
3820 && !track->isTerminated()) {
3821 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3822 __func__, track->id(), track->getTrackStateAsString(),
3823 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003824 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3825 }
3826 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003827 }
3828 }
Andy Hung98ef9782014-03-04 14:46:50 -08003829 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003830 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003831 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3832 // or mSinkBuffer (if there are no effects).
3833 //
3834 // This is done pre-effects computation; if effects change to
3835 // support higher precision, this needs to move.
3836 //
3837 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003838 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003839 if (mMixerBufferValid) {
3840 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3841 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3842
Andy Hung2ddee192015-12-18 17:34:44 -08003843 // mono blend occurs for mixer threads only (not direct or offloaded)
3844 // and is handled here if we're going directly to the sink.
3845 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003846 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3847 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003848 }
3849
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003850 if (!hasFastMixer()) {
3851 // Balance must take effect after mono conversion.
3852 // We do it here if there is no FastMixer.
3853 // mBalance detects zero balance within the class for speed (not needed here).
3854 mBalance.setBalance(mMasterBalance.load());
3855 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3856 }
3857
Andy Hung98ef9782014-03-04 14:46:50 -08003858 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003859 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3860
3861 // If we're going directly to the sink and there are haptic channels,
3862 // we should adjust channels as the sample data is partially interleaved
3863 // in this case.
3864 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3865 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3866 mChannelCount + mHapticChannelCount,
3867 audio_bytes_per_sample(format),
3868 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3869 }
Andy Hung98ef9782014-03-04 14:46:50 -08003870 }
3871
Eric Laurentbfb1b832013-01-07 09:53:42 -08003872 mBytesRemaining = mCurrentWriteLength;
3873 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003874 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3875 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3876 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3877 mBytesWritten += mBytesRemaining;
3878 mFramesWritten += framesRemaining;
3879 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003880 mBytesRemaining = 0;
3881 }
Eric Laurent81784c32012-11-19 14:55:58 -08003882
Eric Laurentbfb1b832013-01-07 09:53:42 -08003883 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003884 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003885 for (size_t i = 0; i < effectChains.size(); i ++) {
3886 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003887 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003888 if (activeHapticSessionId != AUDIO_SESSION_NONE
3889 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003890 // Haptic data is active in this case, copy it directly from
3891 // in buffer to out buffer.
3892 const size_t audioBufferSize = mNormalFrameCount
3893 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3894 memcpy_by_audio_format(
3895 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3896 EFFECT_BUFFER_FORMAT,
3897 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3898 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3899 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003900 }
Eric Laurent81784c32012-11-19 14:55:58 -08003901 }
3902 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003903 // Process effect chains for offloaded thread even if no audio
3904 // was read from audio track: process only updates effect state
3905 // and thus does have to be synchronized with audio writes but may have
3906 // to be called while waiting for async write callback
3907 if (mType == OFFLOAD) {
3908 for (size_t i = 0; i < effectChains.size(); i ++) {
3909 effectChains[i]->process_l();
3910 }
3911 }
Eric Laurent81784c32012-11-19 14:55:58 -08003912
Andy Hung98ef9782014-03-04 14:46:50 -08003913 // Only if the Effects buffer is enabled and there is data in the
3914 // Effects buffer (buffer valid), we need to
3915 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003916 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003917 if (mEffectBufferValid) {
3918 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003919
3920 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003921 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3922 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003923 }
3924
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003925 if (!hasFastMixer()) {
3926 // Balance must take effect after mono conversion.
3927 // We do it here if there is no FastMixer.
3928 // mBalance detects zero balance within the class for speed (not needed here).
3929 mBalance.setBalance(mMasterBalance.load());
3930 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3931 }
3932
Andy Hung98ef9782014-03-04 14:46:50 -08003933 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003934 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3935 // The sample data is partially interleaved when haptic channels exist,
3936 // we need to adjust channels here.
3937 if (mHapticChannelCount > 0) {
3938 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3939 mChannelCount + mHapticChannelCount,
3940 audio_bytes_per_sample(mFormat),
3941 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3942 }
Andy Hung98ef9782014-03-04 14:46:50 -08003943 }
3944
Eric Laurent81784c32012-11-19 14:55:58 -08003945 // enable changes in effect chain
3946 unlockEffectChains(effectChains);
3947
Eric Laurentbfb1b832013-01-07 09:53:42 -08003948 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003949 // mSleepTimeUs == 0 means we must write to audio hardware
3950 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003951 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003952 // writePeriodNs is updated >= 0 when ret > 0.
3953 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003954 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003955 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003956 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003957 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003958 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003959 if (ret < 0) {
3960 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003961 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003962 mBytesWritten += ret;
3963 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003964 const int64_t frames = ret / mFrameSize;
3965 mFramesWritten += frames;
3966
3967 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3968 // process information relating to write time.
3969 if (audio_has_proportional_frames(mFormat)) {
3970 // we are in a continuous mixing cycle
3971 if (mMixerStatus == MIXER_TRACKS_READY &&
3972 loopCount == lastLoopCountWritten + 1) {
3973
3974 const double jitterMs =
3975 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3976 {frames, writePeriodNs},
3977 {0, 0} /* lastTimestamp */, mSampleRate);
3978 const double processMs =
3979 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3980
3981 Mutex::Autolock _l(mLock);
3982 mIoJitterMs.add(jitterMs);
3983 mProcessTimeMs.add(processMs);
3984 }
3985
3986 // write blocked detection
3987 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3988 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3989 mNumDelayedWrites++;
3990 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3991 ATRACE_NAME("underrun");
3992 ALOGW("write blocked for %lld msecs, "
3993 "%d delayed writes, thread %d",
3994 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3995 mNumDelayedWrites, mId);
3996 lastWarning = lastIoEndNs;
3997 }
3998 }
3999 }
4000 // update timing info.
4001 mLastIoBeginNs = lastIoBeginNs;
4002 mLastIoEndNs = lastIoEndNs;
4003 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004004 }
4005 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4006 (mMixerStatus == MIXER_DRAIN_ALL)) {
4007 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004008 }
Andy Hung08fb1742015-05-31 23:22:10 -07004009 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004010
4011 if (mThreadThrottle
4012 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004013 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004014 // Limit MixerThread data processing to no more than twice the
4015 // expected processing rate.
4016 //
4017 // This helps prevent underruns with NuPlayer and other applications
4018 // which may set up buffers that are close to the minimum size, or use
4019 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4020 //
4021 // The throttle smooths out sudden large data drains from the device,
4022 // e.g. when it comes out of standby, which often causes problems with
4023 // (1) mixer threads without a fast mixer (which has its own warm-up)
4024 // (2) minimum buffer sized tracks (even if the track is full,
4025 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004026 //
4027 // Total time spent in last processing cycle equals time spent in
4028 // 1. threadLoop_write, as well as time spent in
4029 // 2. threadLoop_mix (significant for heavy mixing, especially
4030 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004031
Andy Hung446f4df2019-02-21 12:26:41 -08004032 // it's OK if deltaMs is an overestimate.
4033
4034 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004035
Ivan Lozanoea04d392017-11-07 14:37:07 -08004036 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004037 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004038 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004039
Andy Hung08fb1742015-05-31 23:22:10 -07004040 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004041 // notify of throttle start on verbose log
4042 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4043 "mixer(%p) throttle begin:"
4044 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004045 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004046 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004047 // Throttle must be attributed to the previous mixer loop's write time
4048 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004049 // This also ensures proper timing statistics.
4050 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004051 } else {
4052 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4053 if (diff > 0) {
4054 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004055 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004056 ALOGD_IF(!isSingleDeviceType(
4057 outDeviceTypes(), audio_is_a2dp_out_device) &&
4058 !isSingleDeviceType(
4059 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004060 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004061 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4062 }
Andy Hung08fb1742015-05-31 23:22:10 -07004063 }
4064 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004065 }
Eric Laurent81784c32012-11-19 14:55:58 -08004066
Eric Laurentbfb1b832013-01-07 09:53:42 -08004067 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004068 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004069 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004070 // suspended requires accurate metering of sleep time.
4071 if (isSuspended()) {
4072 // advance by expected sleepTime
4073 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4074 const nsecs_t nowNs = systemTime();
4075
4076 // compute expected next time vs current time.
4077 // (negative deltas are treated as delays).
4078 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4079 if (deltaNs < -kMaxNextBufferDelayNs) {
4080 // Delays longer than the max allowed trigger a reset.
4081 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4082 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4083 timeLoopNextNs = nowNs + deltaNs;
4084 } else if (deltaNs < 0) {
4085 // Delays within the max delay allowed: zero the delta/sleepTime
4086 // to help the system catch up in the next iteration(s)
4087 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4088 deltaNs = 0;
4089 }
4090 // update sleep time (which is >= 0)
4091 mSleepTimeUs = deltaNs / 1000;
4092 }
Eric Laurente93cc032016-05-05 10:15:10 -07004093 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4094 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004095 }
Glenn Kastene7754022014-10-31 12:11:26 -07004096 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004097 }
Eric Laurent81784c32012-11-19 14:55:58 -08004098 }
4099
4100 // Finally let go of removed track(s), without the lock held
4101 // since we can't guarantee the destructors won't acquire that
4102 // same lock. This will also mutate and push a new fast mixer state.
4103 threadLoop_removeTracks(tracksToRemove);
4104 tracksToRemove.clear();
4105
4106 // FIXME I don't understand the need for this here;
4107 // it was in the original code but maybe the
4108 // assignment in saveOutputTracks() makes this unnecessary?
4109 clearOutputTracks();
4110
4111 // Effect chains will be actually deleted here if they were removed from
4112 // mEffectChains list during mixing or effects processing
4113 effectChains.clear();
4114
4115 // FIXME Note that the above .clear() is no longer necessary since effectChains
4116 // is now local to this block, but will keep it for now (at least until merge done).
4117 }
4118
Eric Laurentbfb1b832013-01-07 09:53:42 -08004119 threadLoop_exit();
4120
Eric Laurentcf817a22014-08-04 20:36:31 -07004121 if (!mStandby) {
4122 threadLoop_standby();
4123 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004124 }
4125
4126 releaseWakeLock();
4127
4128 ALOGV("Thread %p type %d exiting", this, mType);
4129 return false;
4130}
4131
Eric Laurentbfb1b832013-01-07 09:53:42 -08004132// removeTracks_l() must be called with ThreadBase::mLock held
4133void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4134{
Andy Hungfe726a62018-09-27 15:17:25 -07004135 for (const auto& track : tracksToRemove) {
4136 mActiveTracks.remove(track);
4137 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4138 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4139 if (chain != 0) {
4140 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4141 __func__, track->id(), chain.get(), track->sessionId());
4142 chain->decActiveTrackCnt();
4143 }
4144 // If an external client track, inform APM we're no longer active, and remove if needed.
4145 // We do this under lock so that the state is consistent if the Track is destroyed.
4146 if (track->isExternalTrack()) {
4147 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004148 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004149 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004150 }
4151 }
Andy Hungfe726a62018-09-27 15:17:25 -07004152 if (track->isTerminated()) {
4153 // remove from our tracks vector
4154 removeTrack_l(track);
4155 }
jiabineb3bda02020-06-30 14:07:03 -07004156 if (mHapticChannelCount > 0 &&
4157 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4158 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004159 mLock.unlock();
4160 // Unlock due to VibratorService will lock for this call and will
4161 // call Tracks.mute/unmute which also require thread's lock.
4162 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4163 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004164
4165 // When the track is stop, set the haptic intensity as MUTE
4166 // for the HapticGenerator effect.
4167 if (chain != nullptr) {
4168 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4169 }
jiabin245cdd92018-12-07 17:55:15 -08004170 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004172}
Eric Laurent81784c32012-11-19 14:55:58 -08004173
Eric Laurentaccc1472013-09-20 09:36:34 -07004174status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4175{
4176 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004177 ExtendedTimestamp ets;
4178 status_t status = mNormalSink->getTimestamp(ets);
4179 if (status == NO_ERROR) {
4180 status = ets.getBestTimestamp(&timestamp);
4181 }
4182 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004183 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004184 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07004185 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004186 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07004187 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11004188 if (mDownstreamLatencyStatMs.getN() > 0) {
4189 const uint32_t positionOffset =
4190 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4191 if (positionOffset > timestamp.mPosition) {
4192 timestamp.mPosition = 0;
4193 } else {
4194 timestamp.mPosition -= positionOffset;
4195 }
4196 }
Eric Laurentaccc1472013-09-20 09:36:34 -07004197 return NO_ERROR;
4198 }
4199 }
4200 return INVALID_OPERATION;
4201}
Eric Laurent1c333e22014-05-20 10:48:17 -07004202
Eric Laurenteab90452019-06-24 15:17:46 -07004203// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4204// still applied by the mixer.
4205// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4206// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4207// if more than one track are active
4208status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4209{
4210 status_t result = NO_ERROR;
4211 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4212 if (*volume != mLeftVolFloat) {
4213 result = mOutput->stream->setVolume(*volume, *volume);
4214 ALOGE_IF(result != OK,
4215 "Error when setting output stream volume: %d", result);
4216 if (result == NO_ERROR) {
4217 mLeftVolFloat = *volume;
4218 }
4219 }
4220 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4221 // remove stream volume contribution from software volume.
4222 if (mLeftVolFloat == *volume) {
4223 *volume = 1.0f;
4224 }
4225 }
4226 return result;
4227}
4228
Eric Laurent054d9d32015-04-24 08:48:48 -07004229status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4230 audio_patch_handle_t *handle)
4231{
Andy Hungf60abce2016-08-26 11:37:54 -07004232 status_t status;
4233 if (property_get_bool("af.patch_park", false /* default_value */)) {
4234 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4235 // or if HAL does not properly lock against access.
4236 AutoPark<FastMixer> park(mFastMixer);
4237 status = PlaybackThread::createAudioPatch_l(patch, handle);
4238 } else {
4239 status = PlaybackThread::createAudioPatch_l(patch, handle);
4240 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004241 return status;
4242}
4243
Eric Laurent1c333e22014-05-20 10:48:17 -07004244status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4245 audio_patch_handle_t *handle)
4246{
4247 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004248
4249 // store new device and send to effects
4250 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004251 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004252 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004253 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4254 && !mOutput->audioHwDev->supportsAudioPatches(),
4255 "Enumerated device type(%#x) must not be used "
4256 "as it does not support audio patches",
4257 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004258 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004259 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4260 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004261 }
4262
François Gaffie0c280aa2018-07-25 10:02:15 +02004263 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004264#ifdef ADD_BATTERY_DATA
4265 // when changing the audio output device, call addBatteryData to notify
4266 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004267 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004268 uint32_t params = 0;
4269 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004270 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004271 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004272 }
4273
Eric Laurent054d9d32015-04-24 08:48:48 -07004274 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004275 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004276 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4277 }
4278
4279 if (params != 0) {
4280 addBatteryData(params);
4281 }
4282 }
4283#endif
4284
4285 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004286 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004287 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004288
jiabinc52b1ff2019-10-31 17:20:42 -07004289 // mPatch.num_sinks is not set when the thread is created so that
4290 // the first patch creation triggers an ioConfigChanged callback
4291 bool configChanged = (mPatch.num_sinks == 0) ||
4292 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004293 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004294 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004295 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004296
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004297 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004298 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4299 status = hwDevice->createAudioPatch(patch->num_sources,
4300 patch->sources,
4301 patch->num_sinks,
4302 patch->sinks,
4303 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004304 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004305 char *address;
4306 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4307 //FIXME: we only support address on first sink with HAL version < 3.0
4308 address = audio_device_address_to_parameter(
4309 patch->sinks[0].ext.device.type,
4310 patch->sinks[0].ext.device.address);
4311 } else {
4312 address = (char *)calloc(1, 1);
4313 }
4314 AudioParameter param = AudioParameter(String8(address));
4315 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004316 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004317 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004318 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004319 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004320 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004321
4322 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004323 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004324 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004325 // also dispatch to active AudioTracks for MediaMetrics
4326 for (const auto &track : mActiveTracks) {
4327 track->logEndInterval();
4328 track->logBeginInterval(patchSinksAsString);
4329 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004330
Eric Laurente8726fe2015-06-26 09:39:24 -07004331 if (configChanged) {
4332 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4333 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004334 return status;
4335}
4336
Eric Laurent054d9d32015-04-24 08:48:48 -07004337status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4338{
Andy Hungf60abce2016-08-26 11:37:54 -07004339 status_t status;
4340 if (property_get_bool("af.patch_park", false /* default_value */)) {
4341 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4342 // or if HAL does not properly lock against access.
4343 AutoPark<FastMixer> park(mFastMixer);
4344 status = PlaybackThread::releaseAudioPatch_l(handle);
4345 } else {
4346 status = PlaybackThread::releaseAudioPatch_l(handle);
4347 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004348 return status;
4349}
4350
Eric Laurent1c333e22014-05-20 10:48:17 -07004351status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4352{
4353 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004354
jiabinc52b1ff2019-10-31 17:20:42 -07004355 mPatch = audio_patch{};
4356 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004357
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004358 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004359 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4360 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004361 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004362 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004363 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004364 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004365 }
4366 return status;
4367}
4368
Eric Laurent83b88082014-06-20 18:31:16 -07004369void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4370{
4371 Mutex::Autolock _l(mLock);
4372 mTracks.add(track);
4373}
4374
4375void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4376{
4377 Mutex::Autolock _l(mLock);
4378 destroyTrack_l(track);
4379}
4380
Mikhail Naganovdc769682018-05-04 15:34:08 -07004381void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004382{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004383 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004384 config->role = AUDIO_PORT_ROLE_SOURCE;
4385 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4386 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004387 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4388 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4389 config->flags.output = mOutput->flags;
4390 }
Eric Laurent83b88082014-06-20 18:31:16 -07004391}
4392
Eric Laurent81784c32012-11-19 14:55:58 -08004393// ----------------------------------------------------------------------------
4394
4395AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004396 audio_io_handle_t id, bool systemReady, type_t type)
4397 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004398 // mAudioMixer below
4399 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004400 mFastMixerFutex(0),
4401 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004402 // mOutputSink below
4403 // mPipeSink below
4404 // mNormalSink below
4405{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004406 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004407 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004408 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004409 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004410 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4411 mNormalFrameCount);
4412 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4413
Andy Hungfbfc3952015-01-15 13:33:51 -08004414 if (type == DUPLICATING) {
4415 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4416 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4417 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4418 return;
4419 }
Eric Laurent81784c32012-11-19 14:55:58 -08004420 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004421 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004422 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004423 const NBAIO_Format offers[1] = {Format_from_SR_C(
4424 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004425#if !LOG_NDEBUG
4426 ssize_t index =
4427#else
4428 (void)
4429#endif
4430 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004431 ALOG_ASSERT(index == 0);
4432
4433 // initialize fast mixer depending on configuration
4434 bool initFastMixer;
4435 switch (kUseFastMixer) {
4436 case FastMixer_Never:
4437 initFastMixer = false;
4438 break;
4439 case FastMixer_Always:
4440 initFastMixer = true;
4441 break;
4442 case FastMixer_Static:
4443 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004444 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4445 // where the period is less than an experimentally determined threshold that can be
4446 // scheduled reliably with CFS. However, the BT A2DP HAL is
4447 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4448 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004449 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004450 break;
4451 }
Andy Hungfda69402017-02-15 14:33:12 -08004452 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4453 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4454 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004455 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004456 audio_format_t fastMixerFormat;
4457 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4458 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4459 } else {
4460 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4461 }
4462 if (mFormat != fastMixerFormat) {
4463 // change our Sink format to accept our intermediate precision
4464 mFormat = fastMixerFormat;
4465 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004466 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004467 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4468 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4469 }
Eric Laurent81784c32012-11-19 14:55:58 -08004470
4471 // create a MonoPipe to connect our submix to FastMixer
4472 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004473
Andy Hung1258c1a2014-05-23 21:22:17 -07004474 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004475 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004476 format.mFormat = fastMixerFormat;
4477 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4478
Eric Laurent81784c32012-11-19 14:55:58 -08004479 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4480 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4481 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4482 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4483 const NBAIO_Format offers[1] = {format};
4484 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004485#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004486 ssize_t index =
4487#else
4488 (void)
4489#endif
4490 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004491 ALOG_ASSERT(index == 0);
4492 monoPipe->setAvgFrames((mScreenState & 1) ?
4493 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4494 mPipeSink = monoPipe;
4495
Eric Laurent81784c32012-11-19 14:55:58 -08004496 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004497 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004498 FastMixerStateQueue *sq = mFastMixer->sq();
4499#ifdef STATE_QUEUE_DUMP
4500 sq->setObserverDump(&mStateQueueObserverDump);
4501 sq->setMutatorDump(&mStateQueueMutatorDump);
4502#endif
4503 FastMixerState *state = sq->begin();
4504 FastTrack *fastTrack = &state->mFastTracks[0];
4505 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4506 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4507 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004508 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4509 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4510 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004511 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004512 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004513 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004514 fastTrack->mGeneration++;
4515 state->mFastTracksGen++;
4516 state->mTrackMask = 1;
4517 // fast mixer will use the HAL output sink
4518 state->mOutputSink = mOutputSink.get();
4519 state->mOutputSinkGen++;
4520 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004521 // specify sink channel mask when haptic channel mask present as it can not
4522 // be calculated directly from channel count
4523 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004524 ? AUDIO_CHANNEL_NONE
4525 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004526 state->mCommand = FastMixerState::COLD_IDLE;
4527 // already done in constructor initialization list
4528 //mFastMixerFutex = 0;
4529 state->mColdFutexAddr = &mFastMixerFutex;
4530 state->mColdGen++;
4531 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004532 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4533 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004534 sq->end();
4535 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4536
Eric Tan0513b5d2018-09-17 10:32:48 -07004537 NBLog::thread_info_t info;
4538 info.id = mId;
4539 info.type = NBLog::FASTMIXER;
4540 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4541
Eric Laurent81784c32012-11-19 14:55:58 -08004542 // start the fast mixer
4543 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4544 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004545 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004546 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004547
4548#ifdef AUDIO_WATCHDOG
4549 // create and start the watchdog
4550 mAudioWatchdog = new AudioWatchdog();
4551 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4552 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4553 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004554 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004555#endif
Andy Hung8946a282018-04-19 20:04:56 -07004556 } else {
4557#ifdef TEE_SINK
4558 // Only use the MixerThread tee if there is no FastMixer.
4559 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4560 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4561#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004562 }
4563
4564 switch (kUseFastMixer) {
4565 case FastMixer_Never:
4566 case FastMixer_Dynamic:
4567 mNormalSink = mOutputSink;
4568 break;
4569 case FastMixer_Always:
4570 mNormalSink = mPipeSink;
4571 break;
4572 case FastMixer_Static:
4573 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4574 break;
4575 }
4576}
4577
4578AudioFlinger::MixerThread::~MixerThread()
4579{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004580 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004581 FastMixerStateQueue *sq = mFastMixer->sq();
4582 FastMixerState *state = sq->begin();
4583 if (state->mCommand == FastMixerState::COLD_IDLE) {
4584 int32_t old = android_atomic_inc(&mFastMixerFutex);
4585 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004586 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004587 }
4588 }
4589 state->mCommand = FastMixerState::EXIT;
4590 sq->end();
4591 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4592 mFastMixer->join();
4593 // Though the fast mixer thread has exited, it's state queue is still valid.
4594 // We'll use that extract the final state which contains one remaining fast track
4595 // corresponding to our sub-mix.
4596 state = sq->begin();
4597 ALOG_ASSERT(state->mTrackMask == 1);
4598 FastTrack *fastTrack = &state->mFastTracks[0];
4599 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4600 delete fastTrack->mBufferProvider;
4601 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004602 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004603#ifdef AUDIO_WATCHDOG
4604 if (mAudioWatchdog != 0) {
4605 mAudioWatchdog->requestExit();
4606 mAudioWatchdog->requestExitAndWait();
4607 mAudioWatchdog.clear();
4608 }
4609#endif
4610 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004611 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004612 delete mAudioMixer;
4613}
4614
4615
4616uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4617{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004618 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004619 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4620 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4621 }
4622 return latency;
4623}
4624
Eric Laurentbfb1b832013-01-07 09:53:42 -08004625ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004626{
4627 // FIXME we should only do one push per cycle; confirm this is true
4628 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004629 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004630 FastMixerStateQueue *sq = mFastMixer->sq();
4631 FastMixerState *state = sq->begin();
4632 if (state->mCommand != FastMixerState::MIX_WRITE &&
4633 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4634 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004635
4636 // FIXME workaround for first HAL write being CPU bound on some devices
4637 ATRACE_BEGIN("write");
4638 mOutput->write((char *)mSinkBuffer, 0);
4639 ATRACE_END();
4640
Eric Laurent81784c32012-11-19 14:55:58 -08004641 int32_t old = android_atomic_inc(&mFastMixerFutex);
4642 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004643 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004644 }
4645#ifdef AUDIO_WATCHDOG
4646 if (mAudioWatchdog != 0) {
4647 mAudioWatchdog->resume();
4648 }
4649#endif
4650 }
4651 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004652#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004653 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004654 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004655#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004656 sq->end();
4657 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4658 if (kUseFastMixer == FastMixer_Dynamic) {
4659 mNormalSink = mPipeSink;
4660 }
4661 } else {
4662 sq->end(false /*didModify*/);
4663 }
4664 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004665 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004666}
4667
4668void AudioFlinger::MixerThread::threadLoop_standby()
4669{
4670 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004671 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004672 FastMixerStateQueue *sq = mFastMixer->sq();
4673 FastMixerState *state = sq->begin();
4674 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004675 // Report any frames trapped in the Monopipe
4676 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4677 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4678 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4679 "monoPipeWritten:%lld monoPipeLeft:%lld",
4680 (long long)mFramesWritten, (long long)mSuspendedFrames,
4681 (long long)mPipeSink->framesWritten(), pipeFrames);
4682 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4683
Eric Laurent81784c32012-11-19 14:55:58 -08004684 state->mCommand = FastMixerState::COLD_IDLE;
4685 state->mColdFutexAddr = &mFastMixerFutex;
4686 state->mColdGen++;
4687 mFastMixerFutex = 0;
4688 sq->end();
4689 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4690 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4691 if (kUseFastMixer == FastMixer_Dynamic) {
4692 mNormalSink = mOutputSink;
4693 }
4694#ifdef AUDIO_WATCHDOG
4695 if (mAudioWatchdog != 0) {
4696 mAudioWatchdog->pause();
4697 }
4698#endif
4699 } else {
4700 sq->end(false /*didModify*/);
4701 }
4702 }
4703 PlaybackThread::threadLoop_standby();
4704}
4705
Eric Laurentbfb1b832013-01-07 09:53:42 -08004706bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4707{
4708 return false;
4709}
4710
4711bool AudioFlinger::PlaybackThread::shouldStandby_l()
4712{
4713 return !mStandby;
4714}
4715
4716bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4717{
4718 Mutex::Autolock _l(mLock);
4719 return waitingAsyncCallback_l();
4720}
4721
Eric Laurent81784c32012-11-19 14:55:58 -08004722// shared by MIXER and DIRECT, overridden by DUPLICATING
4723void AudioFlinger::PlaybackThread::threadLoop_standby()
4724{
4725 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004726 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004727 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004728 // discard any pending drain or write ack by incrementing sequence
4729 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4730 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004731 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004732 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4733 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004734 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004735 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004736}
4737
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004738void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4739{
4740 ALOGV("signal playback thread");
4741 broadcast_l();
4742}
4743
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004744void AudioFlinger::PlaybackThread::onAsyncError()
4745{
4746 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4747 invalidateTracks((audio_stream_type_t)i);
4748 }
4749}
4750
Eric Laurent81784c32012-11-19 14:55:58 -08004751void AudioFlinger::MixerThread::threadLoop_mix()
4752{
Eric Laurent81784c32012-11-19 14:55:58 -08004753 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004754 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004755 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004756 // increase sleep time progressively when application underrun condition clears.
4757 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4758 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4759 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004760 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004761 sleepTimeShift--;
4762 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004763 mSleepTimeUs = 0;
4764 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004765 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004766
Eric Laurent81784c32012-11-19 14:55:58 -08004767}
4768
4769void AudioFlinger::MixerThread::threadLoop_sleepTime()
4770{
4771 // If no tracks are ready, sleep once for the duration of an output
4772 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004773 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004774 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004775 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4776 // Using the Monopipe availableToWrite, we estimate the
4777 // sleep time to retry for more data (before we underrun).
4778 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4779 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4780 const size_t pipeFrames = monoPipe->maxFrames();
4781 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4782 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4783 const size_t framesDelay = std::min(
4784 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4785 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4786 pipeFrames, framesLeft, framesDelay);
4787 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4788 } else {
4789 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4790 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4791 mSleepTimeUs = kMinThreadSleepTimeUs;
4792 }
4793 // reduce sleep time in case of consecutive application underruns to avoid
4794 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4795 // duration we would end up writing less data than needed by the audio HAL if
4796 // the condition persists.
4797 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4798 sleepTimeShift++;
4799 }
Eric Laurent81784c32012-11-19 14:55:58 -08004800 }
4801 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004802 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004803 }
4804 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004805 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4806 // before effects processing or output.
4807 if (mMixerBufferValid) {
4808 memset(mMixerBuffer, 0, mMixerBufferSize);
4809 } else {
4810 memset(mSinkBuffer, 0, mSinkBufferSize);
4811 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004812 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004813 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4814 "anticipated start");
4815 }
4816 // TODO add standby time extension fct of effect tail
4817}
4818
4819// prepareTracks_l() must be called with ThreadBase::mLock held
4820AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4821 Vector< sp<Track> > *tracksToRemove)
4822{
Andy Hungc0691382018-09-12 18:01:57 -07004823 // clean up deleted track ids in AudioMixer before allocating new tracks
4824 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4825 // for each trackId, destroy it in the AudioMixer
4826 if (mAudioMixer->exists(trackId)) {
4827 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004828 }
4829 });
Andy Hungc0691382018-09-12 18:01:57 -07004830 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004831
4832 mixer_state mixerStatus = MIXER_IDLE;
4833 // find out which tracks need to be processed
4834 size_t count = mActiveTracks.size();
4835 size_t mixedTracks = 0;
4836 size_t tracksWithEffect = 0;
4837 // counts only _active_ fast tracks
4838 size_t fastTracks = 0;
4839 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4840
4841 float masterVolume = mMasterVolume;
4842 bool masterMute = mMasterMute;
4843
4844 if (masterMute) {
4845 masterVolume = 0;
4846 }
4847 // Delegate master volume control to effect in output mix effect chain if needed
4848 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4849 if (chain != 0) {
4850 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4851 chain->setVolume_l(&v, &v);
4852 masterVolume = (float)((v + (1 << 23)) >> 24);
4853 chain.clear();
4854 }
4855
4856 // prepare a new state to push
4857 FastMixerStateQueue *sq = NULL;
4858 FastMixerState *state = NULL;
4859 bool didModify = false;
4860 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004861 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004862 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004863 sq = mFastMixer->sq();
4864 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004865 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004866 }
4867
Andy Hung69aed5f2014-02-25 17:24:40 -08004868 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004869 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004870
Andy Hungbd3b2b02018-05-21 10:53:11 -07004871 // DeferredOperations handles statistics after setting mixerStatus.
4872 class DeferredOperations {
4873 public:
Andy Hungea840382020-05-05 21:50:17 -07004874 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4875 : mMixerStatus(mixerStatus)
4876 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004877
4878 // when leaving scope, tally frames properly.
4879 ~DeferredOperations() {
4880 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4881 // because that is when the underrun occurs.
4882 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004883 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004884 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004885 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004886 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004887 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004888 }
4889 }
Andy Hungea840382020-05-05 21:50:17 -07004890 // send the max underrun frames for this mixer period
4891 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004892 }
4893
4894 // tallyUnderrunFrames() is called to update the track counters
4895 // with the number of underrun frames for a particular mixer period.
4896 // We defer tallying until we know the final mixer status.
4897 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4898 mUnderrunFrames.emplace_back(track, underrunFrames);
4899 }
4900
4901 private:
4902 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004903 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004904 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004905 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004906 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004907
jiabin245cdd92018-12-07 17:55:15 -08004908 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004909 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004910 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004911
4912 // this const just means the local variable doesn't change
4913 Track* const track = t.get();
4914
4915 // process fast tracks
4916 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004917 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4918 "%s(%d): FastTrack(%d) present without FastMixer",
4919 __func__, id(), track->id());
4920
jiabin245cdd92018-12-07 17:55:15 -08004921 if (track->getHapticPlaybackEnabled()) {
4922 noFastHapticTrack = false;
4923 }
Eric Laurent81784c32012-11-19 14:55:58 -08004924
4925 // It's theoretically possible (though unlikely) for a fast track to be created
4926 // and then removed within the same normal mix cycle. This is not a problem, as
4927 // the track never becomes active so it's fast mixer slot is never touched.
4928 // The converse, of removing an (active) track and then creating a new track
4929 // at the identical fast mixer slot within the same normal mix cycle,
4930 // is impossible because the slot isn't marked available until the end of each cycle.
4931 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004932 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004933 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4934 FastTrack *fastTrack = &state->mFastTracks[j];
4935
4936 // Determine whether the track is currently in underrun condition,
4937 // and whether it had a recent underrun.
4938 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4939 FastTrackUnderruns underruns = ftDump->mUnderruns;
4940 uint32_t recentFull = (underruns.mBitFields.mFull -
4941 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4942 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4943 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4944 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4945 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4946 uint32_t recentUnderruns = recentPartial + recentEmpty;
4947 track->mObservedUnderruns = underruns;
4948 // don't count underruns that occur while stopping or pausing
4949 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004950 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004951 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4952 recentUnderruns > 0) {
4953 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004954 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004955 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004956 // Immediately account for FastTrack underruns.
4957 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004958
4959 // This is similar to the state machine for normal tracks,
4960 // with a few modifications for fast tracks.
4961 bool isActive = true;
4962 switch (track->mState) {
4963 case TrackBase::STOPPING_1:
4964 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004965 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004966 track->mState = TrackBase::STOPPING_2;
4967 }
4968 break;
4969 case TrackBase::PAUSING:
4970 // ramp down is not yet implemented
4971 track->setPaused();
4972 break;
4973 case TrackBase::RESUMING:
4974 // ramp up is not yet implemented
4975 track->mState = TrackBase::ACTIVE;
4976 break;
4977 case TrackBase::ACTIVE:
4978 if (recentFull > 0 || recentPartial > 0) {
4979 // track has provided at least some frames recently: reset retry count
4980 track->mRetryCount = kMaxTrackRetries;
4981 }
4982 if (recentUnderruns == 0) {
4983 // no recent underruns: stay active
4984 break;
4985 }
4986 // there has recently been an underrun of some kind
4987 if (track->sharedBuffer() == 0) {
4988 // were any of the recent underruns "empty" (no frames available)?
4989 if (recentEmpty == 0) {
4990 // no, then ignore the partial underruns as they are allowed indefinitely
4991 break;
4992 }
4993 // there has recently been an "empty" underrun: decrement the retry counter
4994 if (--(track->mRetryCount) > 0) {
4995 break;
4996 }
4997 // indicate to client process that the track was disabled because of underrun;
4998 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004999 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005000 // remove from active list, but state remains ACTIVE [confusing but true]
5001 isActive = false;
5002 break;
5003 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005004 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005005 case TrackBase::STOPPING_2:
5006 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005007 case TrackBase::STOPPED:
5008 case TrackBase::FLUSHED: // flush() while active
5009 // Check for presentation complete if track is inactive
5010 // We have consumed all the buffers of this track.
5011 // This would be incomplete if we auto-paused on underrun
5012 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005013 uint32_t latency = 0;
5014 status_t result = mOutput->stream->getLatency(&latency);
5015 ALOGE_IF(result != OK,
5016 "Error when retrieving output stream latency: %d", result);
5017 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005018 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005019 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5020 // track stays in active list until presentation is complete
5021 break;
5022 }
5023 }
5024 if (track->isStopping_2()) {
5025 track->mState = TrackBase::STOPPED;
5026 }
5027 if (track->isStopped()) {
5028 // Can't reset directly, as fast mixer is still polling this track
5029 // track->reset();
5030 // So instead mark this track as needing to be reset after push with ack
5031 resetMask |= 1 << i;
5032 }
5033 isActive = false;
5034 break;
5035 case TrackBase::IDLE:
5036 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005037 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005038 }
5039
5040 if (isActive) {
5041 // was it previously inactive?
5042 if (!(state->mTrackMask & (1 << j))) {
5043 ExtendedAudioBufferProvider *eabp = track;
5044 VolumeProvider *vp = track;
5045 fastTrack->mBufferProvider = eabp;
5046 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005047 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005048 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005049 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005050 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005051 fastTrack->mGeneration++;
5052 state->mTrackMask |= 1 << j;
5053 didModify = true;
5054 // no acknowledgement required for newly active tracks
5055 }
Kevin Rocard12381092018-04-11 09:19:59 -07005056 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005057 float volume;
5058 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5059 volume = 0.f;
5060 } else {
5061 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5062 }
5063
5064 handleVoipVolume_l(&volume);
5065
Eric Laurent81784c32012-11-19 14:55:58 -08005066 // cache the combined master volume and stream type volume for fast mixer; this
5067 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005068 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005069 proxy->framesReleased()).first;
5070 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005071 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005072 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5073 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5074 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005075
Kevin Rocard12381092018-04-11 09:19:59 -07005076 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005077 ++fastTracks;
5078 } else {
5079 // was it previously active?
5080 if (state->mTrackMask & (1 << j)) {
5081 fastTrack->mBufferProvider = NULL;
5082 fastTrack->mGeneration++;
5083 state->mTrackMask &= ~(1 << j);
5084 didModify = true;
5085 // If any fast tracks were removed, we must wait for acknowledgement
5086 // because we're about to decrement the last sp<> on those tracks.
5087 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5088 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005089 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5090 // AudioTrack may start (which may not be with a start() but with a write()
5091 // after underrun) and immediately paused or released. In that case the
5092 // FastTrack state hasn't had time to update.
5093 // TODO Remove the ALOGW when this theory is confirmed.
5094 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005095 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5096 j, track->mState, state->mTrackMask, recentUnderruns,
5097 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005098 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005099 }
5100 tracksToRemove->add(track);
5101 // Avoids a misleading display in dumpsys
5102 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5103 }
jiabin245cdd92018-12-07 17:55:15 -08005104 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5105 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5106 didModify = true;
5107 }
Eric Laurent81784c32012-11-19 14:55:58 -08005108 continue;
5109 }
5110
5111 { // local variable scope to avoid goto warning
5112
5113 audio_track_cblk_t* cblk = track->cblk();
5114
5115 // The first time a track is added we wait
5116 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005117 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005118
5119 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005120 // use the trackId as the AudioMixer name.
5121 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005122 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005123 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005124 track->mChannelMask,
5125 track->mFormat,
5126 track->mSessionId);
5127 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005128 ALOGW("%s(): AudioMixer cannot create track(%d)"
5129 " mask %#x, format %#x, sessionId %d",
5130 __func__, trackId,
5131 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005132 tracksToRemove->add(track);
5133 track->invalidate(); // consider it dead.
5134 continue;
5135 }
5136 }
5137
Eric Laurent81784c32012-11-19 14:55:58 -08005138 // make sure that we have enough frames to mix one full buffer.
5139 // enforce this condition only once to enable draining the buffer in case the client
5140 // app does not call stop() and relies on underrun to stop:
5141 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5142 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005143 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005144 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005145 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005146
5147 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005148 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005149 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5150 // add frames already consumed but not yet released by the resampler
5151 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005152 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005153
Eric Laurent81784c32012-11-19 14:55:58 -08005154 uint32_t minFrames = 1;
5155 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5156 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005157 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005158 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005159
5160 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005161 if (ATRACE_ENABLED()) {
5162 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005163 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005164 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005165 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005166 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005167 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005168 !track->isPaused() && !track->isTerminated())
5169 {
Andy Hungc0691382018-09-12 18:01:57 -07005170 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005171
5172 mixedTracks++;
5173
Andy Hung69aed5f2014-02-25 17:24:40 -08005174 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5175 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005176 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005177 if (track->mainBuffer() != mSinkBuffer &&
5178 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005179 if (mEffectBufferEnabled) {
5180 mEffectBufferValid = true; // Later can set directly.
5181 }
Eric Laurent81784c32012-11-19 14:55:58 -08005182 chain = getEffectChain_l(track->sessionId());
5183 // Delegate volume control to effect in track effect chain if needed
5184 if (chain != 0) {
5185 tracksWithEffect++;
5186 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005187 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005188 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005189 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005190 }
5191 }
5192
5193
5194 int param = AudioMixer::VOLUME;
5195 if (track->mFillingUpStatus == Track::FS_FILLED) {
5196 // no ramp for the first volume setting
5197 track->mFillingUpStatus = Track::FS_ACTIVE;
5198 if (track->mState == TrackBase::RESUMING) {
5199 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005200 // If a new track is paused immediately after start, do not ramp on resume.
5201 if (cblk->mServer != 0) {
5202 param = AudioMixer::RAMP_VOLUME;
5203 }
Eric Laurent81784c32012-11-19 14:55:58 -08005204 }
Andy Hungc0691382018-09-12 18:01:57 -07005205 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005206 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005207 // FIXME should not make a decision based on mServer
5208 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005209 // If the track is stopped before the first frame was mixed,
5210 // do not apply ramp
5211 param = AudioMixer::RAMP_VOLUME;
5212 }
5213
5214 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005215 uint32_t vl, vr; // in U8.24 integer format
5216 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005217 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005218 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005219 // Always fetch volumeshaper volume to ensure state is updated.
5220 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5221 const float vh = track->getVolumeHandler()->getVolume(
5222 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005223
Eric Laurenteab90452019-06-24 15:17:46 -07005224 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5225 v = 0;
5226 }
5227
5228 handleVoipVolume_l(&v);
5229
5230 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005231 vl = vr = 0;
5232 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005233 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005234 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005235 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005236 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5237 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005238 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005239 if (vlf > GAIN_FLOAT_UNITY) {
5240 ALOGV("Track left volume out of range: %.3g", vlf);
5241 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005242 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005243 if (vrf > GAIN_FLOAT_UNITY) {
5244 ALOGV("Track right volume out of range: %.3g", vrf);
5245 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005246 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005247 // now apply the master volume and stream type volume and shaper volume
5248 vlf *= v * vh;
5249 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005250 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005251 // then derive vl and vr as U8.24 versions for the effect chain
5252 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5253 vl = (uint32_t) (scaleto8_24 * vlf);
5254 vr = (uint32_t) (scaleto8_24 * vrf);
5255 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005256 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005257 // send level comes from shared memory and so may be corrupt
5258 if (sendLevel > MAX_GAIN_INT) {
5259 ALOGV("Track send level out of range: %04X", sendLevel);
5260 sendLevel = MAX_GAIN_INT;
5261 }
Andy Hung6be49402014-05-30 10:42:03 -07005262 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5263 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005264 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005265
Kevin Rocard12381092018-04-11 09:19:59 -07005266 track->setFinalVolume((vrf + vlf) / 2.f);
5267
Eric Laurent81784c32012-11-19 14:55:58 -08005268 // Delegate volume control to effect in track effect chain if needed
5269 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5270 // Do not ramp volume if volume is controlled by effect
5271 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005272 // Update remaining floating point volume levels
5273 vlf = (float)vl / (1 << 24);
5274 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005275 track->mHasVolumeController = true;
5276 } else {
5277 // force no volume ramp when volume controller was just disabled or removed
5278 // from effect chain to avoid volume spike
5279 if (track->mHasVolumeController) {
5280 param = AudioMixer::VOLUME;
5281 }
5282 track->mHasVolumeController = false;
5283 }
5284
Eric Laurent81784c32012-11-19 14:55:58 -08005285 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005286 mAudioMixer->setBufferProvider(trackId, track);
5287 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005288
Andy Hungc0691382018-09-12 18:01:57 -07005289 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5290 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5291 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005292 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005293 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005294 AudioMixer::TRACK,
5295 AudioMixer::FORMAT, (void *)track->format());
5296 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005297 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005298 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005299 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005300 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005301 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005302 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005303 AudioMixer::MIXER_CHANNEL_MASK,
5304 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005305 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005306 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005307 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005308 if (reqSampleRate == 0) {
5309 reqSampleRate = mSampleRate;
5310 } else if (reqSampleRate > maxSampleRate) {
5311 reqSampleRate = maxSampleRate;
5312 }
Eric Laurent81784c32012-11-19 14:55:58 -08005313 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005314 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005315 AudioMixer::RESAMPLE,
5316 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005317 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005318
Andy Hung333ab962019-05-28 20:23:35 -07005319 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005320 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005321 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005322 AudioMixer::TIMESTRETCH,
5323 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005324 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005325
Andy Hung69aed5f2014-02-25 17:24:40 -08005326 /*
5327 * Select the appropriate output buffer for the track.
5328 *
Andy Hung98ef9782014-03-04 14:46:50 -08005329 * Tracks with effects go into their own effects chain buffer
5330 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005331 *
5332 * Other tracks can use mMixerBuffer for higher precision
5333 * channel accumulation. If this buffer is enabled
5334 * (mMixerBufferEnabled true), then selected tracks will accumulate
5335 * into it.
5336 *
5337 */
5338 if (mMixerBufferEnabled
5339 && (track->mainBuffer() == mSinkBuffer
5340 || track->mainBuffer() == mMixerBuffer)) {
5341 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005342 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005343 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005344 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005345 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005346 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005347 AudioMixer::TRACK,
5348 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5349 // TODO: override track->mainBuffer()?
5350 mMixerBufferValid = true;
5351 } else {
5352 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005353 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005354 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005355 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005356 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005357 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005358 AudioMixer::TRACK,
5359 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5360 }
Eric Laurent81784c32012-11-19 14:55:58 -08005361 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005362 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005363 AudioMixer::TRACK,
5364 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005365 mAudioMixer->setParameter(
5366 trackId,
5367 AudioMixer::TRACK,
5368 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005369 mAudioMixer->setParameter(
5370 trackId,
5371 AudioMixer::TRACK,
5372 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005373
5374 // reset retry count
5375 track->mRetryCount = kMaxTrackRetries;
5376
5377 // If one track is ready, set the mixer ready if:
5378 // - the mixer was not ready during previous round OR
5379 // - no other track is not ready
5380 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5381 mixerStatus != MIXER_TRACKS_ENABLED) {
5382 mixerStatus = MIXER_TRACKS_READY;
5383 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005384
5385 // Enable the next few lines to instrument a test for underrun log handling.
5386 // TODO: Remove when we have a better way of testing the underrun log.
5387#if 0
5388 static int i;
5389 if ((++i & 0xf) == 0) {
5390 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5391 }
5392#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005393 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005394 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005395 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005396 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5397 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005398 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005399 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005400 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005401
Eric Laurent81784c32012-11-19 14:55:58 -08005402 // clear effect chain input buffer if an active track underruns to avoid sending
5403 // previous audio buffer again to effects
5404 chain = getEffectChain_l(track->sessionId());
5405 if (chain != 0) {
5406 chain->clearInputBuffer();
5407 }
5408
Andy Hungc0691382018-09-12 18:01:57 -07005409 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005410 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5411 track->isStopped() || track->isPaused()) {
5412 // We have consumed all the buffers of this track.
5413 // Remove it from the list of active tracks.
5414 // TODO: use actual buffer filling status instead of latency when available from
5415 // audio HAL
5416 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005417 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005418 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5419 if (track->isStopped()) {
5420 track->reset();
5421 }
5422 tracksToRemove->add(track);
5423 }
5424 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005425 // No buffers for this track. Give it a few chances to
5426 // fill a buffer, then remove it from active list.
5427 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005428 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5429 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005430 tracksToRemove->add(track);
5431 // indicate to client process that the track was disabled because of underrun;
5432 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005433 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005434 // If one track is not ready, mark the mixer also not ready if:
5435 // - the mixer was ready during previous round OR
5436 // - no other track is ready
5437 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5438 mixerStatus != MIXER_TRACKS_READY) {
5439 mixerStatus = MIXER_TRACKS_ENABLED;
5440 }
5441 }
Andy Hungc0691382018-09-12 18:01:57 -07005442 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005443 }
5444
5445 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005446
5447 }
5448
jiabin245cdd92018-12-07 17:55:15 -08005449 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5450 // When there is no fast track playing haptic and FastMixer exists,
5451 // enabling the first FastTrack, which provides mixed data from normal
5452 // tracks, to play haptic data.
5453 FastTrack *fastTrack = &state->mFastTracks[0];
5454 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5455 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5456 didModify = true;
5457 }
5458 }
5459
Eric Laurent81784c32012-11-19 14:55:58 -08005460 // Push the new FastMixer state if necessary
5461 bool pauseAudioWatchdog = false;
5462 if (didModify) {
5463 state->mFastTracksGen++;
5464 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5465 if (kUseFastMixer == FastMixer_Dynamic &&
5466 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5467 state->mCommand = FastMixerState::COLD_IDLE;
5468 state->mColdFutexAddr = &mFastMixerFutex;
5469 state->mColdGen++;
5470 mFastMixerFutex = 0;
5471 if (kUseFastMixer == FastMixer_Dynamic) {
5472 mNormalSink = mOutputSink;
5473 }
5474 // If we go into cold idle, need to wait for acknowledgement
5475 // so that fast mixer stops doing I/O.
5476 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5477 pauseAudioWatchdog = true;
5478 }
Eric Laurent81784c32012-11-19 14:55:58 -08005479 }
5480 if (sq != NULL) {
5481 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005482 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5483 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5484 // when bringing the output sink into standby.)
5485 //
5486 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5487 //
5488 // This occurs with BT suspend when we idle the FastMixer with
5489 // active tracks, which may be added or removed.
5490 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005491 }
5492#ifdef AUDIO_WATCHDOG
5493 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5494 mAudioWatchdog->pause();
5495 }
5496#endif
5497
5498 // Now perform the deferred reset on fast tracks that have stopped
5499 while (resetMask != 0) {
5500 size_t i = __builtin_ctz(resetMask);
5501 ALOG_ASSERT(i < count);
5502 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005503 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005504 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5505 track->reset();
5506 }
5507
Andy Hung80d03d22018-04-10 10:32:11 -07005508 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5509 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5510 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5511 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5512 // See also the implementation of destroyTrack_l().
5513 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005514 const int trackId = track->id();
5515 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5516 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005517 }
5518 }
5519
Eric Laurent81784c32012-11-19 14:55:58 -08005520 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005521 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005522
Eric Laurent97d547d2014-09-02 14:45:53 -07005523 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5524 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005525 }
5526
5527 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005528 // as long as there are effects we should clear the effects buffer, to avoid
5529 // passing a non-clean buffer to the effect chain
5530 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005531 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005532 // sink or mix buffer must be cleared if all tracks are connected to an
5533 // effect chain as in this case the mixer will not write to the sink or mix buffer
5534 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005535 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5536 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005537 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005538 if (mMixerBufferValid) {
5539 memset(mMixerBuffer, 0, mMixerBufferSize);
5540 // TODO: In testing, mSinkBuffer below need not be cleared because
5541 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5542 // after mixing.
5543 //
5544 // To enforce this guarantee:
5545 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5546 // (mixedTracks == 0 && fastTracks > 0))
5547 // must imply MIXER_TRACKS_READY.
5548 // Later, we may clear buffers regardless, and skip much of this logic.
5549 }
Andy Hung98ef9782014-03-04 14:46:50 -08005550 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005551 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005552 }
5553
5554 // if any fast tracks, then status is ready
5555 mMixerStatusIgnoringFastTracks = mixerStatus;
5556 if (fastTracks > 0) {
5557 mixerStatus = MIXER_TRACKS_READY;
5558 }
5559 return mixerStatus;
5560}
5561
Eric Laurentad7dd962016-09-22 12:38:37 -07005562// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005563uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005564{
5565 uint32_t trackCount = 0;
5566 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005567 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005568 trackCount++;
5569 }
5570 }
5571 return trackCount;
5572}
5573
Andy Hung1bc088a2018-02-09 15:57:31 -08005574// isTrackAllowed_l() must be called with ThreadBase::mLock held
5575bool AudioFlinger::MixerThread::isTrackAllowed_l(
5576 audio_channel_mask_t channelMask, audio_format_t format,
5577 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005578{
Andy Hung1bc088a2018-02-09 15:57:31 -08005579 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5580 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005581 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005582 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005583 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005584 ALOGW("%s: invalid format: %#x", __func__, format);
5585 return false;
5586 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005587 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005588 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5589 return false;
5590 }
5591 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005592}
5593
Eric Laurent10351942014-05-08 18:49:52 -07005594// checkForNewParameter_l() must be called with ThreadBase::mLock held
5595bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5596 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005597{
Eric Laurent81784c32012-11-19 14:55:58 -08005598 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005599 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005600
Eric Laurent10351942014-05-08 18:49:52 -07005601 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005602
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005603 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005604
Eric Laurent10351942014-05-08 18:49:52 -07005605 AudioParameter param = AudioParameter(keyValuePair);
5606 int value;
5607 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5608 reconfig = true;
5609 }
5610 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005611 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005612 status = BAD_VALUE;
5613 } else {
5614 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005615 reconfig = true;
5616 }
Eric Laurent10351942014-05-08 18:49:52 -07005617 }
5618 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005619 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005620 status = BAD_VALUE;
5621 } else {
5622 // no need to save value, since it's constant
5623 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005624 }
Eric Laurent10351942014-05-08 18:49:52 -07005625 }
5626 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5627 // do not accept frame count changes if tracks are open as the track buffer
5628 // size depends on frame count and correct behavior would not be guaranteed
5629 // if frame count is changed after track creation
5630 if (!mTracks.isEmpty()) {
5631 status = INVALID_OPERATION;
5632 } else {
5633 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005634 }
Eric Laurent10351942014-05-08 18:49:52 -07005635 }
5636 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005637 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005638 }
Eric Laurent81784c32012-11-19 14:55:58 -08005639
Eric Laurent10351942014-05-08 18:49:52 -07005640 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005641 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005642 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005643 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005644 if (!mStandby) {
5645 mThreadMetrics.logEndInterval();
5646 mStandby = true;
5647 }
Eric Laurent10351942014-05-08 18:49:52 -07005648 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005649 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005650 }
Eric Laurent10351942014-05-08 18:49:52 -07005651 if (status == NO_ERROR && reconfig) {
5652 readOutputParameters_l();
5653 delete mAudioMixer;
5654 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005655 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005656 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005657 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005658 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005659 track->mChannelMask,
5660 track->mFormat,
5661 track->mSessionId);
5662 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005663 "%s(): AudioMixer cannot create track(%d)"
5664 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005665 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005666 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005667 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005668 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005669 }
Eric Laurent81784c32012-11-19 14:55:58 -08005670 }
5671
Eric Laurent42537be2016-01-08 17:16:42 -08005672 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005673}
5674
5675
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005676void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005677{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005678 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005679 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005680 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005681 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005682 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5683 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5684 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005685 if (hasFastMixer()) {
5686 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5687
5688 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5689 // while we are dumping it. It may be inconsistent, but it won't mutate!
5690 // This is a large object so we place it on the heap.
5691 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005692 const std::unique_ptr<FastMixerDumpState> copy =
5693 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005694 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005695
5696#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005697 // Similar for state queue
5698 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5699 observerCopy.dump(fd);
5700 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5701 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005702#endif
5703
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005704#ifdef AUDIO_WATCHDOG
5705 if (mAudioWatchdog != 0) {
5706 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5707 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5708 wdCopy.dump(fd);
5709 }
5710#endif
5711
5712 } else {
5713 dprintf(fd, " No FastMixer\n");
5714 }
Eric Laurent81784c32012-11-19 14:55:58 -08005715}
5716
5717uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5718{
5719 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5720}
5721
5722uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5723{
5724 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5725}
5726
5727void AudioFlinger::MixerThread::cacheParameters_l()
5728{
5729 PlaybackThread::cacheParameters_l();
5730
5731 // FIXME: Relaxed timing because of a certain device that can't meet latency
5732 // Should be reduced to 2x after the vendor fixes the driver issue
5733 // increase threshold again due to low power audio mode. The way this warning
5734 // threshold is calculated and its usefulness should be reconsidered anyway.
5735 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5736}
5737
5738// ----------------------------------------------------------------------------
5739
5740AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005741 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5742 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005743{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005744 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005745}
5746
Eric Laurent81784c32012-11-19 14:55:58 -08005747AudioFlinger::DirectOutputThread::~DirectOutputThread()
5748{
5749}
5750
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005751void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005752{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005753 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005754 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5755 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5756}
5757
5758void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5759{
5760 Mutex::Autolock _l(mLock);
5761 if (mMasterBalance != balance) {
5762 mMasterBalance.store(balance);
5763 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5764 broadcast_l();
5765 }
5766}
5767
Eric Laurent5850c4c2016-11-10 13:04:31 -08005768void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005769{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005770 float left, right;
5771
Andy Hung333ab962019-05-28 20:23:35 -07005772 // Ensure volumeshaper state always advances even when muted.
5773 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5774 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5775 proxy->framesReleased());
5776 mVolumeShaperActive = shaperActive;
5777
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005778 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005779 left = right = 0;
5780 } else {
5781 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005782 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005783
Glenn Kastenc56f3422014-03-21 17:53:17 -07005784 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5785 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5786 if (left > GAIN_FLOAT_UNITY) {
5787 left = GAIN_FLOAT_UNITY;
5788 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005789 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005790 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5791 if (right > GAIN_FLOAT_UNITY) {
5792 right = GAIN_FLOAT_UNITY;
5793 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005794 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005795 }
5796
5797 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005798 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005799 if (left != mLeftVolFloat || right != mRightVolFloat) {
5800 mLeftVolFloat = left;
5801 mRightVolFloat = right;
5802
Eric Laurentbfb1b832013-01-07 09:53:42 -08005803 // Delegate volume control to effect in track effect chain if needed
5804 // only one effect chain can be present on DirectOutputThread, so if
5805 // there is one, the track is connected to it
5806 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005807 // if effect chain exists, volume is handled by it.
5808 // Convert volumes from float to 8.24
5809 uint32_t vl = (uint32_t)(left * (1 << 24));
5810 uint32_t vr = (uint32_t)(right * (1 << 24));
5811 // Direct/Offload effect chains set output volume in setVolume_l().
5812 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5813 } else {
5814 // otherwise we directly set the volume.
5815 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005816 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005817 }
5818 }
5819}
5820
Phil Burk43b4dcc2015-06-09 16:53:44 -07005821void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5822{
5823 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005824 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005825
Eric Laurent0f0631e2015-07-06 18:01:25 -07005826 if (previousTrack != 0 && latestTrack != 0) {
5827 if (mType == DIRECT) {
5828 if (previousTrack.get() != latestTrack.get()) {
5829 mFlushPending = true;
5830 }
5831 } else /* mType == OFFLOAD */ {
5832 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5833 mFlushPending = true;
5834 }
5835 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005836 } else if (previousTrack == 0) {
5837 // there could be an old track added back during track transition for direct
5838 // output, so always issues flush to flush data of the previous track if it
5839 // was already destroyed with HAL paused, then flush can resume the playback
5840 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005841 }
5842 PlaybackThread::onAddNewTrack_l();
5843}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005844
Eric Laurent81784c32012-11-19 14:55:58 -08005845AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5846 Vector< sp<Track> > *tracksToRemove
5847)
5848{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005849 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005850 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005851 bool doHwPause = false;
5852 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005853
5854 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005855 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005856 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005857 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005858 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005859 continue;
5860 }
5861
Eric Laurent5850c4c2016-11-10 13:04:31 -08005862 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005863#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005864 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005865#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005866 // Only consider last track started for volume and mixer state control.
5867 // In theory an older track could underrun and restart after the new one starts
5868 // but as we only care about the transition phase between two tracks on a
5869 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005870 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005871 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005872
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005873 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005874 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005875 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005876 doHwPause = true;
5877 mHwPaused = true;
5878 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005879 } else if (track->isFlushPending()) {
5880 track->flushAck();
5881 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005882 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005883 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005884 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005885 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005886 if (last) {
5887 mLeftVolFloat = mRightVolFloat = -1.0;
5888 if (mHwPaused) {
5889 doHwResume = true;
5890 mHwPaused = false;
5891 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005892 }
5893 }
5894
Eric Laurent81784c32012-11-19 14:55:58 -08005895 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005896 // for all its buffers to be filled before processing it.
5897 // Allow draining the buffer in case the client
5898 // app does not call stop() and relies on underrun to stop:
5899 // hence the test on (track->mRetryCount > 1).
5900 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005901 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005902 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005903 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005904 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005905 minFrames = mNormalFrameCount;
5906 } else {
5907 minFrames = 1;
5908 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005909
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005910 const size_t framesReady = track->framesReady();
5911 const int trackId = track->id();
5912 if (ATRACE_ENABLED()) {
5913 std::string traceName("nRdy");
5914 traceName += std::to_string(trackId);
5915 ATRACE_INT(traceName.c_str(), framesReady);
5916 }
5917 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005918 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005919 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005920 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005921
5922 if (track->mFillingUpStatus == Track::FS_FILLED) {
5923 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005924 if (last) {
5925 // make sure processVolume_l() will apply new volume even if 0
5926 mLeftVolFloat = mRightVolFloat = -1.0;
5927 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005928 if (!mHwSupportsPause) {
5929 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005930 }
5931 }
5932
5933 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005934 processVolume_l(track, last);
5935 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005936 sp<Track> previousTrack = mPreviousTrack.promote();
5937 if (previousTrack != 0) {
5938 if (track != previousTrack.get()) {
5939 // Flush any data still being written from last track
5940 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005941 // Invalidate previous track to force a seek when resuming.
5942 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005943 }
5944 }
5945 mPreviousTrack = track;
5946
Eric Laurentd595b7c2013-04-03 17:27:56 -07005947 // reset retry count
5948 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005949 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005950 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005951 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005952 doHwResume = true;
5953 mHwPaused = false;
5954 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005955 }
Eric Laurent81784c32012-11-19 14:55:58 -08005956 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005957 // clear effect chain input buffer if the last active track started underruns
5958 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005959 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005960 mEffectChains[0]->clearInputBuffer();
5961 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005962 if (track->isStopping_1()) {
5963 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005964 if (last && mHwPaused) {
5965 doHwResume = true;
5966 mHwPaused = false;
5967 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005968 }
5969 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5970 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005971 // We have consumed all the buffers of this track.
5972 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005973 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005974 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005975 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5976 } else {
5977 audioHALFrames = 0;
5978 }
5979
Andy Hung818e7a32016-02-16 18:08:07 -08005980 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005981 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005982 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08005983 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005984 if (track->isStopping_2()) {
5985 track->mState = TrackBase::STOPPED;
5986 }
Eric Laurent81784c32012-11-19 14:55:58 -08005987 if (track->isStopped()) {
5988 track->reset();
5989 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005990 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005991 }
5992 } else {
5993 // No buffers for this track. Give it a few chances to
5994 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005995 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005996 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005997 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005998 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005999 // indicate to client process that the track was disabled because of underrun;
6000 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006001 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006002 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07006003 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6004 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006005 framesReady, minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08006006 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07006007 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006008 doHwPause = true;
6009 mHwPaused = true;
6010 }
Eric Laurent81784c32012-11-19 14:55:58 -08006011 }
6012 }
6013 }
6014 }
6015
Eric Laurentd1f69b02014-12-15 14:33:13 -08006016 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006017 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006018 for (size_t i = 0; i < mTracks.size(); i++) {
6019 if (mTracks[i]->isFlushPending()) {
6020 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006021 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006022 }
6023 }
6024 }
6025
6026 // make sure the pause/flush/resume sequence is executed in the right order.
6027 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6028 // before flush and then resume HW. This can happen in case of pause/flush/resume
6029 // if resume is received before pause is executed.
6030 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006031 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006032 status_t result = mOutput->stream->pause();
6033 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006034 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006035 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006036 flushHw_l();
6037 }
6038 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006039 status_t result = mOutput->stream->resume();
6040 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006041 }
Eric Laurent81784c32012-11-19 14:55:58 -08006042 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006043 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006044
6045 return mixerStatus;
6046}
6047
6048void AudioFlinger::DirectOutputThread::threadLoop_mix()
6049{
Eric Laurent81784c32012-11-19 14:55:58 -08006050 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006051 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006052 // output audio to hardware
6053 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006054 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006055 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006056 status_t status = mActiveTrack->getNextBuffer(&buffer);
6057 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006058 // no need to pad with 0 for compressed audio
6059 if (audio_has_proportional_frames(mFormat)) {
6060 memset(curBuf, 0, frameCount * mFrameSize);
6061 }
Eric Laurent81784c32012-11-19 14:55:58 -08006062 break;
6063 }
6064 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6065 frameCount -= buffer.frameCount;
6066 curBuf += buffer.frameCount * mFrameSize;
6067 mActiveTrack->releaseBuffer(&buffer);
6068 }
Andy Hung2098f272014-02-27 14:00:06 -08006069 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006070 mSleepTimeUs = 0;
6071 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006072 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006073}
6074
6075void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6076{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006077 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006078 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006079 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006080 return;
6081 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006082 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006083 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07006084 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006085 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006086 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006087 }
Phil Burkfdb3c072016-02-09 10:47:02 -08006088 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08006089 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006090 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006091 }
6092}
6093
Eric Laurentd1f69b02014-12-15 14:33:13 -08006094void AudioFlinger::DirectOutputThread::threadLoop_exit()
6095{
6096 {
6097 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006098 for (size_t i = 0; i < mTracks.size(); i++) {
6099 if (mTracks[i]->isFlushPending()) {
6100 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006101 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006102 }
6103 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006104 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006105 flushHw_l();
6106 }
6107 }
6108 PlaybackThread::threadLoop_exit();
6109}
6110
6111// must be called with thread mutex locked
6112bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6113{
6114 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006115 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006116
6117 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6118 // after a timeout and we will enter standby then.
6119 if (mTracks.size() > 0) {
6120 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006121 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6122 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006123 }
6124
Eric Laurent5cff4032015-05-26 13:49:58 -07006125 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006126}
6127
Eric Laurent10351942014-05-08 18:49:52 -07006128// checkForNewParameter_l() must be called with ThreadBase::mLock held
6129bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6130 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006131{
6132 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08006133 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006134
Eric Laurent10351942014-05-08 18:49:52 -07006135 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006136
Eric Laurent10351942014-05-08 18:49:52 -07006137 AudioParameter param = AudioParameter(keyValuePair);
6138 int value;
6139 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006140 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006141 }
Eric Laurent10351942014-05-08 18:49:52 -07006142 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6143 // do not accept frame count changes if tracks are open as the track buffer
6144 // size depends on frame count and correct behavior would not be garantied
6145 // if frame count is changed after track creation
6146 if (!mTracks.isEmpty()) {
6147 status = INVALID_OPERATION;
6148 } else {
6149 reconfig = true;
6150 }
6151 }
6152 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006153 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006154 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006155 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006156 if (!mStandby) {
6157 mThreadMetrics.logEndInterval();
6158 mStandby = true;
6159 }
Eric Laurent10351942014-05-08 18:49:52 -07006160 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006161 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006162 }
6163 if (status == NO_ERROR && reconfig) {
6164 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006165 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006166 }
6167 }
6168
Eric Laurent42537be2016-01-08 17:16:42 -08006169 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08006170}
6171
6172uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6173{
6174 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006175 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006176 time = PlaybackThread::activeSleepTimeUs();
6177 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006178 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006179 }
6180 return time;
6181}
6182
6183uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6184{
6185 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006186 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006187 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6188 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006189 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006190 }
6191 return time;
6192}
6193
6194uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6195{
6196 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006197 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006198 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6199 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006200 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006201 }
6202 return time;
6203}
6204
6205void AudioFlinger::DirectOutputThread::cacheParameters_l()
6206{
6207 PlaybackThread::cacheParameters_l();
6208
6209 // use shorter standby delay as on normal output to release
6210 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006211 // no delay on outputs with HW A/V sync
6212 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006213 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006214 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006215 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006216 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006217 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006218 }
Eric Laurent81784c32012-11-19 14:55:58 -08006219}
6220
Eric Laurente659ef42014-09-29 13:06:46 -07006221void AudioFlinger::DirectOutputThread::flushHw_l()
6222{
Phil Burk062e67a2015-02-11 13:40:50 -08006223 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006224 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006225 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07006226 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Sampath Shetty999f0e82020-01-15 10:19:06 +11006227 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006228}
6229
Andy Hung10cbff12017-02-21 17:30:14 -08006230int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6231 // If a VolumeShaper is active, we must wake up periodically to update volume.
6232 const int64_t NS_PER_MS = 1000000;
6233 return mVolumeShaperActive ?
6234 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6235}
6236
Eric Laurent81784c32012-11-19 14:55:58 -08006237// ----------------------------------------------------------------------------
6238
Eric Laurentbfb1b832013-01-07 09:53:42 -08006239AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006240 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006241 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006242 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006243 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006244 mDrainSequence(0),
6245 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006246{
6247}
6248
6249AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6250{
6251}
6252
6253void AudioFlinger::AsyncCallbackThread::onFirstRef()
6254{
6255 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6256}
6257
6258bool AudioFlinger::AsyncCallbackThread::threadLoop()
6259{
6260 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006261 uint32_t writeAckSequence;
6262 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006263 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006264
6265 {
6266 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006267 while (!((mWriteAckSequence & 1) ||
6268 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006269 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006270 exitPending())) {
6271 mWaitWorkCV.wait(mLock);
6272 }
6273
Eric Laurentbfb1b832013-01-07 09:53:42 -08006274 if (exitPending()) {
6275 break;
6276 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006277 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6278 mWriteAckSequence, mDrainSequence);
6279 writeAckSequence = mWriteAckSequence;
6280 mWriteAckSequence &= ~1;
6281 drainSequence = mDrainSequence;
6282 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006283 asyncError = mAsyncError;
6284 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006285 }
6286 {
Eric Laurent4de95592013-09-26 15:28:21 -07006287 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6288 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006289 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006290 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006291 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006292 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006293 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006294 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006295 if (asyncError) {
6296 playbackThread->onAsyncError();
6297 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006298 }
6299 }
6300 }
6301 return false;
6302}
6303
6304void AudioFlinger::AsyncCallbackThread::exit()
6305{
6306 ALOGV("AsyncCallbackThread::exit");
6307 Mutex::Autolock _l(mLock);
6308 requestExit();
6309 mWaitWorkCV.broadcast();
6310}
6311
Eric Laurent3b4529e2013-09-05 18:09:19 -07006312void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006313{
6314 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006315 // bit 0 is cleared
6316 mWriteAckSequence = sequence << 1;
6317}
6318
6319void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6320{
6321 Mutex::Autolock _l(mLock);
6322 // ignore unexpected callbacks
6323 if (mWriteAckSequence & 2) {
6324 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006325 mWaitWorkCV.signal();
6326 }
6327}
6328
Eric Laurent3b4529e2013-09-05 18:09:19 -07006329void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006330{
6331 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006332 // bit 0 is cleared
6333 mDrainSequence = sequence << 1;
6334}
6335
6336void AudioFlinger::AsyncCallbackThread::resetDraining()
6337{
6338 Mutex::Autolock _l(mLock);
6339 // ignore unexpected callbacks
6340 if (mDrainSequence & 2) {
6341 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006342 mWaitWorkCV.signal();
6343 }
6344}
6345
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006346void AudioFlinger::AsyncCallbackThread::setAsyncError()
6347{
6348 Mutex::Autolock _l(mLock);
6349 mAsyncError = true;
6350 mWaitWorkCV.signal();
6351}
6352
Eric Laurentbfb1b832013-01-07 09:53:42 -08006353
6354// ----------------------------------------------------------------------------
6355AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006356 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6357 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006358 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6359 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006360{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006361 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006362 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006363 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006364}
6365
Eric Laurentbfb1b832013-01-07 09:53:42 -08006366void AudioFlinger::OffloadThread::threadLoop_exit()
6367{
6368 if (mFlushPending || mHwPaused) {
6369 // If a flush is pending or track was paused, just discard buffered data
6370 flushHw_l();
6371 } else {
6372 mMixerStatus = MIXER_DRAIN_ALL;
6373 threadLoop_drain();
6374 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006375 if (mUseAsyncWrite) {
6376 ALOG_ASSERT(mCallbackThread != 0);
6377 mCallbackThread->exit();
6378 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006379 PlaybackThread::threadLoop_exit();
6380}
6381
6382AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6383 Vector< sp<Track> > *tracksToRemove
6384)
6385{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006386 size_t count = mActiveTracks.size();
6387
6388 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006389 bool doHwPause = false;
6390 bool doHwResume = false;
6391
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006392 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006393
Eric Laurentbfb1b832013-01-07 09:53:42 -08006394 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006395 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006396 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006397#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006398 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006399#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006400 // Only consider last track started for volume and mixer state control.
6401 // In theory an older track could underrun and restart after the new one starts
6402 // but as we only care about the transition phase between two tracks on a
6403 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006404 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006405 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006406
Haynes Mathew George7844f672014-01-15 12:32:55 -08006407 if (track->isInvalid()) {
6408 ALOGW("An invalidated track shouldn't be in active list");
6409 tracksToRemove->add(track);
6410 continue;
6411 }
6412
6413 if (track->mState == TrackBase::IDLE) {
6414 ALOGW("An idle track shouldn't be in active list");
6415 continue;
6416 }
6417
Eric Laurentbfb1b832013-01-07 09:53:42 -08006418 if (track->isPausing()) {
6419 track->setPaused();
6420 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006421 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006422 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006423 mHwPaused = true;
6424 }
6425 // If we were part way through writing the mixbuffer to
6426 // the HAL we must save this until we resume
6427 // BUG - this will be wrong if a different track is made active,
6428 // in that case we want to discard the pending data in the
6429 // mixbuffer and tell the client to present it again when the
6430 // track is resumed
6431 mPausedWriteLength = mCurrentWriteLength;
6432 mPausedBytesRemaining = mBytesRemaining;
6433 mBytesRemaining = 0; // stop writing
6434 }
6435 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006436 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006437 if (track->isStopping_1()) {
6438 track->mRetryCount = kMaxTrackStopRetriesOffload;
6439 } else {
6440 track->mRetryCount = kMaxTrackRetriesOffload;
6441 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006442 track->flushAck();
6443 if (last) {
6444 mFlushPending = true;
6445 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006446 } else if (track->isResumePending()){
6447 track->resumeAck();
6448 if (last) {
6449 if (mPausedBytesRemaining) {
6450 // Need to continue write that was interrupted
6451 mCurrentWriteLength = mPausedWriteLength;
6452 mBytesRemaining = mPausedBytesRemaining;
6453 mPausedBytesRemaining = 0;
6454 }
6455 if (mHwPaused) {
6456 doHwResume = true;
6457 mHwPaused = false;
6458 // threadLoop_mix() will handle the case that we need to
6459 // resume an interrupted write
6460 }
6461 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006462 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006463
Eric Laurent3df841a2016-07-15 15:15:40 -07006464 mLeftVolFloat = mRightVolFloat = -1.0;
6465
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006466 // Do not handle new data in this iteration even if track->framesReady()
6467 mixerStatus = MIXER_TRACKS_ENABLED;
6468 }
6469 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006470 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006471 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006472 if (track->mFillingUpStatus == Track::FS_FILLED) {
6473 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006474 if (last) {
6475 // make sure processVolume_l() will apply new volume even if 0
6476 mLeftVolFloat = mRightVolFloat = -1.0;
6477 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006478 }
6479
6480 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006481 sp<Track> previousTrack = mPreviousTrack.promote();
6482 if (previousTrack != 0) {
6483 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006484 // Flush any data still being written from last track
6485 mBytesRemaining = 0;
6486 if (mPausedBytesRemaining) {
6487 // Last track was paused so we also need to flush saved
6488 // mixbuffer state and invalidate track so that it will
6489 // re-submit that unwritten data when it is next resumed
6490 mPausedBytesRemaining = 0;
6491 // Invalidate is a bit drastic - would be more efficient
6492 // to have a flag to tell client that some of the
6493 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006494 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006495 }
6496 // flush data already sent to the DSP if changing audio session as audio
6497 // comes from a different source. Also invalidate previous track to force a
6498 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006499 if (previousTrack->sessionId() != track->sessionId()) {
6500 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006501 }
6502 }
6503 }
6504 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006505 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006506 if (track->isStopping_1()) {
6507 track->mRetryCount = kMaxTrackStopRetriesOffload;
6508 } else {
6509 track->mRetryCount = kMaxTrackRetriesOffload;
6510 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006511 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006512 mixerStatus = MIXER_TRACKS_READY;
6513 }
6514 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006515 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006516 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006517 if (--(track->mRetryCount) <= 0) {
6518 // Hardware buffer can hold a large amount of audio so we must
6519 // wait for all current track's data to drain before we say
6520 // that the track is stopped.
6521 if (mBytesRemaining == 0) {
6522 // Only start draining when all data in mixbuffer
6523 // has been written
6524 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6525 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6526 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6527 if (last && !mStandby) {
6528 // do not modify drain sequence if we are already draining. This happens
6529 // when resuming from pause after drain.
6530 if ((mDrainSequence & 1) == 0) {
6531 mSleepTimeUs = 0;
6532 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6533 mixerStatus = MIXER_DRAIN_TRACK;
6534 mDrainSequence += 2;
6535 }
6536 if (mHwPaused) {
6537 // It is possible to move from PAUSED to STOPPING_1 without
6538 // a resume so we must ensure hardware is running
6539 doHwResume = true;
6540 mHwPaused = false;
6541 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006542 }
6543 }
Eric Laurente93cc032016-05-05 10:15:10 -07006544 } else if (last) {
6545 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6546 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006547 }
6548 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006549 // Drain has completed or we are in standby, signal presentation complete
6550 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006551 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006552 uint32_t latency = 0;
6553 status_t result = mOutput->stream->getLatency(&latency);
6554 ALOGE_IF(result != OK,
6555 "Error when retrieving output stream latency: %d", result);
6556 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006557 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006558 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006559 track->presentationComplete(framesWritten, audioHALFrames);
6560 track->reset();
6561 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006562 // DIRECT and OFFLOADED stop resets frame counts.
6563 if (!mUseAsyncWrite) {
6564 // If we don't get explicit drain notification we must
6565 // register discontinuity regardless of whether this is
6566 // the previous (!last) or the upcoming (last) track
6567 // to avoid skipping the discontinuity.
6568 mTimestampVerifier.discontinuity();
6569 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006570 }
6571 } else {
6572 // No buffers for this track. Give it a few chances to
6573 // fill a buffer, then remove it from active list.
6574 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006575 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006576 uint64_t position = 0;
6577 struct timespec unused;
6578 // The running check restarts the retry counter at least once.
6579 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6580 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6581 running = true;
6582 mOffloadUnderrunPosition = position;
6583 }
6584 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006585 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6586 (long long)position, (long long)mOffloadUnderrunPosition);
6587 }
6588 if (running) { // still running, give us more time.
6589 track->mRetryCount = kMaxTrackRetriesOffload;
6590 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006591 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6592 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006593 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006594 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006595 // it will then automatically call start() when data is available
6596 track->disable();
6597 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006598 } else if (last){
6599 mixerStatus = MIXER_TRACKS_ENABLED;
6600 }
6601 }
6602 }
6603 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006604 if (track->isReady()) { // check ready to prevent premature start.
6605 processVolume_l(track, last);
6606 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006607 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006608
Eric Laurentea0fade2013-10-04 16:23:48 -07006609 // make sure the pause/flush/resume sequence is executed in the right order.
6610 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6611 // before flush and then resume HW. This can happen in case of pause/flush/resume
6612 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006613 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006614 status_t result = mOutput->stream->pause();
6615 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006616 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006617 if (mFlushPending) {
6618 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006619 }
Eric Laurentfd477972013-10-25 18:10:40 -07006620 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006621 status_t result = mOutput->stream->resume();
6622 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006623 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006624
Eric Laurentbfb1b832013-01-07 09:53:42 -08006625 // remove all the tracks that need to be...
6626 removeTracks_l(*tracksToRemove);
6627
6628 return mixerStatus;
6629}
6630
Eric Laurentbfb1b832013-01-07 09:53:42 -08006631// must be called with thread mutex locked
6632bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6633{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006634 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6635 mWriteAckSequence, mDrainSequence);
6636 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006637 return true;
6638 }
6639 return false;
6640}
6641
Eric Laurentbfb1b832013-01-07 09:53:42 -08006642bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6643{
6644 Mutex::Autolock _l(mLock);
6645 return waitingAsyncCallback_l();
6646}
6647
6648void AudioFlinger::OffloadThread::flushHw_l()
6649{
Eric Laurente659ef42014-09-29 13:06:46 -07006650 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006651 // Flush anything still waiting in the mixbuffer
6652 mCurrentWriteLength = 0;
6653 mBytesRemaining = 0;
6654 mPausedWriteLength = 0;
6655 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006656 // reset bytes written count to reflect that DSP buffers are empty after flush.
6657 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006658 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006659
Eric Laurentbfb1b832013-01-07 09:53:42 -08006660 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006661 // discard any pending drain or write ack by incrementing sequence
6662 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6663 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006664 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006665 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6666 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006667 }
6668}
6669
Haynes Mathew George05317d22016-05-03 16:34:26 -07006670void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6671{
6672 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006673 if (PlaybackThread::invalidateTracks_l(streamType)) {
6674 mFlushPending = true;
6675 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006676}
6677
Eric Laurentbfb1b832013-01-07 09:53:42 -08006678// ----------------------------------------------------------------------------
6679
Eric Laurent81784c32012-11-19 14:55:58 -08006680AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006681 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006682 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006683 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006684 mWaitTimeMs(UINT_MAX)
6685{
6686 addOutputTrack(mainThread);
6687}
6688
6689AudioFlinger::DuplicatingThread::~DuplicatingThread()
6690{
6691 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6692 mOutputTracks[i]->destroy();
6693 }
6694}
6695
6696void AudioFlinger::DuplicatingThread::threadLoop_mix()
6697{
6698 // mix buffers...
6699 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006700 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006701 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006702 if (mMixerBufferValid) {
6703 memset(mMixerBuffer, 0, mMixerBufferSize);
6704 } else {
6705 memset(mSinkBuffer, 0, mSinkBufferSize);
6706 }
Eric Laurent81784c32012-11-19 14:55:58 -08006707 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006708 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006709 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006710 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006711 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006712}
6713
6714void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6715{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006716 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006717 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006718 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006719 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006720 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006721 }
6722 } else if (mBytesWritten != 0) {
6723 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6724 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006725 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006726 } else {
6727 // flush remaining overflow buffers in output tracks
6728 writeFrames = 0;
6729 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006730 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006731 }
6732}
6733
Eric Laurentbfb1b832013-01-07 09:53:42 -08006734ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006735{
6736 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006737 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6738
6739 // Consider the first OutputTrack for timestamp and frame counting.
6740
6741 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6742 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6743 // we always claim success.
6744 if (i == 0) {
6745 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6746 ALOGD_IF(correction != 0 && writeFrames != 0,
6747 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6748 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6749 mFramesWritten -= correction;
6750 }
6751
6752 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006753 }
Andy Hungcf10d742020-04-28 15:38:24 -07006754 if (mStandby) {
6755 mThreadMetrics.logBeginInterval();
6756 mStandby = false;
6757 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006758 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006759}
6760
6761void AudioFlinger::DuplicatingThread::threadLoop_standby()
6762{
6763 // DuplicatingThread implements standby by stopping all tracks
6764 for (size_t i = 0; i < outputTracks.size(); i++) {
6765 outputTracks[i]->stop();
6766 }
6767}
6768
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006769void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006770{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006771 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006772
6773 std::stringstream ss;
6774 const size_t numTracks = mOutputTracks.size();
6775 ss << " " << numTracks << " OutputTracks";
6776 if (numTracks > 0) {
6777 ss << ":";
6778 for (const auto &track : mOutputTracks) {
6779 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006780 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006781 if (thread.get() != nullptr) {
6782 ss << thread.get() << ", " << thread->id();
6783 } else {
6784 ss << "null";
6785 }
6786 ss << ")";
6787 }
6788 }
6789 ss << "\n";
6790 std::string result = ss.str();
6791 write(fd, result.c_str(), result.size());
6792}
6793
Eric Laurent81784c32012-11-19 14:55:58 -08006794void AudioFlinger::DuplicatingThread::saveOutputTracks()
6795{
6796 outputTracks = mOutputTracks;
6797}
6798
6799void AudioFlinger::DuplicatingThread::clearOutputTracks()
6800{
6801 outputTracks.clear();
6802}
6803
6804void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6805{
6806 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006807 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6808 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6809 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6810 const size_t frameCount =
6811 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6812 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6813 // from different OutputTracks and their associated MixerThreads (e.g. one may
6814 // nearly empty and the other may be dropping data).
6815
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006816 // TODO b/182392769: use identity util, move to server edge
6817 Identity identity = Identity();
6818 identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
6819 IPCThreadState::self()->getCallingUid()));
6820 identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
6821 IPCThreadState::self()->getCallingPid()));
Andy Hungc25b84a2015-01-14 19:04:10 -08006822 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006823 this,
6824 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006825 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006826 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006827 frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006828 identity);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006829 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6830 if (status != NO_ERROR) {
6831 ALOGE("addOutputTrack() initCheck failed %d", status);
6832 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006833 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006834 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6835 mOutputTracks.add(outputTrack);
6836 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6837 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006838}
6839
6840void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6841{
6842 Mutex::Autolock _l(mLock);
6843 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6844 if (mOutputTracks[i]->thread() == thread) {
6845 mOutputTracks[i]->destroy();
6846 mOutputTracks.removeAt(i);
6847 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006848 if (thread->getOutput() == mOutput) {
6849 mOutput = NULL;
6850 }
Eric Laurent81784c32012-11-19 14:55:58 -08006851 return;
6852 }
6853 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006854 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006855}
6856
6857// caller must hold mLock
6858void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6859{
6860 mWaitTimeMs = UINT_MAX;
6861 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6862 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6863 if (strong != 0) {
6864 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6865 if (waitTimeMs < mWaitTimeMs) {
6866 mWaitTimeMs = waitTimeMs;
6867 }
6868 }
6869 }
6870}
6871
6872
6873bool AudioFlinger::DuplicatingThread::outputsReady(
6874 const SortedVector< sp<OutputTrack> > &outputTracks)
6875{
6876 for (size_t i = 0; i < outputTracks.size(); i++) {
6877 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6878 if (thread == 0) {
6879 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6880 outputTracks[i].get());
6881 return false;
6882 }
6883 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6884 // see note at standby() declaration
6885 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6886 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6887 thread.get());
6888 return false;
6889 }
6890 }
6891 return true;
6892}
6893
Kevin Rocard12381092018-04-11 09:19:59 -07006894void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6895 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006896{
Kevin Rocard12381092018-04-11 09:19:59 -07006897 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6898 outputTrack->setMetadatas(metadata.tracks);
6899 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006900}
6901
Eric Laurent81784c32012-11-19 14:55:58 -08006902uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6903{
6904 return (mWaitTimeMs * 1000) / 2;
6905}
6906
6907void AudioFlinger::DuplicatingThread::cacheParameters_l()
6908{
6909 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6910 updateWaitTime_l();
6911
6912 MixerThread::cacheParameters_l();
6913}
6914
Eric Laurent6acd1d42017-01-04 14:23:29 -08006915
Eric Laurent81784c32012-11-19 14:55:58 -08006916// ----------------------------------------------------------------------------
6917// Record
6918// ----------------------------------------------------------------------------
6919
6920AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6921 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006922 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006923 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006924 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006925 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006926 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006927 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006928 mActiveTracks(&this->mLocalLog),
6929 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006930 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006931 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006932 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6933 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006934 // mFastCapture below
6935 , mFastCaptureFutex(0)
6936 // mInputSource
6937 // mPipeSink
6938 // mPipeSource
6939 , mPipeFramesP2(0)
6940 // mPipeMemory
6941 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006942 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006943 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006944{
Glenn Kastend7dca052015-03-05 16:05:54 -08006945 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6946 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006947
George Burgess IVa8f90c12020-05-14 11:27:19 -07006948 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07006949 mIsMsdDevice = strcmp(
6950 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6951 }
6952
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006953 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006954
Andy Hungc8fddf32018-08-08 18:32:37 -07006955 // TODO: We may also match on address as well as device type for
6956 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07006957 // TODO: This property should be ensure that only contains one single device type.
6958 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6959 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006960 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6961 : AUDIO_DEVICE_NONE));
6962
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006963 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006964 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006965 size_t numCounterOffers = 0;
6966 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006967#if !LOG_NDEBUG
6968 ssize_t index =
6969#else
6970 (void)
6971#endif
6972 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006973 ALOG_ASSERT(index == 0);
6974
6975 // initialize fast capture depending on configuration
6976 bool initFastCapture;
6977 switch (kUseFastCapture) {
6978 case FastCapture_Never:
6979 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006980 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006981 break;
6982 case FastCapture_Always:
6983 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006984 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006985 break;
6986 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006987 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006988 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6989 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6990 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006991 break;
6992 // case FastCapture_Dynamic:
6993 }
6994
6995 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006996 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006997 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006998 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6999 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007000 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007001 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007002 const sp<MemoryDealer> roHeap(readOnlyHeap());
7003 sp<IMemory> pipeMemory;
7004 if ((roHeap == 0) ||
7005 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007006 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007007 ALOGE("not enough memory for pipe buffer size=%zu; "
7008 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7009 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7010 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007011 goto failed;
7012 }
7013 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7014 memset(pipeBuffer, 0, pipeSize);
7015 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7016 const NBAIO_Format offers[1] = {format};
7017 size_t numCounterOffers = 0;
7018 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7019 ALOG_ASSERT(index == 0);
7020 mPipeSink = pipe;
7021 PipeReader *pipeReader = new PipeReader(*pipe);
7022 numCounterOffers = 0;
7023 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7024 ALOG_ASSERT(index == 0);
7025 mPipeSource = pipeReader;
7026 mPipeFramesP2 = pipeFramesP2;
7027 mPipeMemory = pipeMemory;
7028
7029 // create fast capture
7030 mFastCapture = new FastCapture();
7031 FastCaptureStateQueue *sq = mFastCapture->sq();
7032#ifdef STATE_QUEUE_DUMP
7033 // FIXME
7034#endif
7035 FastCaptureState *state = sq->begin();
7036 state->mCblk = NULL;
7037 state->mInputSource = mInputSource.get();
7038 state->mInputSourceGen++;
7039 state->mPipeSink = pipe;
7040 state->mPipeSinkGen++;
7041 state->mFrameCount = mFrameCount;
7042 state->mCommand = FastCaptureState::COLD_IDLE;
7043 // already done in constructor initialization list
7044 //mFastCaptureFutex = 0;
7045 state->mColdFutexAddr = &mFastCaptureFutex;
7046 state->mColdGen++;
7047 state->mDumpState = &mFastCaptureDumpState;
7048#ifdef TEE_SINK
7049 // FIXME
7050#endif
7051 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7052 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7053 sq->end();
7054 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7055
7056 // start the fast capture
7057 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7058 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007059 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007060 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007061#ifdef AUDIO_WATCHDOG
7062 // FIXME
7063#endif
7064
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007065 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007066 }
Andy Hung8946a282018-04-19 20:04:56 -07007067#ifdef TEE_SINK
7068 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7069 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7070#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007071failed: ;
7072
7073 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007074}
7075
Eric Laurent81784c32012-11-19 14:55:58 -08007076AudioFlinger::RecordThread::~RecordThread()
7077{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007078 if (mFastCapture != 0) {
7079 FastCaptureStateQueue *sq = mFastCapture->sq();
7080 FastCaptureState *state = sq->begin();
7081 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7082 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7083 if (old == -1) {
7084 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7085 }
7086 }
7087 state->mCommand = FastCaptureState::EXIT;
7088 sq->end();
7089 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7090 mFastCapture->join();
7091 mFastCapture.clear();
7092 }
7093 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007094 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007095 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007096}
7097
7098void AudioFlinger::RecordThread::onFirstRef()
7099{
Glenn Kastend7dca052015-03-05 16:05:54 -08007100 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007101}
7102
Eric Laurent555530a2017-02-07 18:17:24 -08007103void AudioFlinger::RecordThread::preExit()
7104{
7105 ALOGV(" preExit()");
7106 Mutex::Autolock _l(mLock);
7107 for (size_t i = 0; i < mTracks.size(); i++) {
7108 sp<RecordTrack> track = mTracks[i];
7109 track->invalidate();
7110 }
7111 mActiveTracks.clear();
7112 mStartStopCond.broadcast();
7113}
7114
Eric Laurent81784c32012-11-19 14:55:58 -08007115bool AudioFlinger::RecordThread::threadLoop()
7116{
Eric Laurent81784c32012-11-19 14:55:58 -08007117 nsecs_t lastWarning = 0;
7118
7119 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007120
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007121reacquire_wakelock:
7122 sp<RecordTrack> activeTrack;
7123 {
7124 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007125 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007126 }
7127
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007128 // used to request a deferred sleep, to be executed later while mutex is unlocked
7129 uint32_t sleepUs = 0;
7130
Andy Hung446f4df2019-02-21 12:26:41 -08007131 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7132
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007133 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007134 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007135 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007136
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007137 // activeTracks accumulates a copy of a subset of mActiveTracks
7138 Vector< sp<RecordTrack> > activeTracks;
7139
Glenn Kasten735f45f2014-08-18 15:51:59 -07007140 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007141 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007142
Glenn Kasten735f45f2014-08-18 15:51:59 -07007143 // reference to a fast track which is about to be removed
7144 sp<RecordTrack> fastTrackToRemove;
7145
Eric Laurent33403f02020-05-29 18:35:06 -07007146 bool silenceFastCapture = false;
7147
Eric Laurent81784c32012-11-19 14:55:58 -08007148 { // scope for mLock
7149 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007150
Eric Laurent021cf962014-05-13 10:18:14 -07007151 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007152
Eric Laurent000a4192014-01-29 15:17:32 -08007153 // check exitPending here because checkForNewParameters_l() and
7154 // checkForNewParameters_l() can temporarily release mLock
7155 if (exitPending()) {
7156 break;
7157 }
7158
Eric Laurent5c25d562016-07-13 17:17:45 -07007159 // sleep with mutex unlocked
7160 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007161 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007162 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7163 ATRACE_END();
7164 sleepUs = 0;
7165 continue;
7166 }
7167
Glenn Kasten2b806402013-11-20 16:37:38 -08007168 // if no active track(s), then standby and release wakelock
7169 size_t size = mActiveTracks.size();
7170 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007171 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007172 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007173 releaseWakeLock_l();
7174 ALOGV("RecordThread: loop stopping");
7175 // go to sleep
7176 mWaitWorkCV.wait(mLock);
7177 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007178 goto reacquire_wakelock;
7179 }
7180
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007181 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007182 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007183 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007184
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007185 activeTrack = mActiveTracks[i];
7186 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007187 if (activeTrack->isFastTrack()) {
7188 ALOG_ASSERT(fastTrackToRemove == 0);
7189 fastTrackToRemove = activeTrack;
7190 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007191 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007192 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007193 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007194 continue;
7195 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007196
7197 TrackBase::track_state activeTrackState = activeTrack->mState;
7198 switch (activeTrackState) {
7199
7200 case TrackBase::PAUSING:
7201 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007202 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007203 doBroadcast = true;
7204 size--;
7205 continue;
7206
7207 case TrackBase::STARTING_1:
7208 sleepUs = 10000;
7209 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007210 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007211 continue;
7212
7213 case TrackBase::STARTING_2:
7214 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007215 if (mStandby) {
7216 mThreadMetrics.logBeginInterval();
7217 mStandby = false;
7218 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007219 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007220 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007221 break;
7222
7223 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007224 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007225 break;
7226
Andy Hungce685402018-10-05 17:23:27 -07007227 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7228 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7229 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007230 default:
Andy Hungce685402018-10-05 17:23:27 -07007231 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7232 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007233 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007234
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007235 if (activeTrack->isFastTrack()) {
7236 ALOG_ASSERT(!mFastTrackAvail);
7237 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007238 // if the active fast track is silenced either:
7239 // 1) silence the whole capture from fast capture buffer if this is
7240 // the only active track
7241 // 2) invalidate this track: this will cause the client to reconnect and possibly
7242 // be invalidated again until unsilenced
7243 if (activeTrack->isSilenced()) {
7244 if (size > 1) {
7245 activeTrack->invalidate();
7246 ALOG_ASSERT(fastTrackToRemove == 0);
7247 fastTrackToRemove = activeTrack;
7248 removeTrack_l(activeTrack);
7249 mActiveTracks.remove(activeTrack);
7250 size--;
7251 continue;
7252 } else {
7253 silenceFastCapture = true;
7254 }
7255 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007256 fastTrack = activeTrack;
7257 }
Eric Laurent33403f02020-05-29 18:35:06 -07007258
7259 activeTracks.add(activeTrack);
7260 i++;
7261
Glenn Kasten9e982352013-08-14 14:39:50 -07007262 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007263
Andy Hungdae27702016-10-31 14:01:16 -07007264 mActiveTracks.updatePowerState(this);
7265
Kevin Rocard069c2712018-03-29 19:09:14 -07007266 updateMetadata_l();
7267
Eric Laurent5c25d562016-07-13 17:17:45 -07007268 if (allStopped) {
7269 standbyIfNotAlreadyInStandby();
7270 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007271 if (doBroadcast) {
7272 mStartStopCond.broadcast();
7273 }
7274
7275 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007276 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007277 if (sleepUs == 0) {
7278 sleepUs = kRecordThreadSleepUs;
7279 }
7280 continue;
7281 }
7282 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007283
Eric Laurent81784c32012-11-19 14:55:58 -08007284 lockEffectChains_l(effectChains);
7285 }
7286
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007287 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007288
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007289 size_t size = effectChains.size();
7290 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007291 // thread mutex is not locked, but effect chain is locked
7292 effectChains[i]->process_l();
7293 }
7294
Glenn Kasten735f45f2014-08-18 15:51:59 -07007295 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007296 if (mFastCapture != 0) {
7297 FastCaptureStateQueue *sq = mFastCapture->sq();
7298 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007299 bool didModify = false;
7300 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007301 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7302 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7303 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7304 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7305 if (old == -1) {
7306 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7307 }
7308 }
7309 state->mCommand = FastCaptureState::READ_WRITE;
7310#if 0 // FIXME
7311 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007312 FastThreadDumpState::kSamplingNforLowRamDevice :
7313 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007314#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007315 didModify = true;
7316 }
7317 audio_track_cblk_t *cblkOld = state->mCblk;
7318 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7319 if (cblkNew != cblkOld) {
7320 state->mCblk = cblkNew;
7321 // block until acked if removing a fast track
7322 if (cblkOld != NULL) {
7323 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7324 }
7325 didModify = true;
7326 }
jiabin01c8f562018-07-19 17:47:28 -07007327 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7328 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7329 if (state->mFastPatchRecordBufferProvider != abp) {
7330 state->mFastPatchRecordBufferProvider = abp;
7331 state->mFastPatchRecordFormat = fastTrack == 0 ?
7332 AUDIO_FORMAT_INVALID : fastTrack->format();
7333 didModify = true;
7334 }
Eric Laurent33403f02020-05-29 18:35:06 -07007335 if (state->mSilenceCapture != silenceFastCapture) {
7336 state->mSilenceCapture = silenceFastCapture;
7337 didModify = true;
7338 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007339 sq->end(didModify);
7340 if (didModify) {
7341 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007342#if 0
7343 if (kUseFastCapture == FastCapture_Dynamic) {
7344 mNormalSource = mPipeSource;
7345 }
7346#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007347 }
7348 }
7349
Glenn Kasten735f45f2014-08-18 15:51:59 -07007350 // now run the fast track destructor with thread mutex unlocked
7351 fastTrackToRemove.clear();
7352
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007353 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7354 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7355 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7356 // If destination is non-contiguous, first read past the nominal end of buffer, then
7357 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007358
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007359 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007360 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007361 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007362
7363 // If an NBAIO source is present, use it to read the normal capture's data
7364 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007365 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007366
7367 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7368 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7369 // we immediately retry the read() to get data and prevent another overflow.
7370 for (int retries = 0; retries <= 2; ++retries) {
7371 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7372 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7373 framesToRead);
7374 if (framesRead != OVERRUN) break;
7375 }
7376
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007377 const ssize_t availableToRead = mPipeSource->availableToRead();
7378 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007379 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007380 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7381 "more frames to read than fifo size, %zd > %zu",
7382 availableToRead, mPipeFramesP2);
7383 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7384 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7385 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7386 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007387 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7388 }
7389 if (framesRead < 0) {
7390 status_t status = (status_t) framesRead;
7391 switch (status) {
7392 case OVERRUN:
7393 ALOGW("overrun on read from pipe");
7394 framesRead = 0;
7395 break;
7396 case NEGOTIATE:
7397 ALOGE("re-negotiation is needed");
7398 framesRead = -1; // Will cause an attempt to recover.
7399 break;
7400 default:
7401 ALOGE("unknown error %d on read from pipe", status);
7402 break;
7403 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007404 }
7405 // otherwise use the HAL / AudioStreamIn directly
7406 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007407 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007408 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007409 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007410 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007411 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007412 if (result < 0) {
7413 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007414 } else {
7415 framesRead = bytesRead / mFrameSize;
7416 }
7417 }
7418
Andy Hung446f4df2019-02-21 12:26:41 -08007419 const int64_t lastIoEndNs = systemTime(); // end IO timing
7420
Andy Hung3f0c9022016-01-15 17:49:46 -08007421 // Update server timestamp with server stats
7422 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007423 if (framesRead >= 0) {
7424 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7425 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7426 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007427
7428 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007429 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007430 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007431 if (mStandby) {
7432 mTimestampVerifier.discontinuity();
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