blob: 9fd24fc1f2c266ab5d7c49d03bbc79e0d97fa2d7 [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;
Svet Ganov33761132021-05-13 22:51:08 +0000121using content::AttributionSourceState;
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;
Andy Hung455982f2021-04-27 17:46:12 -0700127
Eric Laurent81784c32012-11-19 14:55:58 -0800128// allow less retry attempts on direct output thread.
129// direct outputs can be a scarce resource in audio hardware and should
130// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700131// Notes:
132// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
133// in case the data write is bursty for the AudioTrack. The application
134// should endeavor to write at least once every kMaxTrackRetriesDirectMs
135// to prevent an underrun situation. If the data is bursty, then
136// the application can also throttle the data sent to be even.
137// 2) For compressed audio data, any data present in the AudioTrack buffer
138// will be sent and reset the retry count. This delivers data as
139// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
140// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
141// of data to be available, then any remaining data is delivered.
142// This is required to ensure the last bit of data is delivered before underrun.
143//
144// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
145// or the size of the HAL period for proportional / linear PCM tracks.
146static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800147
148// don't warn about blocked writes or record buffer overflows more often than this
149static const nsecs_t kWarningThrottleNs = seconds(5);
150
151// RecordThread loop sleep time upon application overrun or audio HAL read error
152static const int kRecordThreadSleepUs = 5000;
153
Eric Laurent10351942014-05-08 18:49:52 -0700154// maximum time to wait in sendConfigEvent_l() for a status to be received
155static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800156
157// minimum sleep time for the mixer thread loop when tracks are active but in underrun
158static const uint32_t kMinThreadSleepTimeUs = 5000;
159// maximum divider applied to the active sleep time in the mixer thread loop
160static const uint32_t kMaxThreadSleepTimeShift = 2;
161
Andy Hung09a50072014-02-27 14:30:47 -0800162// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700163// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800164static const uint32_t kMinNormalSinkBufferSizeMs = 20;
165// maximum normal sink buffer size
166static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800167
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700168// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
169// FIXME This should be based on experimentally observed scheduling jitter
170static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
171
Eric Laurent972a1732013-09-04 09:42:59 -0700172// Offloaded output thread standby delay: allows track transition without going to standby
173static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
174
Eric Laurent51716182016-02-29 18:00:56 -0800175// Direct output thread minimum sleep time in idle or active(underrun) state
176static const nsecs_t kDirectMinSleepTimeUs = 10000;
177
Glenn Kasten1b291842016-07-18 14:55:21 -0700178// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
179// balance between power consumption and latency, and allows threads to be scheduled reliably
180// by the CFS scheduler.
181// FIXME Express other hardcoded references to 20ms with references to this constant and move
182// it appropriately.
183#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800184
Eric Laurent81784c32012-11-19 14:55:58 -0800185// Whether to use fast mixer
186static const enum {
187 FastMixer_Never, // never initialize or use: for debugging only
188 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
189 // normal mixer multiplier is 1
190 FastMixer_Static, // initialize if needed, then use all the time if initialized,
191 // multiplier is calculated based on min & max normal mixer buffer size
192 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
193 // multiplier is calculated based on min & max normal mixer buffer size
194 // FIXME for FastMixer_Dynamic:
195 // Supporting this option will require fixing HALs that can't handle large writes.
196 // For example, one HAL implementation returns an error from a large write,
197 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
198 // We could either fix the HAL implementations, or provide a wrapper that breaks
199 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
200} kUseFastMixer = FastMixer_Static;
201
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700202// Whether to use fast capture
203static const enum {
204 FastCapture_Never, // never initialize or use: for debugging only
205 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
206 FastCapture_Static, // initialize if needed, then use all the time if initialized
207} kUseFastCapture = FastCapture_Static;
208
Eric Laurent81784c32012-11-19 14:55:58 -0800209// Priorities for requestPriority
210static const int kPriorityAudioApp = 2;
211static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700212static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800213
Glenn Kastenea38ee72016-04-18 11:08:01 -0700214// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
215// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
216// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700217
218// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800219static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800220
Glenn Kasten03490092014-05-27 12:30:54 -0700221// The minimum and maximum allowed values
222static const int kFastTrackMultiplierMin = 1;
223static const int kFastTrackMultiplierMax = 2;
224
225// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
226static int sFastTrackMultiplier = kFastTrackMultiplier;
227
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700228// See Thread::readOnlyHeap().
229// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
230// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
231// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700232static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700233
Eric Laurent81784c32012-11-19 14:55:58 -0800234// ----------------------------------------------------------------------------
235
Andy Hungb68f5eb2019-12-03 16:49:17 -0800236// TODO: move all toString helpers to audio.h
237// under #ifdef __cplusplus #endif
238static std::string patchSinksToString(const struct audio_patch *patch)
239{
240 std::stringstream ss;
241 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700242 if (i > 0) {
243 ss << "|";
244 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800245 ss << "(" << toString(patch->sinks[i].ext.device.type)
246 << ", " << patch->sinks[i].ext.device.address << ")";
247 }
248 return ss.str();
249}
250
251static std::string patchSourcesToString(const struct audio_patch *patch)
252{
253 std::stringstream ss;
254 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700255 if (i > 0) {
256 ss << "|";
257 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800258 ss << "(" << toString(patch->sources[i].ext.device.type)
259 << ", " << patch->sources[i].ext.device.address << ")";
260 }
261 return ss.str();
262}
263
Glenn Kasten03490092014-05-27 12:30:54 -0700264static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
265
266static void sFastTrackMultiplierInit()
267{
268 char value[PROPERTY_VALUE_MAX];
269 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
270 char *endptr;
271 unsigned long ul = strtoul(value, &endptr, 0);
272 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
273 sFastTrackMultiplier = (int) ul;
274 }
275 }
276}
277
278// ----------------------------------------------------------------------------
279
Eric Laurent81784c32012-11-19 14:55:58 -0800280#ifdef ADD_BATTERY_DATA
281// To collect the amplifier usage
282static void addBatteryData(uint32_t params) {
283 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
284 if (service == NULL) {
285 // it already logged
286 return;
287 }
288
289 service->addBatteryData(params);
290}
291#endif
292
Andy Hung3f0c9022016-01-15 17:49:46 -0800293// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
294struct {
295 // call when you acquire a partial wakelock
296 void acquire(const sp<IBinder> &wakeLockToken) {
297 pthread_mutex_lock(&mLock);
298 if (wakeLockToken.get() == nullptr) {
299 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
300 } else {
301 if (mCount == 0) {
302 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
303 }
304 ++mCount;
305 }
306 pthread_mutex_unlock(&mLock);
307 }
308
309 // call when you release a partial wakelock.
310 void release(const sp<IBinder> &wakeLockToken) {
311 if (wakeLockToken.get() == nullptr) {
312 return;
313 }
314 pthread_mutex_lock(&mLock);
315 if (--mCount < 0) {
316 ALOGE("negative wakelock count");
317 mCount = 0;
318 }
319 pthread_mutex_unlock(&mLock);
320 }
321
322 // retrieves the boottime timebase offset from monotonic.
323 int64_t getBoottimeOffset() {
324 pthread_mutex_lock(&mLock);
325 int64_t boottimeOffset = mBoottimeOffset;
326 pthread_mutex_unlock(&mLock);
327 return boottimeOffset;
328 }
329
330 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
331 // and the selected timebase.
332 // Currently only TIMEBASE_BOOTTIME is allowed.
333 //
334 // This only needs to be called upon acquiring the first partial wakelock
335 // after all other partial wakelocks are released.
336 //
337 // We do an empirical measurement of the offset rather than parsing
338 // /proc/timer_list since the latter is not a formal kernel ABI.
339 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
340 int clockbase;
341 switch (timebase) {
342 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
343 clockbase = SYSTEM_TIME_BOOTTIME;
344 break;
345 default:
346 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
347 break;
348 }
349 // try three times to get the clock offset, choose the one
350 // with the minimum gap in measurements.
351 const int tries = 3;
352 nsecs_t bestGap, measured;
353 for (int i = 0; i < tries; ++i) {
354 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
355 const nsecs_t tbase = systemTime(clockbase);
356 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
357 const nsecs_t gap = tmono2 - tmono;
358 if (i == 0 || gap < bestGap) {
359 bestGap = gap;
360 measured = tbase - ((tmono + tmono2) >> 1);
361 }
362 }
363
364 // to avoid micro-adjusting, we don't change the timebase
365 // unless it is significantly different.
366 //
367 // Assumption: It probably takes more than toleranceNs to
368 // suspend and resume the device.
369 static int64_t toleranceNs = 10000; // 10 us
370 if (llabs(*offset - measured) > toleranceNs) {
371 ALOGV("Adjusting timebase offset old: %lld new: %lld",
372 (long long)*offset, (long long)measured);
373 *offset = measured;
374 }
375 }
376
377 pthread_mutex_t mLock;
378 int32_t mCount;
379 int64_t mBoottimeOffset;
380} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800381
382// ----------------------------------------------------------------------------
383// CPU Stats
384// ----------------------------------------------------------------------------
385
386class CpuStats {
387public:
388 CpuStats();
389 void sample(const String8 &title);
390#ifdef DEBUG_CPU_USAGE
391private:
392 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700393 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800394
Andy Hung16698b82018-08-01 10:48:38 -0700395 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800396
397 int mCpuNum; // thread's current CPU number
398 int mCpukHz; // frequency of thread's current CPU in kHz
399#endif
400};
401
402CpuStats::CpuStats()
403#ifdef DEBUG_CPU_USAGE
404 : mCpuNum(-1), mCpukHz(-1)
405#endif
406{
407}
408
Glenn Kasten0f11b512014-01-31 16:18:54 -0800409void CpuStats::sample(const String8 &title
410#ifndef DEBUG_CPU_USAGE
411 __unused
412#endif
413 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800414#ifdef DEBUG_CPU_USAGE
415 // get current thread's delta CPU time in wall clock ns
416 double wcNs;
417 bool valid = mCpuUsage.sampleAndEnable(wcNs);
418
419 // record sample for wall clock statistics
420 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700421 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800422 }
423
424 // get the current CPU number
425 int cpuNum = sched_getcpu();
426
427 // get the current CPU frequency in kHz
428 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
429
430 // check if either CPU number or frequency changed
431 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
432 mCpuNum = cpuNum;
433 mCpukHz = cpukHz;
434 // ignore sample for purposes of cycles
435 valid = false;
436 }
437
438 // if no change in CPU number or frequency, then record sample for cycle statistics
439 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700440 const double cycles = wcNs * cpukHz * 0.000001;
441 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800442 }
443
Eric Tan5b13ff82018-07-27 11:20:17 -0700444 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800445 // mCpuUsage.elapsed() is expensive, so don't call it every loop
446 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700447 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800448 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700449 const double perLoop = elapsed / (double) n;
450 const double perLoop100 = perLoop * 0.01;
451 const double perLoop1k = perLoop * 0.001;
452 const double mean = mWcStats.getMean();
453 const double stddev = mWcStats.getStdDev();
454 const double minimum = mWcStats.getMin();
455 const double maximum = mWcStats.getMax();
456 const double meanCycles = mHzStats.getMean();
457 const double stddevCycles = mHzStats.getStdDev();
458 const double minCycles = mHzStats.getMin();
459 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800460 mCpuUsage.resetElapsed();
461 mWcStats.reset();
462 mHzStats.reset();
463 ALOGD("CPU usage for %s over past %.1f secs\n"
464 " (%u mixer loops at %.1f mean ms per loop):\n"
465 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
466 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
467 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
468 title.string(),
469 elapsed * .000000001, n, perLoop * .000001,
470 mean * .001,
471 stddev * .001,
472 minimum * .001,
473 maximum * .001,
474 mean / perLoop100,
475 stddev / perLoop100,
476 minimum / perLoop100,
477 maximum / perLoop100,
478 meanCycles / perLoop1k,
479 stddevCycles / perLoop1k,
480 minCycles / perLoop1k,
481 maxCycles / perLoop1k);
482
483 }
484 }
485#endif
486};
487
488// ----------------------------------------------------------------------------
489// ThreadBase
490// ----------------------------------------------------------------------------
491
Glenn Kasten97b7b752014-09-28 13:04:24 -0700492// static
493const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
494{
495 switch (type) {
496 case MIXER:
497 return "MIXER";
498 case DIRECT:
499 return "DIRECT";
500 case DUPLICATING:
501 return "DUPLICATING";
502 case RECORD:
503 return "RECORD";
504 case OFFLOAD:
505 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700506 case MMAP_PLAYBACK:
507 return "MMAP_PLAYBACK";
508 case MMAP_CAPTURE:
509 return "MMAP_CAPTURE";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700510 default:
511 return "unknown";
512 }
513}
514
Eric Laurent81784c32012-11-19 14:55:58 -0800515AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700516 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800517 : Thread(false /*canCallJava*/),
518 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700519 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700520 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
521 isOut),
522 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700523 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800524 // are set by PlaybackThread::readOutputParameters_l() or
525 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700526 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700527 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700528 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800529 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700530 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800531 mSystemReady(systemReady),
532 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800533{
Andy Hungcf10d742020-04-28 15:38:24 -0700534 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700535 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800536}
537
538AudioFlinger::ThreadBase::~ThreadBase()
539{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700540 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700541 mConfigEvents.clear();
542
Eric Laurent81784c32012-11-19 14:55:58 -0800543 // do not lock the mutex in destructor
544 releaseWakeLock_l();
545 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800546 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800547 binder->unlinkToDeath(mDeathRecipient);
548 }
Andy Hungd0979812019-02-21 15:51:44 -0800549
550 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800551}
552
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700553status_t AudioFlinger::ThreadBase::readyToRun()
554{
555 status_t status = initCheck();
556 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800557 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700558 } else {
559 ALOGE("No working audio driver found.");
560 }
561 return status;
562}
563
Eric Laurent81784c32012-11-19 14:55:58 -0800564void AudioFlinger::ThreadBase::exit()
565{
566 ALOGV("ThreadBase::exit");
567 // do any cleanup required for exit to succeed
568 preExit();
569 {
570 // This lock prevents the following race in thread (uniprocessor for illustration):
571 // if (!exitPending()) {
572 // // context switch from here to exit()
573 // // exit() calls requestExit(), what exitPending() observes
574 // // exit() calls signal(), which is dropped since no waiters
575 // // context switch back from exit() to here
576 // mWaitWorkCV.wait(...);
577 // // now thread is hung
578 // }
579 AutoMutex lock(mLock);
580 requestExit();
581 mWaitWorkCV.broadcast();
582 }
583 // When Thread::requestExitAndWait is made virtual and this method is renamed to
584 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
585 requestExitAndWait();
586}
587
588status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
589{
Eric Laurent81784c32012-11-19 14:55:58 -0800590 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
591 Mutex::Autolock _l(mLock);
592
Eric Laurent10351942014-05-08 18:49:52 -0700593 return sendSetParameterConfigEvent_l(keyValuePairs);
594}
595
596// sendConfigEvent_l() must be called with ThreadBase::mLock held
597// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
598status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
599{
600 status_t status = NO_ERROR;
601
Eric Laurent72e3f392015-05-20 14:43:50 -0700602 if (event->mRequiresSystemReady && !mSystemReady) {
603 event->mWaitStatus = false;
604 mPendingConfigEvents.add(event);
605 return status;
606 }
Eric Laurent10351942014-05-08 18:49:52 -0700607 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700608 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800609 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700610 mLock.unlock();
611 {
612 Mutex::Autolock _l(event->mLock);
613 while (event->mWaitStatus) {
614 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
615 event->mStatus = TIMED_OUT;
616 event->mWaitStatus = false;
617 }
618 }
619 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800620 }
Eric Laurent10351942014-05-08 18:49:52 -0700621 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800622 return status;
623}
624
Eric Laurent09f1ed22019-04-24 17:45:17 -0700625void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
626 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800627{
628 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700629 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800630}
631
632// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700633void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
634 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800635{
Andy Hungd0979812019-02-21 15:51:44 -0800636 // The audio statistics history is exponentially weighted to forget events
637 // about five or more seconds in the past. In order to have
638 // crisper statistics for mediametrics, we reset the statistics on
639 // an IoConfigEvent, to reflect different properties for a new device.
640 mIoJitterMs.reset();
641 mLatencyMs.reset();
642 mProcessTimeMs.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100643 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800644
Eric Laurent09f1ed22019-04-24 17:45:17 -0700645 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700646 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800647}
648
Mikhail Naganov83f04272017-02-07 10:45:09 -0800649void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700650{
651 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800652 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700653}
654
Eric Laurent81784c32012-11-19 14:55:58 -0800655// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800656void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
657 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800658{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800659 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700660 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800661}
662
Eric Laurent10351942014-05-08 18:49:52 -0700663// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
664status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800665{
Andy Hung2ddee192015-12-18 17:34:44 -0800666 sp<ConfigEvent> configEvent;
667 AudioParameter param(keyValuePair);
668 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700669 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800670 setMasterMono_l(value != 0);
671 if (param.size() == 1) {
672 return NO_ERROR; // should be a solo parameter - we don't pass down
673 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700674 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800675 configEvent = new SetParameterConfigEvent(param.toString());
676 } else {
677 configEvent = new SetParameterConfigEvent(keyValuePair);
678 }
Eric Laurent10351942014-05-08 18:49:52 -0700679 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700680}
681
Eric Laurent1c333e22014-05-20 10:48:17 -0700682status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
683 const struct audio_patch *patch,
684 audio_patch_handle_t *handle)
685{
686 Mutex::Autolock _l(mLock);
687 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
688 status_t status = sendConfigEvent_l(configEvent);
689 if (status == NO_ERROR) {
690 CreateAudioPatchConfigEventData *data =
691 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
692 *handle = data->mHandle;
693 }
694 return status;
695}
696
697status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
698 const audio_patch_handle_t handle)
699{
700 Mutex::Autolock _l(mLock);
701 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
702 return sendConfigEvent_l(configEvent);
703}
704
jiabinc52b1ff2019-10-31 17:20:42 -0700705status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
706 const DeviceDescriptorBaseVector& outDevices)
707{
708 if (type() != RECORD) {
709 // The update out device operation is only for record thread.
710 return INVALID_OPERATION;
711 }
712 Mutex::Autolock _l(mLock);
713 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
714 return sendConfigEvent_l(configEvent);
715}
716
Eric Laurentec376dc2021-04-08 20:41:22 +0200717void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
718{
719 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
720 sp<ConfigEvent> configEvent =
721 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
722 sendConfigEvent_l(configEvent);
723}
Eric Laurent1c333e22014-05-20 10:48:17 -0700724
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700725// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700726void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700727{
Eric Laurent10351942014-05-08 18:49:52 -0700728 bool configChanged = false;
729
Eric Laurent81784c32012-11-19 14:55:58 -0800730 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700731 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700732 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800733 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700734 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700735 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700736 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
737 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800738 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700739 true /*asynchronous*/);
740 if (err != 0) {
741 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700742 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700743 }
744 } break;
745 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700746 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700747 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700748 } break;
749 case CFG_EVENT_SET_PARAMETER: {
750 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
751 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
752 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700753 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
754 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700755 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700756 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700757 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700758 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700759 CreateAudioPatchConfigEventData *data =
760 (CreateAudioPatchConfigEventData *)event->mData.get();
761 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700762 const DeviceTypeSet newDevices = getDeviceTypes();
763 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
764 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
765 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700766 } break;
767 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700768 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700769 ReleaseAudioPatchConfigEventData *data =
770 (ReleaseAudioPatchConfigEventData *)event->mData.get();
771 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700772 const DeviceTypeSet newDevices = getDeviceTypes();
773 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
774 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
775 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
776 } break;
777 case CFG_EVENT_UPDATE_OUT_DEVICE: {
778 UpdateOutDevicesConfigEventData *data =
779 (UpdateOutDevicesConfigEventData *)event->mData.get();
780 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700781 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200782 case CFG_EVENT_RESIZE_BUFFER: {
783 ResizeBufferConfigEventData *data =
784 (ResizeBufferConfigEventData *)event->mData.get();
785 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
786 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700787 default:
Eric Laurent10351942014-05-08 18:49:52 -0700788 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700789 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800790 }
Eric Laurent10351942014-05-08 18:49:52 -0700791 {
792 Mutex::Autolock _l(event->mLock);
793 if (event->mWaitStatus) {
794 event->mWaitStatus = false;
795 event->mCond.signal();
796 }
797 }
798 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
799 }
800
801 if (configChanged) {
802 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800803 }
Eric Laurent81784c32012-11-19 14:55:58 -0800804}
805
Marco Nelissenb2208842014-02-07 14:00:50 -0800806String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
807 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700808 const audio_channel_representation_t representation =
809 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700810
811 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800812 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700813 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
814 if (output) {
815 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
816 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
817 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700818 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700819 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
820 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
821 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
822 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
823 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
824 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
825 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
826 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
827 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
828 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
829 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
830 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700831 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
832 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
833 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
834 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
835 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
836 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
837 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700838 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700839 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
840 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700841 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
842 } else {
843 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
844 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
845 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
846 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
847 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
848 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
849 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
850 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
851 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
852 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
853 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
854 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700855 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
856 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
857 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700858 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700859 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
860 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700861 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
862 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
863 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
864 }
865 const int len = s.length();
866 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700867 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700868 s.unlockBuffer(len - 2); // remove trailing ", "
869 }
870 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800871 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700872 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
873 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
874 return s;
875 default:
876 s.appendFormat("unknown mask, representation:%d bits:%#x",
877 representation, audio_channel_mask_get_bits(mask));
878 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800879 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800880}
881
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700882void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800883{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800884 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
885 this, mThreadName, getTid(), type(), threadTypeToString(type()));
886
Eric Laurent81784c32012-11-19 14:55:58 -0800887 bool locked = AudioFlinger::dumpTryLock(mLock);
888 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800889 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800890 }
891
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700892 dumpBase_l(fd, args);
893 dumpInternals_l(fd, args);
894 dumpTracks_l(fd, args);
895 dumpEffectChains_l(fd, args);
896
897 if (locked) {
898 mLock.unlock();
899 }
900
901 dprintf(fd, " Local log:\n");
902 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
903}
904
905void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
906{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700907 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700908 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700909 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700910 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700911 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700912 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700913 dprintf(fd, " Channel count: %u\n", mChannelCount);
914 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800915 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700916 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700917 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700918 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800919 size_t numConfig = mConfigEvents.size();
920 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700921 const size_t SIZE = 256;
922 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800923 for (size_t i = 0; i < numConfig; i++) {
924 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700925 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800926 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700927 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800928 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700929 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800930 }
Andy Hung293558a2017-03-21 12:19:20 -0700931 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700932 dprintf(fd, " Output devices: %s (%s)\n",
933 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
934 dprintf(fd, " Input device: %#x (%s)\n",
935 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800936 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800937
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700938 // Dump timestamp statistics for the Thread types that support it.
939 if (mType == RECORD
940 || mType == MIXER
941 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700942 || mType == DIRECT
943 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700944 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700945 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700946 }
947
Andy Hung446f4df2019-02-21 12:26:41 -0800948 if (mLastIoBeginNs > 0) { // MMAP may not set this
949 dprintf(fd, " Last %s occurred (msecs): %lld\n",
950 isOutput() ? "write" : "read",
951 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
952 }
953
954 if (mProcessTimeMs.getN() > 0) {
955 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
956 }
957
958 if (mIoJitterMs.getN() > 0) {
959 dprintf(fd, " Hal %s jitter ms stats: %s\n",
960 isOutput() ? "write" : "read",
961 mIoJitterMs.toString().c_str());
962 }
963
Andy Hunge6c37112019-02-26 17:38:10 -0800964 if (mLatencyMs.getN() > 0) {
965 dprintf(fd, " Threadloop %s latency stats: %s\n",
966 isOutput() ? "write" : "read",
967 mLatencyMs.toString().c_str());
968 }
Eric Laurent81784c32012-11-19 14:55:58 -0800969}
970
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700971void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800972{
973 const size_t SIZE = 256;
974 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800975
Marco Nelissenb2208842014-02-07 14:00:50 -0800976 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000977 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800978 write(fd, buffer, strlen(buffer));
979
Marco Nelissenb2208842014-02-07 14:00:50 -0800980 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800981 sp<EffectChain> chain = mEffectChains[i];
982 if (chain != 0) {
983 chain->dump(fd, args);
984 }
985 }
986}
987
Andy Hungdae27702016-10-31 14:01:16 -0700988void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800989{
990 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700991 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800992}
993
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100994String16 AudioFlinger::ThreadBase::getWakeLockTag()
995{
996 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800997 case MIXER:
998 return String16("AudioMix");
999 case DIRECT:
1000 return String16("AudioDirectOut");
1001 case DUPLICATING:
1002 return String16("AudioDup");
1003 case RECORD:
1004 return String16("AudioIn");
1005 case OFFLOAD:
1006 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001007 case MMAP_PLAYBACK:
1008 return String16("MmapPlayback");
1009 case MMAP_CAPTURE:
1010 return String16("MmapCapture");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001011 default:
1012 ALOG_ASSERT(false);
1013 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001014 }
1015}
1016
Andy Hungdae27702016-10-31 14:01:16 -07001017void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001018{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001019 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001020 if (mPowerManager != 0) {
1021 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001022 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001023 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1024 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001025 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001026 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001027 {} /* workSource */,
1028 {} /* historyTag */);
1029 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001030 mWakeLockToken = binder;
1031 }
Chris Ye6597d732020-02-28 22:38:25 -08001032 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001033 }
Wei Jia3f273d12015-11-24 09:06:49 -08001034
Andy Hung3f0c9022016-01-15 17:49:46 -08001035 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001036 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1037 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001038}
1039
1040void AudioFlinger::ThreadBase::releaseWakeLock()
1041{
1042 Mutex::Autolock _l(mLock);
1043 releaseWakeLock_l();
1044}
1045
1046void AudioFlinger::ThreadBase::releaseWakeLock_l()
1047{
Andy Hung3f0c9022016-01-15 17:49:46 -08001048 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001049 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001050 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001051 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001052 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001053 }
1054 mWakeLockToken.clear();
1055 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001056}
1057
1058void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001059 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001060 // use checkService() to avoid blocking if power service is not up yet
1061 sp<IBinder> binder =
1062 defaultServiceManager()->checkService(String16("power"));
1063 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001064 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001065 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001066 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001067 binder->linkToDeath(mDeathRecipient);
1068 }
1069 }
1070}
1071
Andy Hungd01b0f12016-11-07 16:10:30 -08001072void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001073 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001074
1075#if !LOG_NDEBUG
1076 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001077 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001078 s << uid << " ";
1079 }
1080 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1081#endif
1082
Andy Hung438e7572015-12-14 15:51:17 -08001083 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1084 if (mSystemReady) {
1085 ALOGE("no wake lock to update, but system ready!");
1086 } else {
1087 ALOGW("no wake lock to update, system not ready yet");
1088 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 return;
1090 }
1091 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001092 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001093 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1094 mWakeLockToken, uidsAsInt);
1095 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001096 }
1097}
1098
Eric Laurent81784c32012-11-19 14:55:58 -08001099void AudioFlinger::ThreadBase::clearPowerManager()
1100{
1101 Mutex::Autolock _l(mLock);
1102 releaseWakeLock_l();
1103 mPowerManager.clear();
1104}
1105
jiabinc52b1ff2019-10-31 17:20:42 -07001106void AudioFlinger::ThreadBase::updateOutDevices(
1107 const DeviceDescriptorBaseVector& outDevices __unused)
1108{
1109 ALOGE("%s should only be called in RecordThread", __func__);
1110}
1111
Eric Laurentec376dc2021-04-08 20:41:22 +02001112void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1113{
1114 ALOGE("%s should only be called in RecordThread", __func__);
1115}
1116
Glenn Kasten0f11b512014-01-31 16:18:54 -08001117void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001118{
1119 sp<ThreadBase> thread = mThread.promote();
1120 if (thread != 0) {
1121 thread->clearPowerManager();
1122 }
1123 ALOGW("power manager service died !!!");
1124}
1125
Eric Laurent81784c32012-11-19 14:55:58 -08001126void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001127 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 sp<EffectChain> chain = getEffectChain_l(sessionId);
1130 if (chain != 0) {
1131 if (type != NULL) {
1132 chain->setEffectSuspended_l(type, suspend);
1133 } else {
1134 chain->setEffectSuspendedAll_l(suspend);
1135 }
1136 }
1137
1138 updateSuspendedSessions_l(type, suspend, sessionId);
1139}
1140
1141void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1142{
1143 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1144 if (index < 0) {
1145 return;
1146 }
1147
1148 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1149 mSuspendedSessions.valueAt(index);
1150
1151 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001152 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001153 for (int j = 0; j < desc->mRefCount; j++) {
1154 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1155 chain->setEffectSuspendedAll_l(true);
1156 } else {
1157 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1158 desc->mType.timeLow);
1159 chain->setEffectSuspended_l(&desc->mType, true);
1160 }
1161 }
1162 }
1163}
1164
1165void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1166 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001167 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001168{
1169 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1170
1171 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1172
1173 if (suspend) {
1174 if (index >= 0) {
1175 sessionEffects = mSuspendedSessions.valueAt(index);
1176 } else {
1177 mSuspendedSessions.add(sessionId, sessionEffects);
1178 }
1179 } else {
1180 if (index < 0) {
1181 return;
1182 }
1183 sessionEffects = mSuspendedSessions.valueAt(index);
1184 }
1185
1186
1187 int key = EffectChain::kKeyForSuspendAll;
1188 if (type != NULL) {
1189 key = type->timeLow;
1190 }
1191 index = sessionEffects.indexOfKey(key);
1192
1193 sp<SuspendedSessionDesc> desc;
1194 if (suspend) {
1195 if (index >= 0) {
1196 desc = sessionEffects.valueAt(index);
1197 } else {
1198 desc = new SuspendedSessionDesc();
1199 if (type != NULL) {
1200 desc->mType = *type;
1201 }
1202 sessionEffects.add(key, desc);
1203 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1204 }
1205 desc->mRefCount++;
1206 } else {
1207 if (index < 0) {
1208 return;
1209 }
1210 desc = sessionEffects.valueAt(index);
1211 if (--desc->mRefCount == 0) {
1212 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1213 sessionEffects.removeItemsAt(index);
1214 if (sessionEffects.isEmpty()) {
1215 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1216 sessionId);
1217 mSuspendedSessions.removeItem(sessionId);
1218 }
1219 }
1220 }
1221 if (!sessionEffects.isEmpty()) {
1222 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1223 }
1224}
1225
Eric Laurent6b446ce2019-12-13 10:56:31 -08001226void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1227 audio_session_t sessionId,
1228 bool threadLocked) {
1229 if (!threadLocked) {
1230 mLock.lock();
1231 }
Eric Laurent81784c32012-11-19 14:55:58 -08001232
Eric Laurent81784c32012-11-19 14:55:58 -08001233 if (mType != RECORD) {
1234 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1235 // another session. This gives the priority to well behaved effect control panels
1236 // and applications not using global effects.
1237 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1238 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001239 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001240 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1241 }
1242 }
1243
Eric Laurent6b446ce2019-12-13 10:56:31 -08001244 if (!threadLocked) {
1245 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001246 }
1247}
1248
Eric Laurent4c415062016-06-17 16:14:16 -07001249// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1250status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1251 const effect_descriptor_t *desc, audio_session_t sessionId)
1252{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001253 // No global output effect sessions on record threads
1254 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1255 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001256 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1257 desc->name, mThreadName);
1258 return BAD_VALUE;
1259 }
1260 // only pre processing effects on record thread
1261 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1262 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1263 desc->name, mThreadName);
1264 return BAD_VALUE;
1265 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001266
1267 // always allow effects without processing load or latency
1268 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1269 return NO_ERROR;
1270 }
1271
Eric Laurent4c415062016-06-17 16:14:16 -07001272 audio_input_flags_t flags = mInput->flags;
1273 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1274 if (flags & AUDIO_INPUT_FLAG_RAW) {
1275 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1276 desc->name, mThreadName);
1277 return BAD_VALUE;
1278 }
1279 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1280 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1281 desc->name, mThreadName);
1282 return BAD_VALUE;
1283 }
1284 }
jiabineb3bda02020-06-30 14:07:03 -07001285
1286 if (EffectModule::isHapticGenerator(&desc->type)) {
1287 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1288 return BAD_VALUE;
1289 }
Eric Laurent4c415062016-06-17 16:14:16 -07001290 return NO_ERROR;
1291}
1292
1293// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1294status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1295 const effect_descriptor_t *desc, audio_session_t sessionId)
1296{
1297 // no preprocessing on playback threads
1298 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1299 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1300 " thread %s", desc->name, mThreadName);
1301 return BAD_VALUE;
1302 }
1303
Eric Laurent3e4de772017-07-16 16:55:08 -07001304 // always allow effects without processing load or latency
1305 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1306 return NO_ERROR;
1307 }
1308
jiabineb3bda02020-06-30 14:07:03 -07001309 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1310 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1311 __func__);
1312 return BAD_VALUE;
1313 }
1314
Eric Laurent4c415062016-06-17 16:14:16 -07001315 switch (mType) {
1316 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001317#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001318 // Reject any effect on mixer multichannel sinks.
1319 // TODO: fix both format and multichannel issues with effects.
1320 if (mChannelCount != FCC_2) {
1321 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1322 " thread %s", desc->name, mChannelCount, mThreadName);
1323 return BAD_VALUE;
1324 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001325#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001326 audio_output_flags_t flags = mOutput->flags;
1327 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1328 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1329 // global effects are applied only to non fast tracks if they are SW
1330 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1331 break;
1332 }
1333 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1334 // only post processing on output stage session
1335 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1336 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1337 " on output stage session", desc->name);
1338 return BAD_VALUE;
1339 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001340 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1341 // only post processing on output stage session
1342 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1343 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1344 " on device session", desc->name);
1345 return BAD_VALUE;
1346 }
Eric Laurent4c415062016-06-17 16:14:16 -07001347 } else {
1348 // no restriction on effects applied on non fast tracks
1349 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1350 break;
1351 }
1352 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001353
Eric Laurent4c415062016-06-17 16:14:16 -07001354 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1355 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1356 desc->name);
1357 return BAD_VALUE;
1358 }
1359 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1360 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1361 " in fast mode", desc->name);
1362 return BAD_VALUE;
1363 }
1364 }
1365 } break;
1366 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001367 // nothing actionable on offload threads, if the effect:
1368 // - is offloadable: the effect can be created
1369 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1370 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001371 break;
1372 case DIRECT:
1373 // Reject any effect on Direct output threads for now, since the format of
1374 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1375 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1376 desc->name, mThreadName);
1377 return BAD_VALUE;
1378 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001379#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001380 // Reject any effect on mixer multichannel sinks.
1381 // TODO: fix both format and multichannel issues with effects.
1382 if (mChannelCount != FCC_2) {
1383 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1384 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1385 return BAD_VALUE;
1386 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001387#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001388 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001389 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1390 " thread %s", desc->name, mThreadName);
1391 return BAD_VALUE;
1392 }
1393 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1394 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1395 " DUPLICATING thread %s", desc->name, mThreadName);
1396 return BAD_VALUE;
1397 }
1398 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1399 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1400 " DUPLICATING thread %s", desc->name, mThreadName);
1401 return BAD_VALUE;
1402 }
1403 break;
1404 default:
1405 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1406 }
1407
1408 return NO_ERROR;
1409}
1410
Eric Laurent81784c32012-11-19 14:55:58 -08001411// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1412sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1413 const sp<AudioFlinger::Client>& client,
1414 const sp<IEffectClient>& effectClient,
1415 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001416 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001417 effect_descriptor_t *desc,
1418 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001419 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001420 bool pinned,
1421 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001422{
1423 sp<EffectModule> effect;
1424 sp<EffectHandle> handle;
1425 status_t lStatus;
1426 sp<EffectChain> chain;
1427 bool chainCreated = false;
1428 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001429 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001430
1431 lStatus = initCheck();
1432 if (lStatus != NO_ERROR) {
1433 ALOGW("createEffect_l() Audio driver not initialized.");
1434 goto Exit;
1435 }
1436
Eric Laurent81784c32012-11-19 14:55:58 -08001437 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1438
1439 { // scope for mLock
1440 Mutex::Autolock _l(mLock);
1441
Eric Laurent4c415062016-06-17 16:14:16 -07001442 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001443 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001444 goto Exit;
1445 }
1446
Eric Laurent81784c32012-11-19 14:55:58 -08001447 // check for existing effect chain with the requested audio session
1448 chain = getEffectChain_l(sessionId);
1449 if (chain == 0) {
1450 // create a new chain for this session
1451 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1452 chain = new EffectChain(this, sessionId);
1453 addEffectChain_l(chain);
1454 chain->setStrategy(getStrategyForSession_l(sessionId));
1455 chainCreated = true;
1456 } else {
1457 effect = chain->getEffectFromDesc_l(desc);
1458 }
1459
1460 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1461
1462 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001463 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001464 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001465 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001466 if (lStatus != NO_ERROR) {
1467 goto Exit;
1468 }
1469 effectCreated = true;
1470
jiabinc52b1ff2019-10-31 17:20:42 -07001471 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001472 effect->setDevices(outDeviceTypeAddrs());
1473 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001474 effect->setMode(mAudioFlinger->getMode());
1475 effect->setAudioSource(mAudioSource);
1476 }
jiabin1319f5a2021-03-30 22:21:24 +00001477 if (effect->isHapticGenerator()) {
1478 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1479 // for the HapticGenerator.
1480 const media::AudioVibratorInfo* defaultVibratorInfo =
1481 mAudioFlinger->getDefaultVibratorInfo_l();
1482 if (defaultVibratorInfo != nullptr) {
1483 // Only set the vibrator info when it is a valid one.
1484 effect->setVibratorInfo(defaultVibratorInfo);
1485 }
1486 }
Eric Laurent81784c32012-11-19 14:55:58 -08001487 // create effect handle and connect it to effect module
1488 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001489 lStatus = handle->initCheck();
1490 if (lStatus == OK) {
1491 lStatus = effect->addHandle(handle.get());
1492 }
Eric Laurent81784c32012-11-19 14:55:58 -08001493 if (enabled != NULL) {
1494 *enabled = (int)effect->isEnabled();
1495 }
1496 }
1497
1498Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001499 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001500 Mutex::Autolock _l(mLock);
1501 if (effectCreated) {
1502 chain->removeEffect_l(effect);
1503 }
Eric Laurent81784c32012-11-19 14:55:58 -08001504 if (chainCreated) {
1505 removeEffectChain_l(chain);
1506 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001507 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001508 }
1509
Glenn Kasten9156ef32013-08-06 15:39:08 -07001510 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001511 return handle;
1512}
1513
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001514void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1515 bool unpinIfLast)
1516{
1517 bool remove = false;
1518 sp<EffectModule> effect;
1519 {
1520 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001521 sp<EffectBase> effectBase = handle->effect().promote();
1522 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001523 return;
1524 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001525 effect = effectBase->asEffectModule();
1526 if (effect == nullptr) {
1527 return;
1528 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001529 // restore suspended effects if the disconnected handle was enabled and the last one.
1530 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1531 if (remove) {
1532 removeEffect_l(effect, true);
1533 }
1534 }
1535 if (remove) {
1536 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001537 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001538 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001539 }
1540 }
1541}
1542
Eric Laurent6b446ce2019-12-13 10:56:31 -08001543void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001544 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001545 Mutex::Autolock _l(mLock);
1546 broadcast_l();
1547 }
1548 if (!effect->isOffloadable()) {
1549 if (mType == ThreadBase::OFFLOAD) {
1550 PlaybackThread *t = (PlaybackThread *)this;
1551 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1552 }
1553 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1554 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1555 }
1556 }
1557}
1558
1559void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001560 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001561 Mutex::Autolock _l(mLock);
1562 broadcast_l();
1563 }
1564}
1565
Glenn Kastend848eb42016-03-08 13:42:11 -08001566sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1567 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001568{
1569 Mutex::Autolock _l(mLock);
1570 return getEffect_l(sessionId, effectId);
1571}
1572
Glenn Kastend848eb42016-03-08 13:42:11 -08001573sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1574 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001575{
1576 sp<EffectChain> chain = getEffectChain_l(sessionId);
1577 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1578}
1579
Eric Laurent6c796322019-04-09 14:13:17 -07001580std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1581{
1582 sp<EffectChain> chain = getEffectChain_l(sessionId);
1583 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1584}
1585
Eric Laurent81784c32012-11-19 14:55:58 -08001586// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1587// PlaybackThread::mLock held
1588status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1589{
1590 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001591 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001592 sp<EffectChain> chain = getEffectChain_l(sessionId);
1593 bool chainCreated = false;
1594
Eric Laurent5baf2af2013-09-12 17:37:00 -07001595 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001596 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001597 this, effect->desc().name, effect->desc().flags);
1598
Eric Laurent81784c32012-11-19 14:55:58 -08001599 if (chain == 0) {
1600 // create a new chain for this session
1601 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1602 chain = new EffectChain(this, sessionId);
1603 addEffectChain_l(chain);
1604 chain->setStrategy(getStrategyForSession_l(sessionId));
1605 chainCreated = true;
1606 }
1607 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1608
1609 if (chain->getEffectFromId_l(effect->id()) != 0) {
1610 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1611 this, effect->desc().name, chain.get());
1612 return BAD_VALUE;
1613 }
1614
Eric Laurent5baf2af2013-09-12 17:37:00 -07001615 effect->setOffloaded(mType == OFFLOAD, mId);
1616
Eric Laurent81784c32012-11-19 14:55:58 -08001617 status_t status = chain->addEffect_l(effect);
1618 if (status != NO_ERROR) {
1619 if (chainCreated) {
1620 removeEffectChain_l(chain);
1621 }
1622 return status;
1623 }
1624
jiabin8f278ee2019-11-11 12:16:27 -08001625 effect->setDevices(outDeviceTypeAddrs());
1626 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001627 effect->setMode(mAudioFlinger->getMode());
1628 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001629
Eric Laurent81784c32012-11-19 14:55:58 -08001630 return NO_ERROR;
1631}
1632
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001633void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001634
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001635 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001636 effect_descriptor_t desc = effect->desc();
1637 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1638 detachAuxEffect_l(effect->id());
1639 }
1640
Andy Hungfda44002021-06-03 17:23:16 -07001641 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001642 if (chain != 0) {
1643 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001644 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001645 removeEffectChain_l(chain);
1646 }
1647 } else {
1648 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1649 }
1650}
1651
1652void AudioFlinger::ThreadBase::lockEffectChains_l(
1653 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1654{
1655 effectChains = mEffectChains;
1656 for (size_t i = 0; i < mEffectChains.size(); i++) {
1657 mEffectChains[i]->lock();
1658 }
1659}
1660
1661void AudioFlinger::ThreadBase::unlockEffectChains(
1662 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1663{
1664 for (size_t i = 0; i < effectChains.size(); i++) {
1665 effectChains[i]->unlock();
1666 }
1667}
1668
Glenn Kastend848eb42016-03-08 13:42:11 -08001669sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001670{
1671 Mutex::Autolock _l(mLock);
1672 return getEffectChain_l(sessionId);
1673}
1674
Glenn Kastend848eb42016-03-08 13:42:11 -08001675sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1676 const
Eric Laurent81784c32012-11-19 14:55:58 -08001677{
1678 size_t size = mEffectChains.size();
1679 for (size_t i = 0; i < size; i++) {
1680 if (mEffectChains[i]->sessionId() == sessionId) {
1681 return mEffectChains[i];
1682 }
1683 }
1684 return 0;
1685}
1686
1687void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1688{
1689 Mutex::Autolock _l(mLock);
1690 size_t size = mEffectChains.size();
1691 for (size_t i = 0; i < size; i++) {
1692 mEffectChains[i]->setMode_l(mode);
1693 }
1694}
1695
Mikhail Naganovdc769682018-05-04 15:34:08 -07001696void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001697{
1698 config->type = AUDIO_PORT_TYPE_MIX;
1699 config->ext.mix.handle = mId;
1700 config->sample_rate = mSampleRate;
1701 config->format = mFormat;
1702 config->channel_mask = mChannelMask;
1703 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1704 AUDIO_PORT_CONFIG_FORMAT;
1705}
1706
Eric Laurent72e3f392015-05-20 14:43:50 -07001707void AudioFlinger::ThreadBase::systemReady()
1708{
1709 Mutex::Autolock _l(mLock);
1710 if (mSystemReady) {
1711 return;
1712 }
1713 mSystemReady = true;
1714
1715 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1716 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1717 }
1718 mPendingConfigEvents.clear();
1719}
1720
Andy Hungdae27702016-10-31 14:01:16 -07001721template <typename T>
1722ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1723 ssize_t index = mActiveTracks.indexOf(track);
1724 if (index >= 0) {
1725 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1726 return index;
1727 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001728 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001729 mActiveTracksGeneration++;
1730 mLatestActiveTrack = track;
1731 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001732 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001733 return mActiveTracks.add(track);
1734}
1735
1736template <typename T>
1737ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1738 ssize_t index = mActiveTracks.remove(track);
1739 if (index < 0) {
1740 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1741 return index;
1742 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001743 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001744 mActiveTracksGeneration++;
1745 --mBatteryCounter[track->uid()].second;
1746 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001747 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001748#ifdef TEE_SINK
1749 track->dumpTee(-1 /* fd */, "_REMOVE");
1750#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001751 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001752 return index;
1753}
1754
1755template <typename T>
1756void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1757 for (const sp<T> &track : mActiveTracks) {
1758 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001759 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001760 }
1761 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001762 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001763 mActiveTracks.clear();
1764 mLatestActiveTrack.clear();
1765 mBatteryCounter.clear();
1766}
1767
1768template <typename T>
1769void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1770 sp<ThreadBase> thread, bool force) {
1771 // Updates ActiveTracks client uids to the thread wakelock.
1772 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1773 thread->updateWakeLockUids_l(getWakeLockUids());
1774 mLastActiveTracksGeneration = mActiveTracksGeneration;
1775 }
1776
1777 // Updates BatteryNotifier uids
1778 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1779 const uid_t uid = it->first;
1780 ssize_t &previous = it->second.first;
1781 ssize_t &current = it->second.second;
1782 if (current > 0) {
1783 if (previous == 0) {
1784 BatteryNotifier::getInstance().noteStartAudio(uid);
1785 }
1786 previous = current;
1787 ++it;
1788 } else if (current == 0) {
1789 if (previous > 0) {
1790 BatteryNotifier::getInstance().noteStopAudio(uid);
1791 }
1792 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1793 } else /* (current < 0) */ {
1794 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1795 }
1796 }
1797}
Eric Laurent83b88082014-06-20 18:31:16 -07001798
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001799template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001800bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001801 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001802 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001803
1804 for (const sp<T> &track : mActiveTracks) {
1805 // Do not short-circuit as all hasChanged states must be reset
1806 // as all the metadata are going to be sent
1807 hasChanged |= track->readAndClearHasChanged();
1808 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001809 return hasChanged;
1810}
1811
1812template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001813void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1814 const char *funcName, const sp<T> &track) const {
1815 if (mLocalLog != nullptr) {
1816 String8 result;
1817 track->appendDump(result, false /* active */);
1818 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1819 }
1820}
1821
Eric Laurent6acd1d42017-01-04 14:23:29 -08001822void AudioFlinger::ThreadBase::broadcast_l()
1823{
1824 // Thread could be blocked waiting for async
1825 // so signal it to handle state changes immediately
1826 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1827 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1828 mSignalPending = true;
1829 mWaitWorkCV.broadcast();
1830}
1831
Andy Hungd0979812019-02-21 15:51:44 -08001832// Call only from threadLoop() or when it is idle.
1833// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1834void AudioFlinger::ThreadBase::sendStatistics(bool force)
1835{
1836 // Do not log if we have no stats.
1837 // We choose the timestamp verifier because it is the most likely item to be present.
1838 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1839 if (nstats == 0) {
1840 return;
1841 }
1842
1843 // Don't log more frequently than once per 12 hours.
1844 // We use BOOTTIME to include suspend time.
1845 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1846 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1847 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1848 return;
1849 }
1850
1851 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1852 mLastRecordedTimeNs = timeNs;
1853
Ray Essickf27e9872019-12-07 06:28:46 -08001854 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001855
1856#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1857
1858 // thread configuration
1859 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1860 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1861 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1862 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1863 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1864 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1865 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001866 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1867 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001868
1869 // thread statistics
1870 if (mIoJitterMs.getN() > 0) {
1871 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1872 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1873 }
1874 if (mProcessTimeMs.getN() > 0) {
1875 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1876 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1877 }
1878 const auto tsjitter = mTimestampVerifier.getJitterMs();
1879 if (tsjitter.getN() > 0) {
1880 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1881 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1882 }
1883 if (mLatencyMs.getN() > 0) {
1884 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1885 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1886 }
1887
1888 item->selfrecord();
1889}
1890
Eric Laurent39934ea2021-07-13 13:35:32 +02001891product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1892{
1893 if (!mAudioFlinger->isAudioPolicyReady()) {
1894 return PRODUCT_STRATEGY_NONE;
1895 }
1896 return AudioSystem::getStrategyForStream(stream);
1897}
1898
Eric Laurent81784c32012-11-19 14:55:58 -08001899// ----------------------------------------------------------------------------
1900// Playback
1901// ----------------------------------------------------------------------------
1902
1903AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1904 AudioStreamOut* output,
1905 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001906 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001907 bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07001908 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001909 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001910 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001911 mMixerBuffer(NULL),
1912 mMixerBufferSize(0),
1913 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1914 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001915 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001916 mEffectBuffer(NULL),
1917 mEffectBufferSize(0),
1918 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1919 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001920 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001921 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001922 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001923 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001924 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001925 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001926 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001927 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001928 mMixerStatus(MIXER_IDLE),
1929 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001930 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001931 mBytesRemaining(0),
1932 mCurrentWriteLength(0),
1933 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001934 mWriteAckSequence(0),
1935 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001936 mScreenState(AudioFlinger::mScreenState),
1937 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001938 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001939 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001940 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1941 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001942{
Glenn Kastend7dca052015-03-05 16:05:54 -08001943 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1944 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001945
1946 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1947 // it would be safer to explicitly pass initial masterVolume/masterMute as
1948 // parameter.
1949 //
1950 // If the HAL we are using has support for master volume or master mute,
1951 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1952 // and the mute set to false).
1953 mMasterVolume = audioFlinger->masterVolume_l();
1954 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001955 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001956 if (mOutput->audioHwDev->canSetMasterVolume()) {
1957 mMasterVolume = 1.0;
1958 }
1959
1960 if (mOutput->audioHwDev->canSetMasterMute()) {
1961 mMasterMute = false;
1962 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001963 mIsMsdDevice = strcmp(
1964 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001965 }
1966
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001967 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001968
Andy Hungc8fddf32018-08-08 18:32:37 -07001969 // TODO: We may also match on address as well as device type for
1970 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001971 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001972 // TODO: This property should be ensure that only contains one single device type.
1973 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1974 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001975 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1976 : AUDIO_DEVICE_NONE));
1977 }
1978
Mikhail Naganovf33115d2020-09-25 23:03:05 +00001979 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1980 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08001981 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001982 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1983 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001984 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001985 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1986 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001987 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1988 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001989}
1990
1991AudioFlinger::PlaybackThread::~PlaybackThread()
1992{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001993 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001994 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001995 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001996 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001997}
1998
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001999// Thread virtuals
2000
2001void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002002{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002003 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002004 ALOGE("The stream is not open yet"); // This should not happen.
2005 } else {
2006 // setEventCallback will need a strong pointer as a parameter. Calling it
2007 // here instead of constructor of PlaybackThread so that the onFirstRef
2008 // callback would not be made on an incompletely constructed object.
2009 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002010 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002011 }
2012 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002013 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002014}
2015
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002016// ThreadBase virtuals
2017void AudioFlinger::PlaybackThread::preExit()
2018{
2019 ALOGV(" preExit()");
2020 // FIXME this is using hard-coded strings but in the future, this functionality will be
2021 // converted to use audio HAL extensions required to support tunneling
2022 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2023 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2024}
2025
2026void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002027{
Eric Laurent81784c32012-11-19 14:55:58 -08002028 String8 result;
2029
Marco Nelissenb2208842014-02-07 14:00:50 -08002030 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002031 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2032 const stream_type_t *st = &mStreamTypes[i];
2033 if (i > 0) {
2034 result.appendFormat(", ");
2035 }
2036 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2037 if (st->mute) {
2038 result.append("M");
2039 }
2040 }
2041 result.append("\n");
2042 write(fd, result.string(), result.length());
2043 result.clear();
2044
Eric Laurent81784c32012-11-19 14:55:58 -08002045 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2046 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002047 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002048 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002049
2050 size_t numtracks = mTracks.size();
2051 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002052 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002053 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002054 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002055 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002056 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002057 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002058 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002059 for (size_t i = 0; i < numtracks; ++i) {
2060 sp<Track> track = mTracks[i];
2061 if (track != 0) {
2062 bool active = mActiveTracks.indexOf(track) >= 0;
2063 if (active) {
2064 numactiveseen++;
2065 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002066 result.append(prefix);
2067 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002068 }
2069 }
2070 } else {
2071 result.append("\n");
2072 }
2073 if (numactiveseen != numactive) {
2074 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002075 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002076 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002077 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002078 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002079 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002080 sp<Track> track = mActiveTracks[i];
2081 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002082 result.append(prefix);
2083 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002084 }
2085 }
2086 }
2087
2088 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002089}
2090
Andy Hung542ae9b2021-06-16 09:37:53 -07002091void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002092{
Andy Hung04cb8f72020-03-20 13:44:33 -07002093 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002094 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002095 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2096 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2097 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2098 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002099 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002100 dprintf(fd, " Total writes: %d\n", mNumWrites);
2101 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2102 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2103 dprintf(fd, " Suspend count: %d\n", mSuspended);
2104 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2105 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2106 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2107 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002108 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002109 AudioStreamOut *output = mOutput;
2110 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002111 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002112 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002113 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2114 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2115 if (mPipeSink.get() != nullptr) {
2116 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2117 }
2118 if (output != nullptr) {
2119 dprintf(fd, " Hal stream dump:\n");
Andy Hung542ae9b2021-06-16 09:37:53 -07002120 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002121 }
Eric Laurent81784c32012-11-19 14:55:58 -08002122}
2123
Eric Laurent81784c32012-11-19 14:55:58 -08002124// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2125sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2126 const sp<AudioFlinger::Client>& client,
2127 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002128 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002129 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002130 audio_format_t format,
2131 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002132 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002133 size_t *pNotificationFrameCount,
2134 uint32_t notificationsPerBuffer,
2135 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002136 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002137 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002138 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002139 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002140 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002141 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002142 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002143 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002144 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002145{
Glenn Kasten74935e42013-12-19 08:56:45 -08002146 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002147 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002148 sp<Track> track;
2149 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002150 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002151 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002152 uint32_t sampleRate;
2153
2154 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2155 lStatus = BAD_VALUE;
2156 goto Exit;
2157 }
Eric Laurent21da6472017-11-09 16:29:26 -08002158
2159 if (*pSampleRate == 0) {
2160 *pSampleRate = mSampleRate;
2161 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002162 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002163
2164 // special case for FAST flag considered OK if fast mixer is present
2165 if (hasFastMixer()) {
2166 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2167 }
2168
2169 // Check if requested flags are compatible with output stream flags
2170 if ((*flags & outputFlags) != *flags) {
2171 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2172 *flags, outputFlags);
2173 *flags = (audio_output_flags_t)(*flags & outputFlags);
2174 }
Eric Laurent81784c32012-11-19 14:55:58 -08002175
Eric Laurent81784c32012-11-19 14:55:58 -08002176 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002177 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002178 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002179 // PCM data
2180 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002181 // TODO: extract as a data library function that checks that a computationally
2182 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002183 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002184 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2185 (channelMask == AUDIO_CHANNEL_OUT_MONO
2186 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002187 // hardware sample rate
2188 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002189 // normal mixer has an associated fast mixer
2190 hasFastMixer() &&
2191 // there are sufficient fast track slots available
2192 (mFastTrackAvailMask != 0)
2193 // FIXME test that MixerThread for this fast track has a capable output HAL
2194 // FIXME add a permission test also?
2195 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002196 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2197 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002198 // read the fast track multiplier property the first time it is needed
2199 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2200 if (ok != 0) {
2201 ALOGE("%s pthread_once failed: %d", __func__, ok);
2202 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002203 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002204 }
Eric Laurent4c415062016-06-17 16:14:16 -07002205
2206 // check compatibility with audio effects.
2207 { // scope for mLock
2208 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002209 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002210 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002211 AUDIO_SESSION_OUTPUT_STAGE,
2212 AUDIO_SESSION_OUTPUT_MIX,
2213 sessionId,
2214 }) {
2215 sp<EffectChain> chain = getEffectChain_l(session);
2216 if (chain.get() != nullptr) {
2217 audio_output_flags_t old = *flags;
2218 chain->checkOutputFlagCompatibility(flags);
2219 if (old != *flags) {
2220 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2221 (int)session, (int)old, (int)*flags);
2222 }
Eric Laurent4c415062016-06-17 16:14:16 -07002223 }
2224 }
2225 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002226 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002227 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2228 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002229 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002230 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2231 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002232 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002233 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002234 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002235 audio_is_linear_pcm(format), channelMask, sampleRate,
2236 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002237 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002238 }
2239 }
Eric Laurent21da6472017-11-09 16:29:26 -08002240
2241 if (!audio_has_proportional_frames(format)) {
2242 if (sharedBuffer != 0) {
2243 // Same comment as below about ignoring frameCount parameter for set()
2244 frameCount = sharedBuffer->size();
2245 } else if (frameCount == 0) {
2246 frameCount = mNormalFrameCount;
2247 }
2248 if (notificationFrameCount != frameCount) {
2249 notificationFrameCount = frameCount;
2250 }
2251 } else if (sharedBuffer != 0) {
2252 // FIXME: Ensure client side memory buffers need
2253 // not have additional alignment beyond sample
2254 // (e.g. 16 bit stereo accessed as 32 bit frame).
2255 size_t alignment = audio_bytes_per_sample(format);
2256 if (alignment & 1) {
2257 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2258 alignment = 1;
2259 }
2260 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2261 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2262 if (channelCount > 1) {
2263 // More than 2 channels does not require stronger alignment than stereo
2264 alignment <<= 1;
2265 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002266 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002267 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002268 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002269 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002270 goto Exit;
2271 }
Eric Laurent21da6472017-11-09 16:29:26 -08002272
2273 // When initializing a shared buffer AudioTrack via constructors,
2274 // there's no frameCount parameter.
2275 // But when initializing a shared buffer AudioTrack via set(),
2276 // there _is_ a frameCount parameter. We silently ignore it.
2277 frameCount = sharedBuffer->size() / frameSize;
2278 } else {
2279 size_t minFrameCount = 0;
2280 // For fast tracks we try to respect the application's request for notifications per buffer.
2281 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2282 if (notificationsPerBuffer > 0) {
2283 // Avoid possible arithmetic overflow during multiplication.
2284 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2285 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2286 notificationsPerBuffer, mFrameCount);
2287 } else {
2288 minFrameCount = mFrameCount * notificationsPerBuffer;
2289 }
2290 }
2291 } else {
2292 // For normal PCM streaming tracks, update minimum frame count.
2293 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2294 // cover audio hardware latency.
2295 // This is probably too conservative, but legacy application code may depend on it.
2296 // If you change this calculation, also review the start threshold which is related.
2297 uint32_t latencyMs = latency_l();
2298 if (latencyMs == 0) {
2299 ALOGE("Error when retrieving output stream latency");
2300 lStatus = UNKNOWN_ERROR;
2301 goto Exit;
2302 }
2303
2304 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2305 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2306
Eric Laurent81784c32012-11-19 14:55:58 -08002307 }
Eric Laurent21da6472017-11-09 16:29:26 -08002308 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002309 frameCount = minFrameCount;
2310 }
Eric Laurent81784c32012-11-19 14:55:58 -08002311 }
Eric Laurent21da6472017-11-09 16:29:26 -08002312
2313 // Make sure that application is notified with sufficient margin before underrun.
2314 // The client can divide the AudioTrack buffer into sub-buffers,
2315 // and expresses its desire to server as the notification frame count.
2316 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2317 size_t maxNotificationFrames;
2318 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2319 // notify every HAL buffer, regardless of the size of the track buffer
2320 maxNotificationFrames = mFrameCount;
2321 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002322 // Triple buffer the notification period for a triple buffered mixer period;
2323 // otherwise, double buffering for the notification period is fine.
2324 //
2325 // TODO: This should be moved to AudioTrack to modify the notification period
2326 // on AudioTrack::setBufferSizeInFrames() changes.
2327 const int nBuffering =
2328 (uint64_t{frameCount} * mSampleRate)
2329 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2330
Eric Laurent21da6472017-11-09 16:29:26 -08002331 maxNotificationFrames = frameCount / nBuffering;
2332 // If client requested a fast track but this was denied, then use the smaller maximum.
2333 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2334 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2335 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2336 maxNotificationFrames = maxNotificationFramesFastDenied;
2337 }
2338 }
2339 }
2340 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2341 if (notificationFrameCount == 0) {
2342 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2343 maxNotificationFrames, frameCount);
2344 } else {
2345 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2346 notificationFrameCount, maxNotificationFrames, frameCount);
2347 }
2348 notificationFrameCount = maxNotificationFrames;
2349 }
2350 }
2351
Glenn Kasten74935e42013-12-19 08:56:45 -08002352 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002353 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002354
Glenn Kastenc3df8382014-03-13 15:05:25 -07002355 switch (mType) {
2356
2357 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002358 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002359 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002360 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2361 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002362 sampleRate, format, channelMask, mOutput, mFormat);
2363 lStatus = BAD_VALUE;
2364 goto Exit;
2365 }
2366 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002367 break;
2368
2369 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002370 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002371 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2372 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002373 sampleRate, format, channelMask, mOutput, mFormat);
2374 lStatus = BAD_VALUE;
2375 goto Exit;
2376 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002377 break;
2378
2379 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002380 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002381 ALOGE("createTrack_l() Bad parameter: format %#x \""
2382 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002383 format, mOutput, mFormat);
2384 lStatus = BAD_VALUE;
2385 goto Exit;
2386 }
Andy Hungcd044842014-08-07 11:04:34 -07002387 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002388 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2389 lStatus = BAD_VALUE;
2390 goto Exit;
2391 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002392 break;
2393
Eric Laurent81784c32012-11-19 14:55:58 -08002394 }
2395
2396 lStatus = initCheck();
2397 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002398 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002399 goto Exit;
2400 }
2401
2402 { // scope for mLock
2403 Mutex::Autolock _l(mLock);
2404
2405 // all tracks in same audio session must share the same routing strategy otherwise
2406 // conflicts will happen when tracks are moved from one output to another by audio policy
2407 // manager
Eric Laurent39934ea2021-07-13 13:35:32 +02002408 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002409 for (size_t i = 0; i < mTracks.size(); ++i) {
2410 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002411 if (t != 0 && t->isExternalTrack()) {
Eric Laurent39934ea2021-07-13 13:35:32 +02002412 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002413 if (sessionId == t->sessionId() && strategy != actual) {
2414 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2415 strategy, actual);
2416 lStatus = BAD_VALUE;
2417 goto Exit;
2418 }
2419 }
2420 }
2421
yucliuc9c49cd2020-07-13 16:25:21 -07002422 // Set DIRECT flag if current thread is DirectOutputThread. This can
2423 // happen when the playback is rerouted to direct output thread by
2424 // dynamic audio policy.
2425 // Do NOT report the flag changes back to client, since the client
2426 // doesn't explicitly request a direct flag.
2427 audio_output_flags_t trackFlags = *flags;
2428 if (mType == DIRECT) {
2429 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2430 }
2431
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002432 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002433 channelMask, frameCount,
2434 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002435 sessionId, creatorPid, attributionSource, trackFlags,
2436 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/, speed);
Glenn Kasten03003332013-08-06 15:40:54 -07002437
Glenn Kasten03003332013-08-06 15:40:54 -07002438 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2439 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002440 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002441 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002442 goto Exit;
2443 }
2444 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002445 {
2446 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2447 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002448 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002449 }
2450 }
Eric Laurent81784c32012-11-19 14:55:58 -08002451
2452 sp<EffectChain> chain = getEffectChain_l(sessionId);
2453 if (chain != 0) {
2454 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2455 track->setMainBuffer(chain->inBuffer());
Eric Laurent39934ea2021-07-13 13:35:32 +02002456 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002457 chain->incTrackCnt();
2458 }
2459
Eric Laurent05067782016-06-01 18:27:28 -07002460 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002461 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2462 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2463 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002464 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002465 }
2466 }
2467
2468 lStatus = NO_ERROR;
2469
2470Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002471 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002472 return track;
2473}
2474
Andy Hung1bc088a2018-02-09 15:57:31 -08002475template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002476ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2477{
Andy Hungc0691382018-09-12 18:01:57 -07002478 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002479 const ssize_t index = mTracks.remove(track);
2480 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002481 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002482 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002483 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002484 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002485 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002486 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002487 }
2488 return index;
2489}
2490
Eric Laurent81784c32012-11-19 14:55:58 -08002491uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2492{
2493 return latency;
2494}
2495
2496uint32_t AudioFlinger::PlaybackThread::latency() const
2497{
2498 Mutex::Autolock _l(mLock);
2499 return latency_l();
2500}
2501uint32_t AudioFlinger::PlaybackThread::latency_l() const
2502{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002503 uint32_t latency;
2504 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2505 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002506 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002507 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002508}
2509
2510void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2511{
2512 Mutex::Autolock _l(mLock);
2513 // Don't apply master volume in SW if our HAL can do it for us.
2514 if (mOutput && mOutput->audioHwDev &&
2515 mOutput->audioHwDev->canSetMasterVolume()) {
2516 mMasterVolume = 1.0;
2517 } else {
2518 mMasterVolume = value;
2519 }
2520}
2521
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002522void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2523{
2524 mMasterBalance.store(balance);
2525}
2526
Eric Laurent81784c32012-11-19 14:55:58 -08002527void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2528{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002529 if (isDuplicating()) {
2530 return;
2531 }
Eric Laurent81784c32012-11-19 14:55:58 -08002532 Mutex::Autolock _l(mLock);
2533 // Don't apply master mute in SW if our HAL can do it for us.
2534 if (mOutput && mOutput->audioHwDev &&
2535 mOutput->audioHwDev->canSetMasterMute()) {
2536 mMasterMute = false;
2537 } else {
2538 mMasterMute = muted;
2539 }
2540}
2541
2542void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2543{
2544 Mutex::Autolock _l(mLock);
2545 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002546 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002547}
2548
2549void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2550{
2551 Mutex::Autolock _l(mLock);
2552 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002553 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002554}
2555
2556float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2557{
2558 Mutex::Autolock _l(mLock);
2559 return mStreamTypes[stream].volume;
2560}
2561
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002562void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2563{
2564 mOutput->stream->setVolume(left, right);
2565}
2566
Eric Laurent81784c32012-11-19 14:55:58 -08002567// addTrack_l() must be called with ThreadBase::mLock held
2568status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2569{
2570 status_t status = ALREADY_EXISTS;
2571
Eric Laurent81784c32012-11-19 14:55:58 -08002572 if (mActiveTracks.indexOf(track) < 0) {
2573 // the track is newly added, make sure it fills up all its
2574 // buffers before playing. This is to ensure the client will
2575 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002576 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002577 TrackBase::track_state state = track->mState;
2578 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002579 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002580 mLock.lock();
2581 // abort track was stopped/paused while we released the lock
2582 if (state != track->mState) {
2583 if (status == NO_ERROR) {
2584 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002585 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002586 mLock.lock();
2587 }
2588 return INVALID_OPERATION;
2589 }
2590 // abort if start is rejected by audio policy manager
2591 if (status != NO_ERROR) {
2592 return PERMISSION_DENIED;
2593 }
2594#ifdef ADD_BATTERY_DATA
2595 // to track the speaker usage
2596 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2597#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002598 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 }
2600
Eric Laurent51716182016-02-29 18:00:56 -08002601 // set retry count for buffer fill
2602 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002603 if (track->isStopping_1()) {
2604 track->mRetryCount = kMaxTrackStopRetriesOffload;
2605 } else {
2606 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2607 }
2608 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002609 } else {
2610 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002611 track->mFillingUpStatus =
2612 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002613 }
2614
jiabineb3bda02020-06-30 14:07:03 -07002615 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2616 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2617 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2618 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002619 // Unlock due to VibratorService will lock for this call and will
2620 // call Tracks.mute/unmute which also require thread's lock.
2621 mLock.unlock();
2622 const int intensity = AudioFlinger::onExternalVibrationStart(
2623 track->getExternalVibration());
2624 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002625 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002626 // Haptic playback should be enabled by vibrator service.
2627 if (track->getHapticPlaybackEnabled()) {
2628 // Disable haptic playback of all active track to ensure only
2629 // one track playing haptic if current track should play haptic.
2630 for (const auto &t : mActiveTracks) {
2631 t->setHapticPlaybackEnabled(false);
2632 }
jiabin245cdd92018-12-07 17:55:15 -08002633 }
jiabine70bc7f2020-06-30 22:07:55 -07002634
2635 // Set haptic intensity for effect
2636 if (chain != nullptr) {
2637 chain->setHapticIntensity_l(track->id(), intensity);
2638 }
jiabin245cdd92018-12-07 17:55:15 -08002639 }
2640
Eric Laurent81784c32012-11-19 14:55:58 -08002641 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002642 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002643 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002644 if (chain != 0) {
2645 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2646 track->sessionId());
2647 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002648 }
2649
Andy Hungc2b11cb2020-04-22 09:04:01 -07002650 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002651 status = NO_ERROR;
2652 }
2653
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002654 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002655 return status;
2656}
2657
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002659{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002660 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002661 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002662 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2663 track->mState = TrackBase::STOPPED;
2664 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002665 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002666 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002667 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002668 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669
2670 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002671}
2672
2673void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2674{
2675 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002676
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002677 String8 result;
2678 track->appendDump(result, false /* active */);
2679 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002680
Eric Laurent81784c32012-11-19 14:55:58 -08002681 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002682 {
2683 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2684 mAudioTrackCallbacks.erase(track);
2685 }
Eric Laurent81784c32012-11-19 14:55:58 -08002686 if (track->isFastTrack()) {
2687 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002688 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002689 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2690 mFastTrackAvailMask |= 1 << index;
2691 // redundant as track is about to be destroyed, for dumpsys only
2692 track->mFastIndex = -1;
2693 }
2694 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2695 if (chain != 0) {
2696 chain->decTrackCnt();
2697 }
2698}
2699
2700String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2701{
Eric Laurent81784c32012-11-19 14:55:58 -08002702 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002703 String8 out_s8;
2704 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2705 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002706 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002707 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002708}
2709
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002710status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2711 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002712 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002713 return NO_INIT;
2714 }
2715 return mOutput->stream->selectPresentation(presentationId, programId);
2716}
2717
Eric Laurent09f1ed22019-04-24 17:45:17 -07002718void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2719 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002720 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2721 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002722
Eric Laurent73e26b62015-04-27 16:55:58 -07002723 desc->mIoHandle = mId;
Eric Laurent74c38dc2020-12-23 18:19:44 +01002724 struct audio_patch patch = mPatch;
2725 if (isMsdDevice()) {
2726 patch = mDownStreamPatch;
2727 }
Eric Laurent81784c32012-11-19 14:55:58 -08002728
2729 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002730 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002731 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002732 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002733 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002734 desc->mChannelMask = mChannelMask;
2735 desc->mSamplingRate = mSampleRate;
2736 desc->mFormat = mFormat;
2737 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002738 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002739 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002740 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002741 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002742 case AUDIO_CLIENT_STARTED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002743 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002744 desc->mPortId = portId;
2745 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002746 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002747 default:
2748 break;
2749 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002750 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002751}
2752
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002753void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002754{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002755 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002756}
2757
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002758void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002759{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002760 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002761}
2762
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002763void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002764{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002765 mCallbackThread->setAsyncError();
2766}
2767
jiabinf6eb4c32020-02-25 14:06:25 -08002768void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2769 const std::basic_string<uint8_t>& metadataBs)
2770{
2771 std::thread([this, metadataBs]() {
2772 audio_utils::metadata::Data metadata =
2773 audio_utils::metadata::dataFromByteString(metadataBs);
2774 if (metadata.empty()) {
2775 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2776 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2777 (int)metadataBs.size());
2778 return;
2779 }
2780
2781 audio_utils::metadata::ByteString metaDataStr =
2782 audio_utils::metadata::byteStringFromData(metadata);
2783 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2784 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002785 for (const auto& callbackPair : mAudioTrackCallbacks) {
2786 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002787 }
2788 }).detach();
2789}
2790
Eric Laurent3b4529e2013-09-05 18:09:19 -07002791void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002792{
2793 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002794 // reject out of sequence requests
2795 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2796 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002797 mWaitWorkCV.signal();
2798 }
2799}
2800
Eric Laurent3b4529e2013-09-05 18:09:19 -07002801void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002802{
2803 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002804 // reject out of sequence requests
2805 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002806 // Register discontinuity when HW drain is completed because that can cause
2807 // the timestamp frame position to reset to 0 for direct and offload threads.
2808 // (Out of sequence requests are ignored, since the discontinuity would be handled
2809 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002810 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002811 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002812 mWaitWorkCV.signal();
2813 }
2814}
2815
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002816void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002817{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002818 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002819 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2820 mSampleRate = audioConfig.sample_rate;
2821 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002822 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002823 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002824 }
Andy Hung9a592762014-07-21 21:56:01 -07002825 if ((mType == MIXER || mType == DUPLICATING)
2826 && !isValidPcmSinkChannelMask(mChannelMask)) {
2827 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2828 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002829 }
Andy Hunge5412692014-05-16 11:25:07 -07002830 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002831 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002832
2833 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002834 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002835 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002836 // Get format from the shim, which will be different than the HAL format
2837 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002838 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002839 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002840 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002841 }
Andy Hung6146c082014-03-18 11:56:15 -07002842 if ((mType == MIXER || mType == DUPLICATING)
2843 && !isValidPcmSinkFormat(mFormat)) {
2844 LOG_FATAL("HAL format %#x not supported for mixed output",
2845 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002846 }
Phil Burk062e67a2015-02-11 13:40:50 -08002847 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002848 result = mOutput->stream->getBufferSize(&mBufferSize);
2849 LOG_ALWAYS_FATAL_IF(result != OK,
2850 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002851 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002852 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002853 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002854 mFrameCount);
2855 }
2856
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002857 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2858 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002859 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002860 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002861 }
2862 }
2863
Eric Laurentd1f69b02014-12-15 14:33:13 -08002864 mHwSupportsPause = false;
2865 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002866 bool supportsPause = false, supportsResume = false;
2867 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2868 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002869 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002870 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002871 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002872 } else if (supportsResume) {
2873 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002874 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002875 }
2876 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002877 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2878 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2879 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002880
Andy Hungfbfc3952015-01-15 13:33:51 -08002881 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2882 // For best precision, we use float instead of the associated output
2883 // device format (typically PCM 16 bit).
2884
2885 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2886 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2887 mBufferSize = mFrameSize * mFrameCount;
2888
2889 // TODO: We currently use the associated output device channel mask and sample rate.
2890 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2891 // (if a valid mask) to avoid premature downmix.
2892 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2893 // instead of the output device sample rate to avoid loss of high frequency information.
2894 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2895 }
2896
Andy Hung09a50072014-02-27 14:30:47 -08002897 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002898 double multiplier = 1.0;
2899 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2900 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002901 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2902 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002903
Eric Laurent81784c32012-11-19 14:55:58 -08002904 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2905 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2906 maxNormalFrameCount = maxNormalFrameCount & ~15;
2907 if (maxNormalFrameCount < minNormalFrameCount) {
2908 maxNormalFrameCount = minNormalFrameCount;
2909 }
2910 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2911 if (multiplier <= 1.0) {
2912 multiplier = 1.0;
2913 } else if (multiplier <= 2.0) {
2914 if (2 * mFrameCount <= maxNormalFrameCount) {
2915 multiplier = 2.0;
2916 } else {
2917 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2918 }
2919 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002920 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002921 }
2922 }
2923 mNormalFrameCount = multiplier * mFrameCount;
2924 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002925 if (mType == MIXER || mType == DUPLICATING) {
2926 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2927 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002928 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002929 mNormalFrameCount);
2930
Andy Hung08fb1742015-05-31 23:22:10 -07002931 // Check if we want to throttle the processing to no more than 2x normal rate
2932 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002933 mThreadThrottleTimeMs = 0;
2934 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002935 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2936
Andy Hung010a1a12014-03-13 13:57:33 -07002937 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2938 // Originally this was int16_t[] array, need to remove legacy implications.
2939 free(mSinkBuffer);
2940 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002941 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2942 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2943 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002944 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002945
Andy Hung69aed5f2014-02-25 17:24:40 -08002946 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2947 // drives the output.
2948 free(mMixerBuffer);
2949 mMixerBuffer = NULL;
2950 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002951 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002952 mMixerBufferSize = mNormalFrameCount * mChannelCount
2953 * audio_bytes_per_sample(mMixerBufferFormat);
2954 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2955 }
Andy Hung98ef9782014-03-04 14:46:50 -08002956 free(mEffectBuffer);
2957 mEffectBuffer = NULL;
2958 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002959 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002960 mEffectBufferSize = mNormalFrameCount * mChannelCount
2961 * audio_bytes_per_sample(mEffectBufferFormat);
2962 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2963 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002964
Mikhail Naganov55773032020-10-01 15:08:13 -07002965 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2966 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002967 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2968 mChannelCount -= mHapticChannelCount;
2969
Eric Laurent81784c32012-11-19 14:55:58 -08002970 // force reconfiguration of effect chains and engines to take new buffer size and audio
2971 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002972 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002973 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2974 // matter.
2975 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2976 Vector< sp<EffectChain> > effectChains = mEffectChains;
2977 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002978 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2979 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002980 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002981
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002982 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002983 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002984 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2985 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2986 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2987 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2988 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2989 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2990 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2991 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2992 (int32_t)mHapticChannelMask)
2993 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2994 (int32_t)mHapticChannelCount)
2995 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2996 formatToString(mHALFormat).c_str())
2997 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2998 (int32_t)mFrameCount) // sic - added HAL
2999 ;
3000 uint32_t latencyMs;
3001 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3002 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3003 }
3004 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003005}
3006
Kevin Rocard069c2712018-03-29 19:09:14 -07003007void AudioFlinger::PlaybackThread::updateMetadata_l()
3008{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003009 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003010 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003011 }
3012 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003013 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003014 for (const sp<Track> &track : mActiveTracks) {
3015 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003016 // Do not forward metadata for PatchTrack with unspecified stream type
3017 if (track->streamType() != AUDIO_STREAM_PATCH) {
3018 track->copyMetadataTo(backInserter);
3019 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003020 }
Kevin Rocard12381092018-04-11 09:19:59 -07003021 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003022}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003023
Kevin Rocard12381092018-04-11 09:19:59 -07003024void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3025 const StreamOutHalInterface::SourceMetadata& metadata)
3026{
3027 mOutput->stream->updateSourceMetadata(metadata);
3028};
3029
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003030status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003031{
3032 if (halFrames == NULL || dspFrames == NULL) {
3033 return BAD_VALUE;
3034 }
3035 Mutex::Autolock _l(mLock);
3036 if (initCheck() != NO_ERROR) {
3037 return INVALID_OPERATION;
3038 }
Andy Hung818e7a32016-02-16 18:08:07 -08003039 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003040 *halFrames = framesWritten;
3041
3042 if (isSuspended()) {
3043 // return an estimation of rendered frames when the output is suspended
3044 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003045 *dspFrames = (uint32_t)
3046 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003047 return NO_ERROR;
3048 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003049 status_t status;
3050 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003051 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003052 *dspFrames = (size_t)frames;
3053 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003054 }
3055}
3056
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003057product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003058{
3059 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3060 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3061 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent39934ea2021-07-13 13:35:32 +02003062 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003063 }
3064 for (size_t i = 0; i < mTracks.size(); i++) {
3065 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003066 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent39934ea2021-07-13 13:35:32 +02003067 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003068 }
3069 }
Eric Laurent39934ea2021-07-13 13:35:32 +02003070 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003071}
3072
3073
Phil Burk062e67a2015-02-11 13:40:50 -08003074AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003075{
3076 Mutex::Autolock _l(mLock);
3077 return mOutput;
3078}
3079
Phil Burk062e67a2015-02-11 13:40:50 -08003080AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003081{
3082 Mutex::Autolock _l(mLock);
3083 AudioStreamOut *output = mOutput;
3084 mOutput = NULL;
3085 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3086 // must push a NULL and wait for ack
3087 mOutputSink.clear();
3088 mPipeSink.clear();
3089 mNormalSink.clear();
3090 return output;
3091}
3092
3093// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003094sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003095{
3096 if (mOutput == NULL) {
3097 return NULL;
3098 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003099 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003100}
3101
3102uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3103{
3104 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3105}
3106
3107status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3108{
3109 if (!isValidSyncEvent(event)) {
3110 return BAD_VALUE;
3111 }
3112
3113 Mutex::Autolock _l(mLock);
3114
3115 for (size_t i = 0; i < mTracks.size(); ++i) {
3116 sp<Track> track = mTracks[i];
3117 if (event->triggerSession() == track->sessionId()) {
3118 (void) track->setSyncEvent(event);
3119 return NO_ERROR;
3120 }
3121 }
3122
3123 return NAME_NOT_FOUND;
3124}
3125
3126bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3127{
3128 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3129}
3130
3131void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3132 const Vector< sp<Track> >& tracksToRemove)
3133{
Andy Hungfe726a62018-09-27 15:17:25 -07003134 // Miscellaneous track cleanup when removed from the active list,
3135 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003136#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003137 for (const auto& track : tracksToRemove) {
3138 if (track->isExternalTrack()) {
3139 // to track the speaker usage
3140 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003141 }
3142 }
Andy Hungfe726a62018-09-27 15:17:25 -07003143#else
3144 (void)tracksToRemove; // suppress unused warning
3145#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003146}
3147
3148void AudioFlinger::PlaybackThread::checkSilentMode_l()
3149{
3150 if (!mMasterMute) {
3151 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003152 if (mOutDeviceTypeAddrs.empty()) {
3153 ALOGD("ro.audio.silent is ignored since no output device is set");
3154 return;
3155 }
jiabinc52b1ff2019-10-31 17:20:42 -07003156 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003157 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3158 return;
3159 }
Eric Laurent81784c32012-11-19 14:55:58 -08003160 if (property_get("ro.audio.silent", value, "0") > 0) {
3161 char *endptr;
3162 unsigned long ul = strtoul(value, &endptr, 0);
3163 if (*endptr == '\0' && ul != 0) {
3164 ALOGD("Silence is golden");
3165 // The setprop command will not allow a property to be changed after
3166 // the first time it is set, so we don't have to worry about un-muting.
3167 setMasterMute_l(true);
3168 }
3169 }
3170 }
3171}
3172
3173// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003174ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003175{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003176 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003177 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003178 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003179 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003180
3181 // If an NBAIO sink is present, use it to write the normal mixer's submix
3182 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003183
Andy Hung010a1a12014-03-13 13:57:33 -07003184 const size_t count = mBytesRemaining / mFrameSize;
3185
Simon Wilson2d590962012-11-29 15:18:50 -08003186 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003187 // update the setpoint when AudioFlinger::mScreenState changes
3188 uint32_t screenState = AudioFlinger::mScreenState;
3189 if (screenState != mScreenState) {
3190 mScreenState = screenState;
3191 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3192 if (pipe != NULL) {
3193 pipe->setAvgFrames((mScreenState & 1) ?
3194 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3195 }
3196 }
Andy Hung010a1a12014-03-13 13:57:33 -07003197 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003198 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003199 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003200 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003201#ifdef TEE_SINK
3202 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3203#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003204 } else {
3205 bytesWritten = framesWritten;
3206 }
3207 // otherwise use the HAL / AudioStreamOut directly
3208 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003209 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003210
Eric Laurentbfb1b832013-01-07 09:53:42 -08003211 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003212 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3213 mWriteAckSequence += 2;
3214 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003215 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003216 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003217 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003218 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003219 // FIXME We should have an implementation of timestamps for direct output threads.
3220 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003221 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003222 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003223
Eric Laurentbfb1b832013-01-07 09:53:42 -08003224 if (mUseAsyncWrite &&
3225 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3226 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003227 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003228 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003229 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003230 }
Eric Laurent81784c32012-11-19 14:55:58 -08003231 }
3232
Eric Laurent81784c32012-11-19 14:55:58 -08003233 mNumWrites++;
3234 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003235 if (mStandby) {
3236 mThreadMetrics.logBeginInterval();
3237 mStandby = false;
3238 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003239 return bytesWritten;
3240}
3241
3242void AudioFlinger::PlaybackThread::threadLoop_drain()
3243{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003244 bool supportsDrain = false;
3245 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003246 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3247 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003248 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3249 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003250 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003251 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003252 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003253 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003254 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003255 }
3256}
3257
3258void AudioFlinger::PlaybackThread::threadLoop_exit()
3259{
Eric Laurent275e8e92014-11-30 15:14:47 -08003260 {
3261 Mutex::Autolock _l(mLock);
3262 for (size_t i = 0; i < mTracks.size(); i++) {
3263 sp<Track> track = mTracks[i];
3264 track->invalidate();
3265 }
Andy Hungdae27702016-10-31 14:01:16 -07003266 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3267 // After we exit there are no more track changes sent to BatteryNotifier
3268 // because that requires an active threadLoop.
3269 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3270 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003271 }
Eric Laurent81784c32012-11-19 14:55:58 -08003272}
3273
3274/*
3275The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003276 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003277 - mActiveSleepTimeUs from activeSleepTimeUs()
3278 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003279 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3280 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003281 - maxPeriod from frame count and sample rate (MIXER only)
3282
3283The parameters that affect these derived values are:
3284 - frame count
3285 - frame size
3286 - sample rate
3287 - device type: A2DP or not
3288 - device latency
3289 - format: PCM or not
3290 - active sleep time
3291 - idle sleep time
3292*/
3293
3294void AudioFlinger::PlaybackThread::cacheParameters_l()
3295{
Andy Hung25c2dac2014-02-27 14:56:00 -08003296 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003297 mActiveSleepTimeUs = activeSleepTimeUs();
3298 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003299
3300 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3301 // truncating audio when going to standby.
3302 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003303 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003304 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3305 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3306 }
3307 }
Eric Laurent81784c32012-11-19 14:55:58 -08003308}
3309
Eric Laurent13084622016-05-17 10:51:49 -07003310bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003311{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003312 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003313 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003314 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003315 size_t size = mTracks.size();
3316 for (size_t i = 0; i < size; i++) {
3317 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003318 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003319 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003320 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003321 }
3322 }
Eric Laurent13084622016-05-17 10:51:49 -07003323 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003324}
3325
Haynes Mathew George05317d22016-05-03 16:34:26 -07003326void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3327{
3328 Mutex::Autolock _l(mLock);
3329 invalidateTracks_l(streamType);
3330}
3331
jiabinf042b9b2021-05-07 23:46:28 +00003332// getTrackById_l must be called with holding thread lock
3333AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3334 audio_port_handle_t trackPortId) {
3335 for (size_t i = 0; i < mTracks.size(); i++) {
3336 if (mTracks[i]->portId() == trackPortId) {
3337 return mTracks[i].get();
3338 }
3339 }
3340 return nullptr;
3341}
3342
Eric Laurent81784c32012-11-19 14:55:58 -08003343status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3344{
Glenn Kastend848eb42016-03-08 13:42:11 -08003345 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003346 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003347 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003348 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3349 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3350 &halInBuffer);
3351 if (result != OK) return result;
3352 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003353 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003354 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003355 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003356 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003357 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003358 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003359 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003360 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003361 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003362 &halInBuffer);
3363 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003364#ifdef FLOAT_EFFECT_CHAIN
3365 buffer = halInBuffer->audioBuffer()->f32;
3366#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003367 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003368#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003369 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3370 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003371 }
3372
3373 // Attach all tracks with same session ID to this chain.
3374 for (size_t i = 0; i < mTracks.size(); ++i) {
3375 sp<Track> track = mTracks[i];
3376 if (session == track->sessionId()) {
3377 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3378 buffer);
3379 track->setMainBuffer(buffer);
3380 chain->incTrackCnt();
3381 }
3382 }
3383
3384 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003385 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003386 if (session == track->sessionId()) {
3387 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3388 chain->incActiveTrackCnt();
3389 }
3390 }
3391 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003392 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003393 chain->setInBuffer(halInBuffer);
3394 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003395 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3396 // chains list in order to be processed last as it contains output device effects.
3397 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3398 // processing effects specific to an output stream before effects applied to all streams
3399 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003400 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3401 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003402 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003403 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003404 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003405 // Effect chain for other sessions are inserted at beginning of effect
3406 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003407 // sessions is not important.
3408 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003409 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3410 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003411 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003412 size_t size = mEffectChains.size();
3413 size_t i = 0;
3414 for (i = 0; i < size; i++) {
3415 if (mEffectChains[i]->sessionId() < session) {
3416 break;
3417 }
3418 }
3419 mEffectChains.insertAt(chain, i);
3420 checkSuspendOnAddEffectChain_l(chain);
3421
3422 return NO_ERROR;
3423}
3424
3425size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3426{
Glenn Kastend848eb42016-03-08 13:42:11 -08003427 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003428
3429 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3430
3431 for (size_t i = 0; i < mEffectChains.size(); i++) {
3432 if (chain == mEffectChains[i]) {
3433 mEffectChains.removeAt(i);
3434 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003435 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003436 if (session == track->sessionId()) {
3437 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3438 chain.get(), session);
3439 chain->decActiveTrackCnt();
3440 }
3441 }
3442
3443 // detach all tracks with same session ID from this chain
3444 for (size_t i = 0; i < mTracks.size(); ++i) {
3445 sp<Track> track = mTracks[i];
3446 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003447 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003448 chain->decTrackCnt();
3449 }
3450 }
3451 break;
3452 }
3453 }
3454 return mEffectChains.size();
3455}
3456
3457status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003458 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003459{
3460 Mutex::Autolock _l(mLock);
3461 return attachAuxEffect_l(track, EffectId);
3462}
3463
3464status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003465 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003466{
3467 status_t status = NO_ERROR;
3468
3469 if (EffectId == 0) {
3470 track->setAuxBuffer(0, NULL);
3471 } else {
3472 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3473 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3474 if (effect != 0) {
3475 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3476 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3477 } else {
3478 status = INVALID_OPERATION;
3479 }
3480 } else {
3481 status = BAD_VALUE;
3482 }
3483 }
3484 return status;
3485}
3486
3487void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3488{
3489 for (size_t i = 0; i < mTracks.size(); ++i) {
3490 sp<Track> track = mTracks[i];
3491 if (track->auxEffectId() == effectId) {
3492 attachAuxEffect_l(track, 0);
3493 }
3494 }
3495}
3496
3497bool AudioFlinger::PlaybackThread::threadLoop()
3498{
Glenn Kasten388d5712017-04-07 14:38:41 -07003499 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003500
Eric Laurent81784c32012-11-19 14:55:58 -08003501 Vector< sp<Track> > tracksToRemove;
3502
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003503 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003504 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003505
3506 // MIXER
3507 nsecs_t lastWarning = 0;
3508
3509 // DUPLICATING
3510 // FIXME could this be made local to while loop?
3511 writeFrames = 0;
3512
3513 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003514 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003515
3516 if (mType == MIXER) {
3517 sleepTimeShift = 0;
3518 }
3519
3520 CpuStats cpuStats;
3521 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3522
3523 acquireWakeLock();
3524
Glenn Kasteneef598c2017-04-03 14:41:13 -07003525 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3526 // thread associated with this PlaybackThread.
3527 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3528 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003529 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3530 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003531 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003532 const char *logString = NULL;
3533
rago1bb90822017-05-02 18:31:48 -07003534 // Estimated time for next buffer to be written to hal. This is used only on
3535 // suspended mode (for now) to help schedule the wait time until next iteration.
3536 nsecs_t timeLoopNextNs = 0;
3537
Eric Laurent664539d2013-09-23 18:24:31 -07003538 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003539
Andy Hung2dbffc22018-08-08 18:50:41 -07003540 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003541
Andy Hung446f4df2019-02-21 12:26:41 -08003542 // loopCount is used for statistics and diagnostics.
3543 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003544 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003545 // Log merge requests are performed during AudioFlinger binder transactions, but
3546 // that does not cover audio playback. It's requested here for that reason.
3547 mAudioFlinger->requestLogMerge();
3548
Eric Laurent81784c32012-11-19 14:55:58 -08003549 cpuStats.sample(myName);
3550
3551 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003552 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003553 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003554
Andy Hung2dbffc22018-08-08 18:50:41 -07003555 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3556 //
jiabinc52b1ff2019-10-31 17:20:42 -07003557 // Note: we access outDeviceTypes() outside of mLock.
3558 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003559 // Here, we try for the AF lock, but do not block on it as the latency
3560 // is more informational.
3561 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3562 std::vector<PatchPanel::SoftwarePatch> swPatches;
3563 double latencyMs;
3564 status_t status = INVALID_OPERATION;
3565 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3566 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3567 && swPatches.size() > 0) {
3568 status = swPatches[0].getLatencyMs_l(&latencyMs);
3569 downstreamPatchHandle = swPatches[0].getPatchHandle();
3570 }
3571 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003572 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003573 lastDownstreamPatchHandle = downstreamPatchHandle;
3574 }
3575 if (status == OK) {
3576 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003577 // latency of 5 seconds).
3578 const double minLatency = 0., maxLatency = 5000.;
3579 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003580 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003581 } else {
3582 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003583 if (latencyMs < minLatency) latencyMs = minLatency;
3584 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003585 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003586 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003587 }
3588 mAudioFlinger->mLock.unlock();
3589 }
3590 } else {
3591 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3592 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003593 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003594 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3595 }
3596 }
3597
Eric Laurent81784c32012-11-19 14:55:58 -08003598 { // scope for mLock
3599
3600 Mutex::Autolock _l(mLock);
3601
Eric Laurent021cf962014-05-13 10:18:14 -07003602 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003603
Glenn Kasteneef598c2017-04-03 14:41:13 -07003604 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003605 if (logString != NULL) {
3606 mNBLogWriter->logTimestamp();
3607 mNBLogWriter->log(logString);
3608 logString = NULL;
3609 }
3610
Dean Wheatley12473e92021-03-18 23:00:55 +11003611 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003612
Eric Laurent81784c32012-11-19 14:55:58 -08003613 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003614 if (mSignalPending) {
3615 // A signal was raised while we were unlocked
3616 mSignalPending = false;
3617 } else if (waitingAsyncCallback_l()) {
3618 if (exitPending()) {
3619 break;
3620 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003621 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003622 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003623 releaseWakeLock_l();
3624 released = true;
3625 }
Andy Hung10cbff12017-02-21 17:30:14 -08003626
3627 const int64_t waitNs = computeWaitTimeNs_l();
3628 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3629 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3630 if (status == TIMED_OUT) {
3631 mSignalPending = true; // if timeout recheck everything
3632 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003633 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003634 if (released) {
3635 acquireWakeLock_l();
3636 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003637 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3638 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003639
3640 continue;
3641 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003642 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003643 isSuspended()) {
3644 // put audio hardware into standby after short delay
3645 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003646
3647 threadLoop_standby();
3648
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003649 // This is where we go into standby
3650 if (!mStandby) {
3651 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003652 mThreadMetrics.logEndInterval();
3653 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003654 }
Andy Hungd0979812019-02-21 15:51:44 -08003655 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003656 }
3657
Eric Tan39ec8d62018-07-24 09:49:29 -07003658 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003659 // we're about to wait, flush the binder command buffer
3660 IPCThreadState::self()->flushCommands();
3661
3662 clearOutputTracks();
3663
3664 if (exitPending()) {
3665 break;
3666 }
3667
3668 releaseWakeLock_l();
3669 // wait until we have something to do...
3670 ALOGV("%s going to sleep", myName.string());
3671 mWaitWorkCV.wait(mLock);
3672 ALOGV("%s waking up", myName.string());
3673 acquireWakeLock_l();
3674
3675 mMixerStatus = MIXER_IDLE;
3676 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3677 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003678 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003679 checkSilentMode_l();
3680
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003681 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3682 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003683 if (mType == MIXER) {
3684 sleepTimeShift = 0;
3685 }
3686
3687 continue;
3688 }
3689 }
Eric Laurent81784c32012-11-19 14:55:58 -08003690 // mMixerStatusIgnoringFastTracks is also updated internally
3691 mMixerStatus = prepareTracks_l(&tracksToRemove);
3692
Andy Hungdae27702016-10-31 14:01:16 -07003693 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003694
Kevin Rocard069c2712018-03-29 19:09:14 -07003695 updateMetadata_l();
3696
Eric Laurent81784c32012-11-19 14:55:58 -08003697 // prevent any changes in effect chain list and in each effect chain
3698 // during mixing and effect process as the audio buffers could be deleted
3699 // or modified if an effect is created or deleted
3700 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003701
3702 // Determine which session to pick up haptic data.
3703 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003704 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003705 // TODO: Write haptic data directly to sink buffer when mixing.
3706 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3707 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003708 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3709 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3710 activeHapticSessionId = track->sessionId();
3711 break;
3712 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003713 if (track->getHapticPlaybackEnabled()) {
3714 activeHapticSessionId = track->sessionId();
3715 break;
3716 }
3717 }
3718 }
3719
Andy Hungc1646382019-04-30 16:12:10 -07003720 // Acquire a local copy of active tracks with lock (release w/o lock).
3721 //
3722 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3723 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3724 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3725 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003726 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003727
Eric Laurentbfb1b832013-01-07 09:53:42 -08003728 if (mBytesRemaining == 0) {
3729 mCurrentWriteLength = 0;
3730 if (mMixerStatus == MIXER_TRACKS_READY) {
3731 // threadLoop_mix() sets mCurrentWriteLength
3732 threadLoop_mix();
3733 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3734 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003735 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003736 // must be written to HAL
3737 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003738 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003739 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003740
3741 // Tally underrun frames as we are inserting 0s here.
3742 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003743 if (track->mFillingUpStatus == Track::FS_ACTIVE
3744 && !track->isStopped()
3745 && !track->isPaused()
3746 && !track->isTerminated()) {
3747 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3748 __func__, track->id(), track->getTrackStateAsString(),
3749 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003750 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3751 }
3752 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003753 }
3754 }
Andy Hung98ef9782014-03-04 14:46:50 -08003755 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003756 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003757 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3758 // or mSinkBuffer (if there are no effects).
3759 //
3760 // This is done pre-effects computation; if effects change to
3761 // support higher precision, this needs to move.
3762 //
3763 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003764 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003765 if (mMixerBufferValid) {
3766 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3767 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3768
Andy Hung2ddee192015-12-18 17:34:44 -08003769 // mono blend occurs for mixer threads only (not direct or offloaded)
3770 // and is handled here if we're going directly to the sink.
3771 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003772 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3773 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003774 }
3775
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003776 if (!hasFastMixer()) {
3777 // Balance must take effect after mono conversion.
3778 // We do it here if there is no FastMixer.
3779 // mBalance detects zero balance within the class for speed (not needed here).
3780 mBalance.setBalance(mMasterBalance.load());
3781 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3782 }
3783
Andy Hung98ef9782014-03-04 14:46:50 -08003784 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003785 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3786
3787 // If we're going directly to the sink and there are haptic channels,
3788 // we should adjust channels as the sample data is partially interleaved
3789 // in this case.
3790 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3791 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3792 mChannelCount + mHapticChannelCount,
3793 audio_bytes_per_sample(format),
3794 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3795 }
Andy Hung98ef9782014-03-04 14:46:50 -08003796 }
3797
Eric Laurentbfb1b832013-01-07 09:53:42 -08003798 mBytesRemaining = mCurrentWriteLength;
3799 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003800 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3801 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3802 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3803 mBytesWritten += mBytesRemaining;
3804 mFramesWritten += framesRemaining;
3805 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003806 mBytesRemaining = 0;
3807 }
Eric Laurent81784c32012-11-19 14:55:58 -08003808
Eric Laurentbfb1b832013-01-07 09:53:42 -08003809 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003810 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003811 for (size_t i = 0; i < effectChains.size(); i ++) {
3812 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003813 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003814 if (activeHapticSessionId != AUDIO_SESSION_NONE
3815 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003816 // Haptic data is active in this case, copy it directly from
3817 // in buffer to out buffer.
3818 const size_t audioBufferSize = mNormalFrameCount
3819 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3820 memcpy_by_audio_format(
3821 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3822 EFFECT_BUFFER_FORMAT,
3823 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3824 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3825 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003826 }
Eric Laurent81784c32012-11-19 14:55:58 -08003827 }
3828 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003829 // Process effect chains for offloaded thread even if no audio
3830 // was read from audio track: process only updates effect state
3831 // and thus does have to be synchronized with audio writes but may have
3832 // to be called while waiting for async write callback
3833 if (mType == OFFLOAD) {
3834 for (size_t i = 0; i < effectChains.size(); i ++) {
3835 effectChains[i]->process_l();
3836 }
3837 }
Eric Laurent81784c32012-11-19 14:55:58 -08003838
Andy Hung98ef9782014-03-04 14:46:50 -08003839 // Only if the Effects buffer is enabled and there is data in the
3840 // Effects buffer (buffer valid), we need to
3841 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003842 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003843 if (mEffectBufferValid) {
3844 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003845
3846 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003847 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3848 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003849 }
3850
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003851 if (!hasFastMixer()) {
3852 // Balance must take effect after mono conversion.
3853 // We do it here if there is no FastMixer.
3854 // mBalance detects zero balance within the class for speed (not needed here).
3855 mBalance.setBalance(mMasterBalance.load());
3856 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3857 }
3858
Andy Hung98ef9782014-03-04 14:46:50 -08003859 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003860 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3861 // The sample data is partially interleaved when haptic channels exist,
3862 // we need to adjust channels here.
3863 if (mHapticChannelCount > 0) {
3864 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3865 mChannelCount + mHapticChannelCount,
3866 audio_bytes_per_sample(mFormat),
3867 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3868 }
Andy Hung98ef9782014-03-04 14:46:50 -08003869 }
3870
Eric Laurent81784c32012-11-19 14:55:58 -08003871 // enable changes in effect chain
3872 unlockEffectChains(effectChains);
3873
Eric Laurentbfb1b832013-01-07 09:53:42 -08003874 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003875 // mSleepTimeUs == 0 means we must write to audio hardware
3876 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003877 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003878 // writePeriodNs is updated >= 0 when ret > 0.
3879 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003880 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003881 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003882 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003883 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003884 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003885 if (ret < 0) {
3886 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003887 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003888 mBytesWritten += ret;
3889 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003890 const int64_t frames = ret / mFrameSize;
3891 mFramesWritten += frames;
3892
3893 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3894 // process information relating to write time.
3895 if (audio_has_proportional_frames(mFormat)) {
3896 // we are in a continuous mixing cycle
3897 if (mMixerStatus == MIXER_TRACKS_READY &&
3898 loopCount == lastLoopCountWritten + 1) {
3899
3900 const double jitterMs =
3901 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3902 {frames, writePeriodNs},
3903 {0, 0} /* lastTimestamp */, mSampleRate);
3904 const double processMs =
3905 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3906
3907 Mutex::Autolock _l(mLock);
3908 mIoJitterMs.add(jitterMs);
3909 mProcessTimeMs.add(processMs);
3910 }
3911
3912 // write blocked detection
3913 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3914 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3915 mNumDelayedWrites++;
3916 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3917 ATRACE_NAME("underrun");
3918 ALOGW("write blocked for %lld msecs, "
3919 "%d delayed writes, thread %d",
3920 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3921 mNumDelayedWrites, mId);
3922 lastWarning = lastIoEndNs;
3923 }
3924 }
3925 }
3926 // update timing info.
3927 mLastIoBeginNs = lastIoBeginNs;
3928 mLastIoEndNs = lastIoEndNs;
3929 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003930 }
3931 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3932 (mMixerStatus == MIXER_DRAIN_ALL)) {
3933 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003934 }
Andy Hung08fb1742015-05-31 23:22:10 -07003935 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003936
3937 if (mThreadThrottle
3938 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003939 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003940 // Limit MixerThread data processing to no more than twice the
3941 // expected processing rate.
3942 //
3943 // This helps prevent underruns with NuPlayer and other applications
3944 // which may set up buffers that are close to the minimum size, or use
3945 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3946 //
3947 // The throttle smooths out sudden large data drains from the device,
3948 // e.g. when it comes out of standby, which often causes problems with
3949 // (1) mixer threads without a fast mixer (which has its own warm-up)
3950 // (2) minimum buffer sized tracks (even if the track is full,
3951 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003952 //
3953 // Total time spent in last processing cycle equals time spent in
3954 // 1. threadLoop_write, as well as time spent in
3955 // 2. threadLoop_mix (significant for heavy mixing, especially
3956 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003957
Andy Hung446f4df2019-02-21 12:26:41 -08003958 // it's OK if deltaMs is an overestimate.
3959
3960 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003961
Ivan Lozanoea04d392017-11-07 14:37:07 -08003962 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003963 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07003964 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08003965
Andy Hung08fb1742015-05-31 23:22:10 -07003966 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003967 // notify of throttle start on verbose log
3968 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3969 "mixer(%p) throttle begin:"
3970 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003971 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003972 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003973 // Throttle must be attributed to the previous mixer loop's write time
3974 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003975 // This also ensures proper timing statistics.
3976 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003977 } else {
3978 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3979 if (diff > 0) {
3980 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003981 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07003982 ALOGD_IF(!isSingleDeviceType(
3983 outDeviceTypes(), audio_is_a2dp_out_device) &&
3984 !isSingleDeviceType(
3985 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003986 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003987 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3988 }
Andy Hung08fb1742015-05-31 23:22:10 -07003989 }
3990 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003991 }
Eric Laurent81784c32012-11-19 14:55:58 -08003992
Eric Laurentbfb1b832013-01-07 09:53:42 -08003993 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003994 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003995 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003996 // suspended requires accurate metering of sleep time.
3997 if (isSuspended()) {
3998 // advance by expected sleepTime
3999 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4000 const nsecs_t nowNs = systemTime();
4001
4002 // compute expected next time vs current time.
4003 // (negative deltas are treated as delays).
4004 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4005 if (deltaNs < -kMaxNextBufferDelayNs) {
4006 // Delays longer than the max allowed trigger a reset.
4007 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4008 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4009 timeLoopNextNs = nowNs + deltaNs;
4010 } else if (deltaNs < 0) {
4011 // Delays within the max delay allowed: zero the delta/sleepTime
4012 // to help the system catch up in the next iteration(s)
4013 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4014 deltaNs = 0;
4015 }
4016 // update sleep time (which is >= 0)
4017 mSleepTimeUs = deltaNs / 1000;
4018 }
Eric Laurente93cc032016-05-05 10:15:10 -07004019 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4020 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004021 }
Glenn Kastene7754022014-10-31 12:11:26 -07004022 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004023 }
Eric Laurent81784c32012-11-19 14:55:58 -08004024 }
4025
4026 // Finally let go of removed track(s), without the lock held
4027 // since we can't guarantee the destructors won't acquire that
4028 // same lock. This will also mutate and push a new fast mixer state.
4029 threadLoop_removeTracks(tracksToRemove);
4030 tracksToRemove.clear();
4031
4032 // FIXME I don't understand the need for this here;
4033 // it was in the original code but maybe the
4034 // assignment in saveOutputTracks() makes this unnecessary?
4035 clearOutputTracks();
4036
4037 // Effect chains will be actually deleted here if they were removed from
4038 // mEffectChains list during mixing or effects processing
4039 effectChains.clear();
4040
4041 // FIXME Note that the above .clear() is no longer necessary since effectChains
4042 // is now local to this block, but will keep it for now (at least until merge done).
4043 }
4044
Eric Laurentbfb1b832013-01-07 09:53:42 -08004045 threadLoop_exit();
4046
Eric Laurentcf817a22014-08-04 20:36:31 -07004047 if (!mStandby) {
4048 threadLoop_standby();
4049 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004050 }
4051
4052 releaseWakeLock();
4053
4054 ALOGV("Thread %p type %d exiting", this, mType);
4055 return false;
4056}
4057
Dean Wheatley12473e92021-03-18 23:00:55 +11004058void AudioFlinger::PlaybackThread::collectTimestamps_l()
4059{
4060 // Collect timestamp statistics for the Playback Thread types that support it.
4061 if (mType != MIXER
4062 && mType != DUPLICATING
4063 && mType != DIRECT
4064 && mType != OFFLOAD) {
4065 return;
4066 }
4067 if (mStandby) {
4068 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4069 return;
4070 } else if (mHwPaused) {
4071 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4072 return;
4073 }
4074
4075 // Gather the framesReleased counters for all active tracks,
4076 // and associate with the sink frames written out. We need
4077 // this to convert the sink timestamp to the track timestamp.
4078 bool kernelLocationUpdate = false;
4079 ExtendedTimestamp timestamp; // use private copy to fetch
4080
4081 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4082 // HAL may be draining some small duration buffered data for fade out.
4083 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4084 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4085 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4086 mSampleRate);
4087
4088 if (isTimestampCorrectionEnabled()) {
4089 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4090 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4091 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4092 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4093 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4094 = correctedTimestamp.mFrames;
4095 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4096 = correctedTimestamp.mTimeNs;
4097 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4098 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4099 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4100
4101 // Note: Downstream latency only added if timestamp correction enabled.
4102 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4103 const int64_t newPosition =
4104 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4105 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4106 // prevent retrograde
4107 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4108 newPosition,
4109 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4110 - mSuspendedFrames));
4111 }
4112 }
4113
4114 // We always fetch the timestamp here because often the downstream
4115 // sink will block while writing.
4116
4117 // We keep track of the last valid kernel position in case we are in underrun
4118 // and the normal mixer period is the same as the fast mixer period, or there
4119 // is some error from the HAL.
4120 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4121 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4122 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4123 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4124 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4125
4126 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4127 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4128 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4129 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4130 }
4131
4132 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4133 kernelLocationUpdate = true;
4134 } else {
4135 ALOGVV("getTimestamp error - no valid kernel position");
4136 }
4137
4138 // copy over kernel info
4139 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4140 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4141 + mSuspendedFrames; // add frames discarded when suspended
4142 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4143 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4144 } else {
4145 mTimestampVerifier.error();
4146 }
4147
4148 // mFramesWritten for non-offloaded tracks are contiguous
4149 // even after standby() is called. This is useful for the track frame
4150 // to sink frame mapping.
4151 bool serverLocationUpdate = false;
4152 if (mFramesWritten != mLastFramesWritten) {
4153 serverLocationUpdate = true;
4154 mLastFramesWritten = mFramesWritten;
4155 }
4156 // Only update timestamps if there is a meaningful change.
4157 // Either the kernel timestamp must be valid or we have written something.
4158 if (kernelLocationUpdate || serverLocationUpdate) {
4159 if (serverLocationUpdate) {
4160 // use the time before we called the HAL write - it is a bit more accurate
4161 // to when the server last read data than the current time here.
4162 //
4163 // If we haven't written anything, mLastIoBeginNs will be -1
4164 // and we use systemTime().
4165 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4166 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4167 ? systemTime() : mLastIoBeginNs;
4168 }
4169
4170 for (const sp<Track> &t : mActiveTracks) {
4171 if (!t->isFastTrack()) {
4172 t->updateTrackFrameInfo(
4173 t->mAudioTrackServerProxy->framesReleased(),
4174 mFramesWritten,
4175 mSampleRate,
4176 mTimestamp);
4177 }
4178 }
4179 }
4180
4181 if (audio_has_proportional_frames(mFormat)) {
4182 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4183 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4184 mLatencyMs.add(latencyMs);
4185 }
4186 }
4187#if 0
4188 // logFormat example
4189 if (z % 100 == 0) {
4190 timespec ts;
4191 clock_gettime(CLOCK_MONOTONIC, &ts);
4192 LOGT("This is an integer %d, this is a float %f, this is my "
4193 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4194 LOGT("A deceptive null-terminated string %\0");
4195 }
4196 ++z;
4197#endif
4198}
4199
Eric Laurentbfb1b832013-01-07 09:53:42 -08004200// removeTracks_l() must be called with ThreadBase::mLock held
4201void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4202{
Andy Hungfe726a62018-09-27 15:17:25 -07004203 for (const auto& track : tracksToRemove) {
4204 mActiveTracks.remove(track);
4205 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4206 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4207 if (chain != 0) {
4208 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4209 __func__, track->id(), chain.get(), track->sessionId());
4210 chain->decActiveTrackCnt();
4211 }
4212 // If an external client track, inform APM we're no longer active, and remove if needed.
4213 // We do this under lock so that the state is consistent if the Track is destroyed.
4214 if (track->isExternalTrack()) {
4215 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004216 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004217 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004218 }
4219 }
Andy Hungfe726a62018-09-27 15:17:25 -07004220 if (track->isTerminated()) {
4221 // remove from our tracks vector
4222 removeTrack_l(track);
4223 }
jiabineb3bda02020-06-30 14:07:03 -07004224 if (mHapticChannelCount > 0 &&
4225 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4226 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004227 mLock.unlock();
4228 // Unlock due to VibratorService will lock for this call and will
4229 // call Tracks.mute/unmute which also require thread's lock.
4230 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4231 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004232
4233 // When the track is stop, set the haptic intensity as MUTE
4234 // for the HapticGenerator effect.
4235 if (chain != nullptr) {
4236 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4237 }
jiabin245cdd92018-12-07 17:55:15 -08004238 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004239 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004240}
Eric Laurent81784c32012-11-19 14:55:58 -08004241
Eric Laurentaccc1472013-09-20 09:36:34 -07004242status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4243{
4244 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004245 ExtendedTimestamp ets;
4246 status_t status = mNormalSink->getTimestamp(ets);
4247 if (status == NO_ERROR) {
4248 status = ets.getBestTimestamp(&timestamp);
4249 }
4250 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004251 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004252 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004253 collectTimestamps_l();
4254 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4255 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004256 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004257 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4258 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4259 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4260 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4261 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004262 }
4263 return INVALID_OPERATION;
4264}
Eric Laurent1c333e22014-05-20 10:48:17 -07004265
Eric Laurenteab90452019-06-24 15:17:46 -07004266// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4267// still applied by the mixer.
4268// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4269// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4270// if more than one track are active
4271status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4272{
4273 status_t result = NO_ERROR;
4274 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4275 if (*volume != mLeftVolFloat) {
4276 result = mOutput->stream->setVolume(*volume, *volume);
4277 ALOGE_IF(result != OK,
4278 "Error when setting output stream volume: %d", result);
4279 if (result == NO_ERROR) {
4280 mLeftVolFloat = *volume;
4281 }
4282 }
4283 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4284 // remove stream volume contribution from software volume.
4285 if (mLeftVolFloat == *volume) {
4286 *volume = 1.0f;
4287 }
4288 }
4289 return result;
4290}
4291
Eric Laurent054d9d32015-04-24 08:48:48 -07004292status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4293 audio_patch_handle_t *handle)
4294{
Andy Hungf60abce2016-08-26 11:37:54 -07004295 status_t status;
4296 if (property_get_bool("af.patch_park", false /* default_value */)) {
4297 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4298 // or if HAL does not properly lock against access.
4299 AutoPark<FastMixer> park(mFastMixer);
4300 status = PlaybackThread::createAudioPatch_l(patch, handle);
4301 } else {
4302 status = PlaybackThread::createAudioPatch_l(patch, handle);
4303 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004304 return status;
4305}
4306
Eric Laurent1c333e22014-05-20 10:48:17 -07004307status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4308 audio_patch_handle_t *handle)
4309{
4310 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004311
4312 // store new device and send to effects
4313 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004314 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004315 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004316 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4317 && !mOutput->audioHwDev->supportsAudioPatches(),
4318 "Enumerated device type(%#x) must not be used "
4319 "as it does not support audio patches",
4320 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004321 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004322 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4323 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004324 }
4325
François Gaffie0c280aa2018-07-25 10:02:15 +02004326 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004327#ifdef ADD_BATTERY_DATA
4328 // when changing the audio output device, call addBatteryData to notify
4329 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004330 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004331 uint32_t params = 0;
4332 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004333 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004334 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004335 }
4336
Eric Laurent054d9d32015-04-24 08:48:48 -07004337 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004338 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004339 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4340 }
4341
4342 if (params != 0) {
4343 addBatteryData(params);
4344 }
4345 }
4346#endif
4347
4348 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004349 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004350 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004351
jiabinc52b1ff2019-10-31 17:20:42 -07004352 // mPatch.num_sinks is not set when the thread is created so that
4353 // the first patch creation triggers an ioConfigChanged callback
4354 bool configChanged = (mPatch.num_sinks == 0) ||
4355 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004356 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004357 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004358 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004359
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004360 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004361 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4362 status = hwDevice->createAudioPatch(patch->num_sources,
4363 patch->sources,
4364 patch->num_sinks,
4365 patch->sinks,
4366 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004367 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004368 char *address;
4369 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4370 //FIXME: we only support address on first sink with HAL version < 3.0
4371 address = audio_device_address_to_parameter(
4372 patch->sinks[0].ext.device.type,
4373 patch->sinks[0].ext.device.address);
4374 } else {
4375 address = (char *)calloc(1, 1);
4376 }
4377 AudioParameter param = AudioParameter(String8(address));
4378 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004379 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004380 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004381 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004382 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004383 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004384
4385 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004386 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004387 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004388 // also dispatch to active AudioTracks for MediaMetrics
4389 for (const auto &track : mActiveTracks) {
4390 track->logEndInterval();
4391 track->logBeginInterval(patchSinksAsString);
4392 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004393
Eric Laurente8726fe2015-06-26 09:39:24 -07004394 if (configChanged) {
4395 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4396 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004397 return status;
4398}
4399
Eric Laurent054d9d32015-04-24 08:48:48 -07004400status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4401{
Andy Hungf60abce2016-08-26 11:37:54 -07004402 status_t status;
4403 if (property_get_bool("af.patch_park", false /* default_value */)) {
4404 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4405 // or if HAL does not properly lock against access.
4406 AutoPark<FastMixer> park(mFastMixer);
4407 status = PlaybackThread::releaseAudioPatch_l(handle);
4408 } else {
4409 status = PlaybackThread::releaseAudioPatch_l(handle);
4410 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004411 return status;
4412}
4413
Eric Laurent1c333e22014-05-20 10:48:17 -07004414status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4415{
4416 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004417
jiabinc52b1ff2019-10-31 17:20:42 -07004418 mPatch = audio_patch{};
4419 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004420
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004421 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004422 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4423 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004424 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004425 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004426 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004427 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004428 }
4429 return status;
4430}
4431
Eric Laurent83b88082014-06-20 18:31:16 -07004432void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4433{
4434 Mutex::Autolock _l(mLock);
4435 mTracks.add(track);
4436}
4437
4438void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4439{
4440 Mutex::Autolock _l(mLock);
4441 destroyTrack_l(track);
4442}
4443
Mikhail Naganovdc769682018-05-04 15:34:08 -07004444void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004445{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004446 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004447 config->role = AUDIO_PORT_ROLE_SOURCE;
4448 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4449 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004450 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4451 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4452 config->flags.output = mOutput->flags;
4453 }
Eric Laurent83b88082014-06-20 18:31:16 -07004454}
4455
Eric Laurent81784c32012-11-19 14:55:58 -08004456// ----------------------------------------------------------------------------
4457
4458AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004459 audio_io_handle_t id, bool systemReady, type_t type)
4460 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004461 // mAudioMixer below
4462 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004463 mFastMixerFutex(0),
4464 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004465 // mOutputSink below
4466 // mPipeSink below
4467 // mNormalSink below
4468{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004469 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004470 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004471 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004472 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004473 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4474 mNormalFrameCount);
4475 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4476
Andy Hungfbfc3952015-01-15 13:33:51 -08004477 if (type == DUPLICATING) {
4478 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4479 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4480 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4481 return;
4482 }
Eric Laurent81784c32012-11-19 14:55:58 -08004483 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004484 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004485 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004486 const NBAIO_Format offers[1] = {Format_from_SR_C(
4487 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004488#if !LOG_NDEBUG
4489 ssize_t index =
4490#else
4491 (void)
4492#endif
4493 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004494 ALOG_ASSERT(index == 0);
4495
4496 // initialize fast mixer depending on configuration
4497 bool initFastMixer;
4498 switch (kUseFastMixer) {
4499 case FastMixer_Never:
4500 initFastMixer = false;
4501 break;
4502 case FastMixer_Always:
4503 initFastMixer = true;
4504 break;
4505 case FastMixer_Static:
4506 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004507 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4508 // where the period is less than an experimentally determined threshold that can be
4509 // scheduled reliably with CFS. However, the BT A2DP HAL is
4510 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4511 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004512 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004513 break;
4514 }
Andy Hungfda69402017-02-15 14:33:12 -08004515 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4516 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4517 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004518 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004519 audio_format_t fastMixerFormat;
4520 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4521 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4522 } else {
4523 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4524 }
4525 if (mFormat != fastMixerFormat) {
4526 // change our Sink format to accept our intermediate precision
4527 mFormat = fastMixerFormat;
4528 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004529 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004530 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4531 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4532 }
Eric Laurent81784c32012-11-19 14:55:58 -08004533
4534 // create a MonoPipe to connect our submix to FastMixer
4535 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004536
Andy Hung1258c1a2014-05-23 21:22:17 -07004537 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004538 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004539 format.mFormat = fastMixerFormat;
4540 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4541
Eric Laurent81784c32012-11-19 14:55:58 -08004542 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4543 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4544 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4545 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4546 const NBAIO_Format offers[1] = {format};
4547 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004548#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004549 ssize_t index =
4550#else
4551 (void)
4552#endif
4553 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004554 ALOG_ASSERT(index == 0);
4555 monoPipe->setAvgFrames((mScreenState & 1) ?
4556 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4557 mPipeSink = monoPipe;
4558
Eric Laurent81784c32012-11-19 14:55:58 -08004559 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004560 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004561 FastMixerStateQueue *sq = mFastMixer->sq();
4562#ifdef STATE_QUEUE_DUMP
4563 sq->setObserverDump(&mStateQueueObserverDump);
4564 sq->setMutatorDump(&mStateQueueMutatorDump);
4565#endif
4566 FastMixerState *state = sq->begin();
4567 FastTrack *fastTrack = &state->mFastTracks[0];
4568 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4569 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4570 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004571 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4572 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4573 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004574 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004575 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004576 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004577 fastTrack->mGeneration++;
4578 state->mFastTracksGen++;
4579 state->mTrackMask = 1;
4580 // fast mixer will use the HAL output sink
4581 state->mOutputSink = mOutputSink.get();
4582 state->mOutputSinkGen++;
4583 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004584 // specify sink channel mask when haptic channel mask present as it can not
4585 // be calculated directly from channel count
4586 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004587 ? AUDIO_CHANNEL_NONE
4588 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004589 state->mCommand = FastMixerState::COLD_IDLE;
4590 // already done in constructor initialization list
4591 //mFastMixerFutex = 0;
4592 state->mColdFutexAddr = &mFastMixerFutex;
4593 state->mColdGen++;
4594 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004595 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4596 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004597 sq->end();
4598 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4599
Eric Tan0513b5d2018-09-17 10:32:48 -07004600 NBLog::thread_info_t info;
4601 info.id = mId;
4602 info.type = NBLog::FASTMIXER;
4603 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4604
Eric Laurent81784c32012-11-19 14:55:58 -08004605 // start the fast mixer
4606 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4607 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004608 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004609 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004610
4611#ifdef AUDIO_WATCHDOG
4612 // create and start the watchdog
4613 mAudioWatchdog = new AudioWatchdog();
4614 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4615 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4616 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004617 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004618#endif
Andy Hung8946a282018-04-19 20:04:56 -07004619 } else {
4620#ifdef TEE_SINK
4621 // Only use the MixerThread tee if there is no FastMixer.
4622 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4623 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4624#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004625 }
4626
4627 switch (kUseFastMixer) {
4628 case FastMixer_Never:
4629 case FastMixer_Dynamic:
4630 mNormalSink = mOutputSink;
4631 break;
4632 case FastMixer_Always:
4633 mNormalSink = mPipeSink;
4634 break;
4635 case FastMixer_Static:
4636 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4637 break;
4638 }
4639}
4640
4641AudioFlinger::MixerThread::~MixerThread()
4642{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004643 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004644 FastMixerStateQueue *sq = mFastMixer->sq();
4645 FastMixerState *state = sq->begin();
4646 if (state->mCommand == FastMixerState::COLD_IDLE) {
4647 int32_t old = android_atomic_inc(&mFastMixerFutex);
4648 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004649 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004650 }
4651 }
4652 state->mCommand = FastMixerState::EXIT;
4653 sq->end();
4654 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4655 mFastMixer->join();
4656 // Though the fast mixer thread has exited, it's state queue is still valid.
4657 // We'll use that extract the final state which contains one remaining fast track
4658 // corresponding to our sub-mix.
4659 state = sq->begin();
4660 ALOG_ASSERT(state->mTrackMask == 1);
4661 FastTrack *fastTrack = &state->mFastTracks[0];
4662 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4663 delete fastTrack->mBufferProvider;
4664 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004665 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004666#ifdef AUDIO_WATCHDOG
4667 if (mAudioWatchdog != 0) {
4668 mAudioWatchdog->requestExit();
4669 mAudioWatchdog->requestExitAndWait();
4670 mAudioWatchdog.clear();
4671 }
4672#endif
4673 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004674 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004675 delete mAudioMixer;
4676}
4677
4678
4679uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4680{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004681 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004682 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4683 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4684 }
4685 return latency;
4686}
4687
Eric Laurentbfb1b832013-01-07 09:53:42 -08004688ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004689{
4690 // FIXME we should only do one push per cycle; confirm this is true
4691 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004692 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004693 FastMixerStateQueue *sq = mFastMixer->sq();
4694 FastMixerState *state = sq->begin();
4695 if (state->mCommand != FastMixerState::MIX_WRITE &&
4696 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4697 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004698
4699 // FIXME workaround for first HAL write being CPU bound on some devices
4700 ATRACE_BEGIN("write");
4701 mOutput->write((char *)mSinkBuffer, 0);
4702 ATRACE_END();
4703
Eric Laurent81784c32012-11-19 14:55:58 -08004704 int32_t old = android_atomic_inc(&mFastMixerFutex);
4705 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004706 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004707 }
4708#ifdef AUDIO_WATCHDOG
4709 if (mAudioWatchdog != 0) {
4710 mAudioWatchdog->resume();
4711 }
4712#endif
4713 }
4714 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004715#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004716 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004717 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004718#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004719 sq->end();
4720 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4721 if (kUseFastMixer == FastMixer_Dynamic) {
4722 mNormalSink = mPipeSink;
4723 }
4724 } else {
4725 sq->end(false /*didModify*/);
4726 }
4727 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004728 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004729}
4730
4731void AudioFlinger::MixerThread::threadLoop_standby()
4732{
4733 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004734 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004735 FastMixerStateQueue *sq = mFastMixer->sq();
4736 FastMixerState *state = sq->begin();
4737 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004738 // Report any frames trapped in the Monopipe
4739 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4740 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4741 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4742 "monoPipeWritten:%lld monoPipeLeft:%lld",
4743 (long long)mFramesWritten, (long long)mSuspendedFrames,
4744 (long long)mPipeSink->framesWritten(), pipeFrames);
4745 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4746
Eric Laurent81784c32012-11-19 14:55:58 -08004747 state->mCommand = FastMixerState::COLD_IDLE;
4748 state->mColdFutexAddr = &mFastMixerFutex;
4749 state->mColdGen++;
4750 mFastMixerFutex = 0;
4751 sq->end();
4752 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4753 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4754 if (kUseFastMixer == FastMixer_Dynamic) {
4755 mNormalSink = mOutputSink;
4756 }
4757#ifdef AUDIO_WATCHDOG
4758 if (mAudioWatchdog != 0) {
4759 mAudioWatchdog->pause();
4760 }
4761#endif
4762 } else {
4763 sq->end(false /*didModify*/);
4764 }
4765 }
4766 PlaybackThread::threadLoop_standby();
4767}
4768
Eric Laurentbfb1b832013-01-07 09:53:42 -08004769bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4770{
4771 return false;
4772}
4773
4774bool AudioFlinger::PlaybackThread::shouldStandby_l()
4775{
4776 return !mStandby;
4777}
4778
4779bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4780{
4781 Mutex::Autolock _l(mLock);
4782 return waitingAsyncCallback_l();
4783}
4784
Eric Laurent81784c32012-11-19 14:55:58 -08004785// shared by MIXER and DIRECT, overridden by DUPLICATING
4786void AudioFlinger::PlaybackThread::threadLoop_standby()
4787{
4788 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004789 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004790 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004791 // discard any pending drain or write ack by incrementing sequence
4792 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4793 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004794 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004795 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4796 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004797 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004798 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004799}
4800
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004801void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4802{
4803 ALOGV("signal playback thread");
4804 broadcast_l();
4805}
4806
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004807void AudioFlinger::PlaybackThread::onAsyncError()
4808{
4809 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4810 invalidateTracks((audio_stream_type_t)i);
4811 }
4812}
4813
Eric Laurent81784c32012-11-19 14:55:58 -08004814void AudioFlinger::MixerThread::threadLoop_mix()
4815{
Eric Laurent81784c32012-11-19 14:55:58 -08004816 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004817 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004818 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004819 // increase sleep time progressively when application underrun condition clears.
4820 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4821 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4822 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004823 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004824 sleepTimeShift--;
4825 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004826 mSleepTimeUs = 0;
4827 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004828 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004829
Eric Laurent81784c32012-11-19 14:55:58 -08004830}
4831
4832void AudioFlinger::MixerThread::threadLoop_sleepTime()
4833{
4834 // If no tracks are ready, sleep once for the duration of an output
4835 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004836 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004837 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004838 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4839 // Using the Monopipe availableToWrite, we estimate the
4840 // sleep time to retry for more data (before we underrun).
4841 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4842 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4843 const size_t pipeFrames = monoPipe->maxFrames();
4844 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4845 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4846 const size_t framesDelay = std::min(
4847 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4848 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4849 pipeFrames, framesLeft, framesDelay);
4850 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4851 } else {
4852 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4853 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4854 mSleepTimeUs = kMinThreadSleepTimeUs;
4855 }
4856 // reduce sleep time in case of consecutive application underruns to avoid
4857 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4858 // duration we would end up writing less data than needed by the audio HAL if
4859 // the condition persists.
4860 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4861 sleepTimeShift++;
4862 }
Eric Laurent81784c32012-11-19 14:55:58 -08004863 }
4864 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004865 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004866 }
4867 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004868 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4869 // before effects processing or output.
4870 if (mMixerBufferValid) {
4871 memset(mMixerBuffer, 0, mMixerBufferSize);
4872 } else {
4873 memset(mSinkBuffer, 0, mSinkBufferSize);
4874 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004875 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004876 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4877 "anticipated start");
4878 }
4879 // TODO add standby time extension fct of effect tail
4880}
4881
4882// prepareTracks_l() must be called with ThreadBase::mLock held
4883AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4884 Vector< sp<Track> > *tracksToRemove)
4885{
Andy Hungc0691382018-09-12 18:01:57 -07004886 // clean up deleted track ids in AudioMixer before allocating new tracks
4887 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4888 // for each trackId, destroy it in the AudioMixer
4889 if (mAudioMixer->exists(trackId)) {
4890 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004891 }
4892 });
Andy Hungc0691382018-09-12 18:01:57 -07004893 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004894
4895 mixer_state mixerStatus = MIXER_IDLE;
4896 // find out which tracks need to be processed
4897 size_t count = mActiveTracks.size();
4898 size_t mixedTracks = 0;
4899 size_t tracksWithEffect = 0;
4900 // counts only _active_ fast tracks
4901 size_t fastTracks = 0;
4902 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4903
4904 float masterVolume = mMasterVolume;
4905 bool masterMute = mMasterMute;
4906
4907 if (masterMute) {
4908 masterVolume = 0;
4909 }
4910 // Delegate master volume control to effect in output mix effect chain if needed
4911 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4912 if (chain != 0) {
4913 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4914 chain->setVolume_l(&v, &v);
4915 masterVolume = (float)((v + (1 << 23)) >> 24);
4916 chain.clear();
4917 }
4918
4919 // prepare a new state to push
4920 FastMixerStateQueue *sq = NULL;
4921 FastMixerState *state = NULL;
4922 bool didModify = false;
4923 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004924 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004925 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004926 sq = mFastMixer->sq();
4927 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004928 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004929 }
4930
Andy Hung69aed5f2014-02-25 17:24:40 -08004931 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004932 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004933
Andy Hungbd3b2b02018-05-21 10:53:11 -07004934 // DeferredOperations handles statistics after setting mixerStatus.
4935 class DeferredOperations {
4936 public:
Andy Hungea840382020-05-05 21:50:17 -07004937 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4938 : mMixerStatus(mixerStatus)
4939 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004940
4941 // when leaving scope, tally frames properly.
4942 ~DeferredOperations() {
4943 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4944 // because that is when the underrun occurs.
4945 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004946 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004947 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004948 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004949 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004950 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004951 }
4952 }
Andy Hungea840382020-05-05 21:50:17 -07004953 // send the max underrun frames for this mixer period
4954 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004955 }
4956
4957 // tallyUnderrunFrames() is called to update the track counters
4958 // with the number of underrun frames for a particular mixer period.
4959 // We defer tallying until we know the final mixer status.
4960 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4961 mUnderrunFrames.emplace_back(track, underrunFrames);
4962 }
4963
4964 private:
4965 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004966 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004967 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004968 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004969 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004970
jiabin245cdd92018-12-07 17:55:15 -08004971 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004972 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004973 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004974
4975 // this const just means the local variable doesn't change
4976 Track* const track = t.get();
4977
4978 // process fast tracks
4979 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004980 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4981 "%s(%d): FastTrack(%d) present without FastMixer",
4982 __func__, id(), track->id());
4983
jiabin245cdd92018-12-07 17:55:15 -08004984 if (track->getHapticPlaybackEnabled()) {
4985 noFastHapticTrack = false;
4986 }
Eric Laurent81784c32012-11-19 14:55:58 -08004987
4988 // It's theoretically possible (though unlikely) for a fast track to be created
4989 // and then removed within the same normal mix cycle. This is not a problem, as
4990 // the track never becomes active so it's fast mixer slot is never touched.
4991 // The converse, of removing an (active) track and then creating a new track
4992 // at the identical fast mixer slot within the same normal mix cycle,
4993 // is impossible because the slot isn't marked available until the end of each cycle.
4994 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004995 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004996 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4997 FastTrack *fastTrack = &state->mFastTracks[j];
4998
4999 // Determine whether the track is currently in underrun condition,
5000 // and whether it had a recent underrun.
5001 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5002 FastTrackUnderruns underruns = ftDump->mUnderruns;
5003 uint32_t recentFull = (underruns.mBitFields.mFull -
5004 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5005 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5006 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5007 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5008 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5009 uint32_t recentUnderruns = recentPartial + recentEmpty;
5010 track->mObservedUnderruns = underruns;
5011 // don't count underruns that occur while stopping or pausing
5012 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005013 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005014 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5015 recentUnderruns > 0) {
5016 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005017 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005018 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005019 // Immediately account for FastTrack underruns.
5020 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005021
5022 // This is similar to the state machine for normal tracks,
5023 // with a few modifications for fast tracks.
5024 bool isActive = true;
5025 switch (track->mState) {
5026 case TrackBase::STOPPING_1:
5027 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005028 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005029 track->mState = TrackBase::STOPPING_2;
5030 }
5031 break;
5032 case TrackBase::PAUSING:
5033 // ramp down is not yet implemented
5034 track->setPaused();
5035 break;
5036 case TrackBase::RESUMING:
5037 // ramp up is not yet implemented
5038 track->mState = TrackBase::ACTIVE;
5039 break;
5040 case TrackBase::ACTIVE:
5041 if (recentFull > 0 || recentPartial > 0) {
5042 // track has provided at least some frames recently: reset retry count
5043 track->mRetryCount = kMaxTrackRetries;
5044 }
5045 if (recentUnderruns == 0) {
5046 // no recent underruns: stay active
5047 break;
5048 }
5049 // there has recently been an underrun of some kind
5050 if (track->sharedBuffer() == 0) {
5051 // were any of the recent underruns "empty" (no frames available)?
5052 if (recentEmpty == 0) {
5053 // no, then ignore the partial underruns as they are allowed indefinitely
5054 break;
5055 }
5056 // there has recently been an "empty" underrun: decrement the retry counter
5057 if (--(track->mRetryCount) > 0) {
5058 break;
5059 }
5060 // indicate to client process that the track was disabled because of underrun;
5061 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005062 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005063 // remove from active list, but state remains ACTIVE [confusing but true]
5064 isActive = false;
5065 break;
5066 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005067 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005068 case TrackBase::STOPPING_2:
5069 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005070 case TrackBase::STOPPED:
5071 case TrackBase::FLUSHED: // flush() while active
5072 // Check for presentation complete if track is inactive
5073 // We have consumed all the buffers of this track.
5074 // This would be incomplete if we auto-paused on underrun
5075 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005076 uint32_t latency = 0;
5077 status_t result = mOutput->stream->getLatency(&latency);
5078 ALOGE_IF(result != OK,
5079 "Error when retrieving output stream latency: %d", result);
5080 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005081 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005082 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5083 // track stays in active list until presentation is complete
5084 break;
5085 }
5086 }
5087 if (track->isStopping_2()) {
5088 track->mState = TrackBase::STOPPED;
5089 }
5090 if (track->isStopped()) {
5091 // Can't reset directly, as fast mixer is still polling this track
5092 // track->reset();
5093 // So instead mark this track as needing to be reset after push with ack
5094 resetMask |= 1 << i;
5095 }
5096 isActive = false;
5097 break;
5098 case TrackBase::IDLE:
5099 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005100 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005101 }
5102
5103 if (isActive) {
5104 // was it previously inactive?
5105 if (!(state->mTrackMask & (1 << j))) {
5106 ExtendedAudioBufferProvider *eabp = track;
5107 VolumeProvider *vp = track;
5108 fastTrack->mBufferProvider = eabp;
5109 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005110 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005111 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005112 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005113 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005114 fastTrack->mGeneration++;
5115 state->mTrackMask |= 1 << j;
5116 didModify = true;
5117 // no acknowledgement required for newly active tracks
5118 }
Kevin Rocard12381092018-04-11 09:19:59 -07005119 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005120 float volume;
5121 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5122 volume = 0.f;
5123 } else {
5124 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5125 }
5126
5127 handleVoipVolume_l(&volume);
5128
Eric Laurent81784c32012-11-19 14:55:58 -08005129 // cache the combined master volume and stream type volume for fast mixer; this
5130 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005131 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005132 proxy->framesReleased()).first;
5133 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005134 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005135 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5136 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5137 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005138
Kevin Rocard12381092018-04-11 09:19:59 -07005139 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005140 ++fastTracks;
5141 } else {
5142 // was it previously active?
5143 if (state->mTrackMask & (1 << j)) {
5144 fastTrack->mBufferProvider = NULL;
5145 fastTrack->mGeneration++;
5146 state->mTrackMask &= ~(1 << j);
5147 didModify = true;
5148 // If any fast tracks were removed, we must wait for acknowledgement
5149 // because we're about to decrement the last sp<> on those tracks.
5150 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5151 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005152 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5153 // AudioTrack may start (which may not be with a start() but with a write()
5154 // after underrun) and immediately paused or released. In that case the
5155 // FastTrack state hasn't had time to update.
5156 // TODO Remove the ALOGW when this theory is confirmed.
5157 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005158 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005159 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005160 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005161 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005162 }
5163 tracksToRemove->add(track);
5164 // Avoids a misleading display in dumpsys
5165 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5166 }
jiabin245cdd92018-12-07 17:55:15 -08005167 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5168 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5169 didModify = true;
5170 }
Eric Laurent81784c32012-11-19 14:55:58 -08005171 continue;
5172 }
5173
5174 { // local variable scope to avoid goto warning
5175
5176 audio_track_cblk_t* cblk = track->cblk();
5177
5178 // The first time a track is added we wait
5179 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005180 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005181
5182 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005183 // use the trackId as the AudioMixer name.
5184 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005185 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005186 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005187 track->mChannelMask,
5188 track->mFormat,
5189 track->mSessionId);
5190 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005191 ALOGW("%s(): AudioMixer cannot create track(%d)"
5192 " mask %#x, format %#x, sessionId %d",
5193 __func__, trackId,
5194 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005195 tracksToRemove->add(track);
5196 track->invalidate(); // consider it dead.
5197 continue;
5198 }
5199 }
5200
Eric Laurent81784c32012-11-19 14:55:58 -08005201 // make sure that we have enough frames to mix one full buffer.
5202 // enforce this condition only once to enable draining the buffer in case the client
5203 // app does not call stop() and relies on underrun to stop:
5204 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5205 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005206 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005207 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005208 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005209
5210 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005211 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005212 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5213 // add frames already consumed but not yet released by the resampler
5214 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005215 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005216
Eric Laurent81784c32012-11-19 14:55:58 -08005217 uint32_t minFrames = 1;
5218 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5219 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005220 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005221 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005222
5223 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005224 if (ATRACE_ENABLED()) {
5225 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005226 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005227 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005228 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005229 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005230 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005231 !track->isPaused() && !track->isTerminated())
5232 {
Andy Hungc0691382018-09-12 18:01:57 -07005233 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005234
5235 mixedTracks++;
5236
Andy Hung69aed5f2014-02-25 17:24:40 -08005237 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5238 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005239 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005240 if (track->mainBuffer() != mSinkBuffer &&
5241 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005242 if (mEffectBufferEnabled) {
5243 mEffectBufferValid = true; // Later can set directly.
5244 }
Eric Laurent81784c32012-11-19 14:55:58 -08005245 chain = getEffectChain_l(track->sessionId());
5246 // Delegate volume control to effect in track effect chain if needed
5247 if (chain != 0) {
5248 tracksWithEffect++;
5249 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005250 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005251 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005252 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005253 }
5254 }
5255
5256
5257 int param = AudioMixer::VOLUME;
5258 if (track->mFillingUpStatus == Track::FS_FILLED) {
5259 // no ramp for the first volume setting
5260 track->mFillingUpStatus = Track::FS_ACTIVE;
5261 if (track->mState == TrackBase::RESUMING) {
5262 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005263 // If a new track is paused immediately after start, do not ramp on resume.
5264 if (cblk->mServer != 0) {
5265 param = AudioMixer::RAMP_VOLUME;
5266 }
Eric Laurent81784c32012-11-19 14:55:58 -08005267 }
Andy Hungc0691382018-09-12 18:01:57 -07005268 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005269 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005270 // FIXME should not make a decision based on mServer
5271 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005272 // If the track is stopped before the first frame was mixed,
5273 // do not apply ramp
5274 param = AudioMixer::RAMP_VOLUME;
5275 }
5276
5277 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005278 uint32_t vl, vr; // in U8.24 integer format
5279 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005280 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005281 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005282 // Always fetch volumeshaper volume to ensure state is updated.
5283 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5284 const float vh = track->getVolumeHandler()->getVolume(
5285 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005286
Eric Laurenteab90452019-06-24 15:17:46 -07005287 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5288 v = 0;
5289 }
5290
5291 handleVoipVolume_l(&v);
5292
5293 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005294 vl = vr = 0;
5295 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005296 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005297 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005298 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005299 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5300 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005301 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005302 if (vlf > GAIN_FLOAT_UNITY) {
5303 ALOGV("Track left volume out of range: %.3g", vlf);
5304 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005305 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005306 if (vrf > GAIN_FLOAT_UNITY) {
5307 ALOGV("Track right volume out of range: %.3g", vrf);
5308 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005309 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005310 // now apply the master volume and stream type volume and shaper volume
5311 vlf *= v * vh;
5312 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005313 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005314 // then derive vl and vr as U8.24 versions for the effect chain
5315 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5316 vl = (uint32_t) (scaleto8_24 * vlf);
5317 vr = (uint32_t) (scaleto8_24 * vrf);
5318 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005319 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005320 // send level comes from shared memory and so may be corrupt
5321 if (sendLevel > MAX_GAIN_INT) {
5322 ALOGV("Track send level out of range: %04X", sendLevel);
5323 sendLevel = MAX_GAIN_INT;
5324 }
Andy Hung6be49402014-05-30 10:42:03 -07005325 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5326 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005327 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005328
Kevin Rocard12381092018-04-11 09:19:59 -07005329 track->setFinalVolume((vrf + vlf) / 2.f);
5330
Eric Laurent81784c32012-11-19 14:55:58 -08005331 // Delegate volume control to effect in track effect chain if needed
5332 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5333 // Do not ramp volume if volume is controlled by effect
5334 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005335 // Update remaining floating point volume levels
5336 vlf = (float)vl / (1 << 24);
5337 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005338 track->mHasVolumeController = true;
5339 } else {
5340 // force no volume ramp when volume controller was just disabled or removed
5341 // from effect chain to avoid volume spike
5342 if (track->mHasVolumeController) {
5343 param = AudioMixer::VOLUME;
5344 }
5345 track->mHasVolumeController = false;
5346 }
5347
Eric Laurent81784c32012-11-19 14:55:58 -08005348 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005349 mAudioMixer->setBufferProvider(trackId, track);
5350 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005351
Andy Hungc0691382018-09-12 18:01:57 -07005352 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5353 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5354 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005355 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005356 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005357 AudioMixer::TRACK,
5358 AudioMixer::FORMAT, (void *)track->format());
5359 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005360 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005361 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005362 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005363 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005364 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005365 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005366 AudioMixer::MIXER_CHANNEL_MASK,
5367 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005368 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005369 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005370 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005371 if (reqSampleRate == 0) {
5372 reqSampleRate = mSampleRate;
5373 } else if (reqSampleRate > maxSampleRate) {
5374 reqSampleRate = maxSampleRate;
5375 }
Eric Laurent81784c32012-11-19 14:55:58 -08005376 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005377 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005378 AudioMixer::RESAMPLE,
5379 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005380 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005381
Andy Hung333ab962019-05-28 20:23:35 -07005382 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005383 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005384 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005385 AudioMixer::TIMESTRETCH,
5386 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005387 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005388
Andy Hung69aed5f2014-02-25 17:24:40 -08005389 /*
5390 * Select the appropriate output buffer for the track.
5391 *
Andy Hung98ef9782014-03-04 14:46:50 -08005392 * Tracks with effects go into their own effects chain buffer
5393 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005394 *
5395 * Other tracks can use mMixerBuffer for higher precision
5396 * channel accumulation. If this buffer is enabled
5397 * (mMixerBufferEnabled true), then selected tracks will accumulate
5398 * into it.
5399 *
5400 */
5401 if (mMixerBufferEnabled
5402 && (track->mainBuffer() == mSinkBuffer
5403 || track->mainBuffer() == mMixerBuffer)) {
5404 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005405 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005406 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005407 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005408 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005409 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005410 AudioMixer::TRACK,
5411 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5412 // TODO: override track->mainBuffer()?
5413 mMixerBufferValid = true;
5414 } else {
5415 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005416 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005417 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005418 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005419 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005420 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005421 AudioMixer::TRACK,
5422 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5423 }
Eric Laurent81784c32012-11-19 14:55:58 -08005424 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005425 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005426 AudioMixer::TRACK,
5427 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005428 mAudioMixer->setParameter(
5429 trackId,
5430 AudioMixer::TRACK,
5431 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005432 mAudioMixer->setParameter(
5433 trackId,
5434 AudioMixer::TRACK,
5435 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005436
5437 // reset retry count
5438 track->mRetryCount = kMaxTrackRetries;
5439
5440 // If one track is ready, set the mixer ready if:
5441 // - the mixer was not ready during previous round OR
5442 // - no other track is not ready
5443 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5444 mixerStatus != MIXER_TRACKS_ENABLED) {
5445 mixerStatus = MIXER_TRACKS_READY;
5446 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005447
5448 // Enable the next few lines to instrument a test for underrun log handling.
5449 // TODO: Remove when we have a better way of testing the underrun log.
5450#if 0
5451 static int i;
5452 if ((++i & 0xf) == 0) {
5453 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5454 }
5455#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005456 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005457 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005458 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005459 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5460 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005461 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005462 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005463 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005464
Eric Laurent81784c32012-11-19 14:55:58 -08005465 // clear effect chain input buffer if an active track underruns to avoid sending
5466 // previous audio buffer again to effects
5467 chain = getEffectChain_l(track->sessionId());
5468 if (chain != 0) {
5469 chain->clearInputBuffer();
5470 }
5471
Andy Hungc0691382018-09-12 18:01:57 -07005472 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005473 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5474 track->isStopped() || track->isPaused()) {
5475 // We have consumed all the buffers of this track.
5476 // Remove it from the list of active tracks.
5477 // TODO: use actual buffer filling status instead of latency when available from
5478 // audio HAL
5479 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005480 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005481 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5482 if (track->isStopped()) {
5483 track->reset();
5484 }
5485 tracksToRemove->add(track);
5486 }
5487 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005488 // No buffers for this track. Give it a few chances to
5489 // fill a buffer, then remove it from active list.
5490 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005491 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5492 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005493 tracksToRemove->add(track);
5494 // indicate to client process that the track was disabled because of underrun;
5495 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005496 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005497 // If one track is not ready, mark the mixer also not ready if:
5498 // - the mixer was ready during previous round OR
5499 // - no other track is ready
5500 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5501 mixerStatus != MIXER_TRACKS_READY) {
5502 mixerStatus = MIXER_TRACKS_ENABLED;
5503 }
5504 }
Andy Hungc0691382018-09-12 18:01:57 -07005505 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005506 }
5507
5508 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005509
5510 }
5511
jiabin245cdd92018-12-07 17:55:15 -08005512 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5513 // When there is no fast track playing haptic and FastMixer exists,
5514 // enabling the first FastTrack, which provides mixed data from normal
5515 // tracks, to play haptic data.
5516 FastTrack *fastTrack = &state->mFastTracks[0];
5517 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5518 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5519 didModify = true;
5520 }
5521 }
5522
Eric Laurent81784c32012-11-19 14:55:58 -08005523 // Push the new FastMixer state if necessary
5524 bool pauseAudioWatchdog = false;
5525 if (didModify) {
5526 state->mFastTracksGen++;
5527 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5528 if (kUseFastMixer == FastMixer_Dynamic &&
5529 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5530 state->mCommand = FastMixerState::COLD_IDLE;
5531 state->mColdFutexAddr = &mFastMixerFutex;
5532 state->mColdGen++;
5533 mFastMixerFutex = 0;
5534 if (kUseFastMixer == FastMixer_Dynamic) {
5535 mNormalSink = mOutputSink;
5536 }
5537 // If we go into cold idle, need to wait for acknowledgement
5538 // so that fast mixer stops doing I/O.
5539 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5540 pauseAudioWatchdog = true;
5541 }
Eric Laurent81784c32012-11-19 14:55:58 -08005542 }
5543 if (sq != NULL) {
5544 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005545 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5546 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5547 // when bringing the output sink into standby.)
5548 //
5549 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5550 //
5551 // This occurs with BT suspend when we idle the FastMixer with
5552 // active tracks, which may be added or removed.
5553 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005554 }
5555#ifdef AUDIO_WATCHDOG
5556 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5557 mAudioWatchdog->pause();
5558 }
5559#endif
5560
5561 // Now perform the deferred reset on fast tracks that have stopped
5562 while (resetMask != 0) {
5563 size_t i = __builtin_ctz(resetMask);
5564 ALOG_ASSERT(i < count);
5565 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005566 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005567 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5568 track->reset();
5569 }
5570
Andy Hung80d03d22018-04-10 10:32:11 -07005571 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5572 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5573 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5574 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5575 // See also the implementation of destroyTrack_l().
5576 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005577 const int trackId = track->id();
5578 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5579 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005580 }
5581 }
5582
Eric Laurent81784c32012-11-19 14:55:58 -08005583 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005584 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005585
Eric Laurent97d547d2014-09-02 14:45:53 -07005586 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5587 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005588 }
5589
5590 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005591 // as long as there are effects we should clear the effects buffer, to avoid
5592 // passing a non-clean buffer to the effect chain
5593 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005594 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005595 // sink or mix buffer must be cleared if all tracks are connected to an
5596 // effect chain as in this case the mixer will not write to the sink or mix buffer
5597 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005598 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5599 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005600 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005601 if (mMixerBufferValid) {
5602 memset(mMixerBuffer, 0, mMixerBufferSize);
5603 // TODO: In testing, mSinkBuffer below need not be cleared because
5604 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5605 // after mixing.
5606 //
5607 // To enforce this guarantee:
5608 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5609 // (mixedTracks == 0 && fastTracks > 0))
5610 // must imply MIXER_TRACKS_READY.
5611 // Later, we may clear buffers regardless, and skip much of this logic.
5612 }
Andy Hung98ef9782014-03-04 14:46:50 -08005613 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005614 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005615 }
5616
5617 // if any fast tracks, then status is ready
5618 mMixerStatusIgnoringFastTracks = mixerStatus;
5619 if (fastTracks > 0) {
5620 mixerStatus = MIXER_TRACKS_READY;
5621 }
5622 return mixerStatus;
5623}
5624
Eric Laurentad7dd962016-09-22 12:38:37 -07005625// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005626uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005627{
5628 uint32_t trackCount = 0;
5629 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005630 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005631 trackCount++;
5632 }
5633 }
5634 return trackCount;
5635}
5636
ziyangch09204bd2021-12-01 13:48:04 -08005637bool AudioFlinger::PlaybackThread::checkRunningTimestamp()
5638{
5639 uint64_t position = 0;
5640 struct timespec unused;
5641 const status_t ret = mOutput->getPresentationPosition(&position, &unused);
5642 if (ret == NO_ERROR) {
5643 if (position != mLastCheckedTimestampPosition) {
5644 mLastCheckedTimestampPosition = position;
5645 return true;
5646 }
5647 }
5648 return false;
5649}
5650
Andy Hung1bc088a2018-02-09 15:57:31 -08005651// isTrackAllowed_l() must be called with ThreadBase::mLock held
5652bool AudioFlinger::MixerThread::isTrackAllowed_l(
5653 audio_channel_mask_t channelMask, audio_format_t format,
5654 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005655{
Andy Hung1bc088a2018-02-09 15:57:31 -08005656 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5657 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005658 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005659 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005660 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005661 ALOGW("%s: invalid format: %#x", __func__, format);
5662 return false;
5663 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005664 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005665 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5666 return false;
5667 }
5668 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005669}
5670
Eric Laurent10351942014-05-08 18:49:52 -07005671// checkForNewParameter_l() must be called with ThreadBase::mLock held
5672bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5673 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005674{
Eric Laurent81784c32012-11-19 14:55:58 -08005675 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005676 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005677
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005678 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005679
Eric Laurent10351942014-05-08 18:49:52 -07005680 AudioParameter param = AudioParameter(keyValuePair);
5681 int value;
5682 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5683 reconfig = true;
5684 }
5685 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005686 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005687 status = BAD_VALUE;
5688 } else {
5689 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005690 reconfig = true;
5691 }
Eric Laurent10351942014-05-08 18:49:52 -07005692 }
5693 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005694 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005695 status = BAD_VALUE;
5696 } else {
5697 // no need to save value, since it's constant
5698 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005699 }
Eric Laurent10351942014-05-08 18:49:52 -07005700 }
5701 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5702 // do not accept frame count changes if tracks are open as the track buffer
5703 // size depends on frame count and correct behavior would not be guaranteed
5704 // if frame count is changed after track creation
5705 if (!mTracks.isEmpty()) {
5706 status = INVALID_OPERATION;
5707 } else {
5708 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005709 }
Eric Laurent10351942014-05-08 18:49:52 -07005710 }
5711 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005712 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005713 }
Eric Laurent81784c32012-11-19 14:55:58 -08005714
Eric Laurent10351942014-05-08 18:49:52 -07005715 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005716 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005717 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005718 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005719 if (!mStandby) {
5720 mThreadMetrics.logEndInterval();
5721 mStandby = true;
5722 }
Eric Laurent10351942014-05-08 18:49:52 -07005723 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005724 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005725 }
Eric Laurent10351942014-05-08 18:49:52 -07005726 if (status == NO_ERROR && reconfig) {
5727 readOutputParameters_l();
5728 delete mAudioMixer;
5729 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005730 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005731 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005732 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005733 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005734 track->mChannelMask,
5735 track->mFormat,
5736 track->mSessionId);
5737 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005738 "%s(): AudioMixer cannot create track(%d)"
5739 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005740 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005741 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005742 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005743 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005744 }
Eric Laurent81784c32012-11-19 14:55:58 -08005745 }
5746
Dean Wheatley68918102021-03-19 22:09:19 +11005747 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005748}
5749
5750
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005751void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005752{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005753 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005754 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005755 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005756 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005757 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5758 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5759 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005760 if (hasFastMixer()) {
5761 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5762
5763 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5764 // while we are dumping it. It may be inconsistent, but it won't mutate!
5765 // This is a large object so we place it on the heap.
5766 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005767 const std::unique_ptr<FastMixerDumpState> copy =
5768 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005769 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005770
5771#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005772 // Similar for state queue
5773 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5774 observerCopy.dump(fd);
5775 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5776 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005777#endif
5778
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005779#ifdef AUDIO_WATCHDOG
5780 if (mAudioWatchdog != 0) {
5781 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5782 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5783 wdCopy.dump(fd);
5784 }
5785#endif
5786
5787 } else {
5788 dprintf(fd, " No FastMixer\n");
5789 }
Eric Laurent81784c32012-11-19 14:55:58 -08005790}
5791
5792uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5793{
5794 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5795}
5796
5797uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5798{
5799 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5800}
5801
5802void AudioFlinger::MixerThread::cacheParameters_l()
5803{
5804 PlaybackThread::cacheParameters_l();
5805
5806 // FIXME: Relaxed timing because of a certain device that can't meet latency
5807 // Should be reduced to 2x after the vendor fixes the driver issue
5808 // increase threshold again due to low power audio mode. The way this warning
5809 // threshold is calculated and its usefulness should be reconsidered anyway.
5810 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5811}
5812
5813// ----------------------------------------------------------------------------
5814
5815AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005816 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5817 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005818{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005819 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005820}
5821
Eric Laurent81784c32012-11-19 14:55:58 -08005822AudioFlinger::DirectOutputThread::~DirectOutputThread()
5823{
5824}
5825
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005826void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005827{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005828 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005829 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5830 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5831}
5832
5833void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5834{
5835 Mutex::Autolock _l(mLock);
5836 if (mMasterBalance != balance) {
5837 mMasterBalance.store(balance);
5838 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5839 broadcast_l();
5840 }
5841}
5842
Eric Laurent5850c4c2016-11-10 13:04:31 -08005843void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005844{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005845 float left, right;
5846
Andy Hung333ab962019-05-28 20:23:35 -07005847 // Ensure volumeshaper state always advances even when muted.
5848 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5849 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5850 proxy->framesReleased());
5851 mVolumeShaperActive = shaperActive;
5852
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005853 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005854 left = right = 0;
5855 } else {
5856 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005857 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005858
Glenn Kastenc56f3422014-03-21 17:53:17 -07005859 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5860 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5861 if (left > GAIN_FLOAT_UNITY) {
5862 left = GAIN_FLOAT_UNITY;
5863 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005864 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005865 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5866 if (right > GAIN_FLOAT_UNITY) {
5867 right = GAIN_FLOAT_UNITY;
5868 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005869 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005870 }
5871
5872 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005873 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005874 if (left != mLeftVolFloat || right != mRightVolFloat) {
5875 mLeftVolFloat = left;
5876 mRightVolFloat = right;
5877
Eric Laurentbfb1b832013-01-07 09:53:42 -08005878 // Delegate volume control to effect in track effect chain if needed
5879 // only one effect chain can be present on DirectOutputThread, so if
5880 // there is one, the track is connected to it
5881 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005882 // if effect chain exists, volume is handled by it.
5883 // Convert volumes from float to 8.24
5884 uint32_t vl = (uint32_t)(left * (1 << 24));
5885 uint32_t vr = (uint32_t)(right * (1 << 24));
5886 // Direct/Offload effect chains set output volume in setVolume_l().
5887 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5888 } else {
5889 // otherwise we directly set the volume.
5890 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005891 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005892 }
5893 }
5894}
5895
Phil Burk43b4dcc2015-06-09 16:53:44 -07005896void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5897{
5898 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005899 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005900
Eric Laurent0f0631e2015-07-06 18:01:25 -07005901 if (previousTrack != 0 && latestTrack != 0) {
5902 if (mType == DIRECT) {
5903 if (previousTrack.get() != latestTrack.get()) {
5904 mFlushPending = true;
5905 }
5906 } else /* mType == OFFLOAD */ {
5907 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5908 mFlushPending = true;
5909 }
5910 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005911 } else if (previousTrack == 0) {
5912 // there could be an old track added back during track transition for direct
5913 // output, so always issues flush to flush data of the previous track if it
5914 // was already destroyed with HAL paused, then flush can resume the playback
5915 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005916 }
5917 PlaybackThread::onAddNewTrack_l();
5918}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005919
Eric Laurent81784c32012-11-19 14:55:58 -08005920AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5921 Vector< sp<Track> > *tracksToRemove
5922)
5923{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005924 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005925 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005926 bool doHwPause = false;
5927 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005928
5929 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005930 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005931 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005932 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005933 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005934 continue;
5935 }
5936
Eric Laurent5850c4c2016-11-10 13:04:31 -08005937 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005938#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005939 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005940#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005941 // Only consider last track started for volume and mixer state control.
5942 // In theory an older track could underrun and restart after the new one starts
5943 // but as we only care about the transition phase between two tracks on a
5944 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005945 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005946 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005947
Kuowei Li23666472021-01-20 10:23:25 +08005948 if (track->isPausePending()) {
5949 track->pauseAck();
5950 // It is possible a track might have been flushed or stopped.
5951 // Other operations such as flush pending might occur on the next prepare.
5952 if (track->isPausing()) {
5953 track->setPaused();
5954 }
5955 // Always perform pause, as an immediate flush will change
5956 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005957 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005958 doHwPause = true;
5959 mHwPaused = true;
5960 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005961 } else if (track->isFlushPending()) {
5962 track->flushAck();
5963 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005964 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005965 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005966 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005967 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005968 if (last) {
5969 mLeftVolFloat = mRightVolFloat = -1.0;
5970 if (mHwPaused) {
5971 doHwResume = true;
5972 mHwPaused = false;
5973 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005974 }
5975 }
5976
Eric Laurent81784c32012-11-19 14:55:58 -08005977 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005978 // for all its buffers to be filled before processing it.
5979 // Allow draining the buffer in case the client
5980 // app does not call stop() and relies on underrun to stop:
5981 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07005982 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
5983 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
5984 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07005985 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07005986
5987 // target retry count that we will use is based on the time we wait for retries.
5988 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
5989 // the retry threshold is when we accept any size for PCM data. This is slightly
5990 // smaller than the retry count so we can push small bits of data without a glitch.
5991 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08005992 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005993 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07005994 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005995 minFrames = mNormalFrameCount;
5996 } else {
5997 minFrames = 1;
5998 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005999
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006000 const size_t framesReady = track->framesReady();
6001 const int trackId = track->id();
6002 if (ATRACE_ENABLED()) {
6003 std::string traceName("nRdy");
6004 traceName += std::to_string(trackId);
6005 ATRACE_INT(traceName.c_str(), framesReady);
6006 }
6007 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006008 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006009 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006010 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006011
6012 if (track->mFillingUpStatus == Track::FS_FILLED) {
6013 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006014 if (last) {
6015 // make sure processVolume_l() will apply new volume even if 0
6016 mLeftVolFloat = mRightVolFloat = -1.0;
6017 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006018 if (!mHwSupportsPause) {
6019 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006020 }
6021 }
6022
6023 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006024 processVolume_l(track, last);
6025 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006026 sp<Track> previousTrack = mPreviousTrack.promote();
6027 if (previousTrack != 0) {
6028 if (track != previousTrack.get()) {
6029 // Flush any data still being written from last track
6030 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006031 // Invalidate previous track to force a seek when resuming.
6032 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006033 }
6034 }
6035 mPreviousTrack = track;
6036
Eric Laurentd595b7c2013-04-03 17:27:56 -07006037 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006038 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006039 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006040 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006041 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006042 doHwResume = true;
6043 mHwPaused = false;
6044 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006045 }
Eric Laurent81784c32012-11-19 14:55:58 -08006046 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006047 // clear effect chain input buffer if the last active track started underruns
6048 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006049 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006050 mEffectChains[0]->clearInputBuffer();
6051 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006052 if (track->isStopping_1()) {
6053 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006054 if (last && mHwPaused) {
6055 doHwResume = true;
6056 mHwPaused = false;
6057 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006058 }
6059 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6060 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006061 // We have consumed all the buffers of this track.
6062 // Remove it from the list of active tracks.
Eric Laurentfd477972013-10-25 18:10:40 -07006063 if (mStandby || !last ||
Andy Hung59de4262021-06-14 10:53:54 -07006064 track->presentationComplete(latency_l()) ||
Jindong32dc26e2019-11-11 18:10:01 +08006065 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006066 if (track->isStopping_2()) {
6067 track->mState = TrackBase::STOPPED;
6068 }
Eric Laurent81784c32012-11-19 14:55:58 -08006069 if (track->isStopped()) {
6070 track->reset();
6071 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006072 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006073 }
6074 } else {
6075 // No buffers for this track. Give it a few chances to
6076 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006077 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006078 if (--(track->mRetryCount) <= 0) {
ziyangch09204bd2021-12-01 13:48:04 -08006079 const bool running = checkRunningTimestamp();
6080 if (running) { // still running, give us more time.
6081 track->mRetryCount = kMaxTrackRetriesOffload;
6082 } else {
6083 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6084 tracksToRemove->add(track);
6085 // indicate to client process that the track was disabled because of
6086 // underrun; it will then automatically call start() when data is available
6087 track->disable();
6088 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6089 // unlike mixerthread, HAL can be paused for direct output
6090 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6091 "minFrames = %u, mFormat = %#x",
6092 framesReady, minFrames, mFormat);
6093 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6094 doHwPause = true;
6095 mHwPaused = true;
6096 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006097 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006098 } else if (last) {
6099 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006100 }
6101 }
6102 }
6103 }
6104
Eric Laurentd1f69b02014-12-15 14:33:13 -08006105 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006106 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006107 for (size_t i = 0; i < mTracks.size(); i++) {
6108 if (mTracks[i]->isFlushPending()) {
6109 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006110 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006111 }
6112 }
6113 }
6114
6115 // make sure the pause/flush/resume sequence is executed in the right order.
6116 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6117 // before flush and then resume HW. This can happen in case of pause/flush/resume
6118 // if resume is received before pause is executed.
6119 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006120 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006121 status_t result = mOutput->stream->pause();
6122 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006123 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006124 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006125 flushHw_l();
6126 }
6127 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006128 status_t result = mOutput->stream->resume();
6129 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006130 }
Eric Laurent81784c32012-11-19 14:55:58 -08006131 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006132 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006133
6134 return mixerStatus;
6135}
6136
6137void AudioFlinger::DirectOutputThread::threadLoop_mix()
6138{
Eric Laurent81784c32012-11-19 14:55:58 -08006139 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006140 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006141 // output audio to hardware
6142 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006143 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006144 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006145 status_t status = mActiveTrack->getNextBuffer(&buffer);
6146 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006147 // no need to pad with 0 for compressed audio
6148 if (audio_has_proportional_frames(mFormat)) {
6149 memset(curBuf, 0, frameCount * mFrameSize);
6150 }
Eric Laurent81784c32012-11-19 14:55:58 -08006151 break;
6152 }
6153 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6154 frameCount -= buffer.frameCount;
6155 curBuf += buffer.frameCount * mFrameSize;
6156 mActiveTrack->releaseBuffer(&buffer);
6157 }
Andy Hung2098f272014-02-27 14:00:06 -08006158 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006159 mSleepTimeUs = 0;
6160 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006161 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006162}
6163
6164void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6165{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006166 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006167 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006168 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006169 return;
6170 }
Andy Hung85ba3332021-04-27 17:40:26 -07006171 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6172 mSleepTimeUs = mActiveSleepTimeUs;
6173 } else {
6174 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006175 }
Andy Hung85ba3332021-04-27 17:40:26 -07006176 // Note: In S or later, we do not write zeroes for
6177 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006178}
6179
Eric Laurentd1f69b02014-12-15 14:33:13 -08006180void AudioFlinger::DirectOutputThread::threadLoop_exit()
6181{
6182 {
6183 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006184 for (size_t i = 0; i < mTracks.size(); i++) {
6185 if (mTracks[i]->isFlushPending()) {
6186 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006187 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006188 }
6189 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006190 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006191 flushHw_l();
6192 }
6193 }
6194 PlaybackThread::threadLoop_exit();
6195}
6196
6197// must be called with thread mutex locked
6198bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6199{
6200 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006201 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006202
6203 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6204 // after a timeout and we will enter standby then.
6205 if (mTracks.size() > 0) {
6206 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006207 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6208 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006209 }
6210
Eric Laurent5cff4032015-05-26 13:49:58 -07006211 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006212}
6213
Eric Laurent10351942014-05-08 18:49:52 -07006214// checkForNewParameter_l() must be called with ThreadBase::mLock held
6215bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6216 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006217{
6218 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006219 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006220
Eric Laurent10351942014-05-08 18:49:52 -07006221 AudioParameter param = AudioParameter(keyValuePair);
6222 int value;
6223 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006224 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006225 }
Eric Laurent10351942014-05-08 18:49:52 -07006226 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6227 // do not accept frame count changes if tracks are open as the track buffer
6228 // size depends on frame count and correct behavior would not be garantied
6229 // if frame count is changed after track creation
6230 if (!mTracks.isEmpty()) {
6231 status = INVALID_OPERATION;
6232 } else {
6233 reconfig = true;
6234 }
6235 }
6236 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006237 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006238 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006239 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006240 if (!mStandby) {
6241 mThreadMetrics.logEndInterval();
6242 mStandby = true;
6243 }
Eric Laurent10351942014-05-08 18:49:52 -07006244 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006245 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006246 }
6247 if (status == NO_ERROR && reconfig) {
6248 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006249 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006250 }
6251 }
6252
Dean Wheatley68918102021-03-19 22:09:19 +11006253 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006254}
6255
6256uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6257{
6258 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006259 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006260 time = PlaybackThread::activeSleepTimeUs();
6261 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006262 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006263 }
6264 return time;
6265}
6266
6267uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6268{
6269 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006270 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006271 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6272 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006273 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006274 }
6275 return time;
6276}
6277
6278uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6279{
6280 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006281 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006282 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6283 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006284 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006285 }
6286 return time;
6287}
6288
6289void AudioFlinger::DirectOutputThread::cacheParameters_l()
6290{
6291 PlaybackThread::cacheParameters_l();
6292
6293 // use shorter standby delay as on normal output to release
6294 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006295 // no delay on outputs with HW A/V sync
6296 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006297 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006298 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006299 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006300 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006301 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006302 }
Eric Laurent81784c32012-11-19 14:55:58 -08006303}
6304
Eric Laurente659ef42014-09-29 13:06:46 -07006305void AudioFlinger::DirectOutputThread::flushHw_l()
6306{
ziyangch09204bd2021-12-01 13:48:04 -08006307 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006308 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006309 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006310 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006311 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006312 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006313}
6314
Andy Hung10cbff12017-02-21 17:30:14 -08006315int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6316 // If a VolumeShaper is active, we must wake up periodically to update volume.
6317 const int64_t NS_PER_MS = 1000000;
6318 return mVolumeShaperActive ?
6319 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6320}
6321
Eric Laurent81784c32012-11-19 14:55:58 -08006322// ----------------------------------------------------------------------------
6323
Eric Laurentbfb1b832013-01-07 09:53:42 -08006324AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006325 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006326 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006327 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006328 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006329 mDrainSequence(0),
6330 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006331{
6332}
6333
6334AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6335{
6336}
6337
6338void AudioFlinger::AsyncCallbackThread::onFirstRef()
6339{
6340 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6341}
6342
6343bool AudioFlinger::AsyncCallbackThread::threadLoop()
6344{
6345 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006346 uint32_t writeAckSequence;
6347 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006348 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006349
6350 {
6351 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006352 while (!((mWriteAckSequence & 1) ||
6353 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006354 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006355 exitPending())) {
6356 mWaitWorkCV.wait(mLock);
6357 }
6358
Eric Laurentbfb1b832013-01-07 09:53:42 -08006359 if (exitPending()) {
6360 break;
6361 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006362 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6363 mWriteAckSequence, mDrainSequence);
6364 writeAckSequence = mWriteAckSequence;
6365 mWriteAckSequence &= ~1;
6366 drainSequence = mDrainSequence;
6367 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006368 asyncError = mAsyncError;
6369 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006370 }
6371 {
Eric Laurent4de95592013-09-26 15:28:21 -07006372 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6373 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006374 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006375 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006376 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006377 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006378 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006379 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006380 if (asyncError) {
6381 playbackThread->onAsyncError();
6382 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006383 }
6384 }
6385 }
6386 return false;
6387}
6388
6389void AudioFlinger::AsyncCallbackThread::exit()
6390{
6391 ALOGV("AsyncCallbackThread::exit");
6392 Mutex::Autolock _l(mLock);
6393 requestExit();
6394 mWaitWorkCV.broadcast();
6395}
6396
Eric Laurent3b4529e2013-09-05 18:09:19 -07006397void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006398{
6399 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006400 // bit 0 is cleared
6401 mWriteAckSequence = sequence << 1;
6402}
6403
6404void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6405{
6406 Mutex::Autolock _l(mLock);
6407 // ignore unexpected callbacks
6408 if (mWriteAckSequence & 2) {
6409 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006410 mWaitWorkCV.signal();
6411 }
6412}
6413
Eric Laurent3b4529e2013-09-05 18:09:19 -07006414void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006415{
6416 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006417 // bit 0 is cleared
6418 mDrainSequence = sequence << 1;
6419}
6420
6421void AudioFlinger::AsyncCallbackThread::resetDraining()
6422{
6423 Mutex::Autolock _l(mLock);
6424 // ignore unexpected callbacks
6425 if (mDrainSequence & 2) {
6426 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006427 mWaitWorkCV.signal();
6428 }
6429}
6430
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006431void AudioFlinger::AsyncCallbackThread::setAsyncError()
6432{
6433 Mutex::Autolock _l(mLock);
6434 mAsyncError = true;
6435 mWaitWorkCV.signal();
6436}
6437
Eric Laurentbfb1b832013-01-07 09:53:42 -08006438
6439// ----------------------------------------------------------------------------
6440AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006441 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6442 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
ziyangch09204bd2021-12-01 13:48:04 -08006443 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006444{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006445 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006446 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006447 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006448}
6449
Eric Laurentbfb1b832013-01-07 09:53:42 -08006450void AudioFlinger::OffloadThread::threadLoop_exit()
6451{
6452 if (mFlushPending || mHwPaused) {
6453 // If a flush is pending or track was paused, just discard buffered data
6454 flushHw_l();
6455 } else {
6456 mMixerStatus = MIXER_DRAIN_ALL;
6457 threadLoop_drain();
6458 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006459 if (mUseAsyncWrite) {
6460 ALOG_ASSERT(mCallbackThread != 0);
6461 mCallbackThread->exit();
6462 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006463 PlaybackThread::threadLoop_exit();
6464}
6465
6466AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6467 Vector< sp<Track> > *tracksToRemove
6468)
6469{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006470 size_t count = mActiveTracks.size();
6471
6472 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006473 bool doHwPause = false;
6474 bool doHwResume = false;
6475
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006476 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006477
Eric Laurentbfb1b832013-01-07 09:53:42 -08006478 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006479 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006480 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006481#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006482 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006483#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006484 // Only consider last track started for volume and mixer state control.
6485 // In theory an older track could underrun and restart after the new one starts
6486 // but as we only care about the transition phase between two tracks on a
6487 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006488 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006489 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006490
Haynes Mathew George7844f672014-01-15 12:32:55 -08006491 if (track->isInvalid()) {
6492 ALOGW("An invalidated track shouldn't be in active list");
6493 tracksToRemove->add(track);
6494 continue;
6495 }
6496
6497 if (track->mState == TrackBase::IDLE) {
6498 ALOGW("An idle track shouldn't be in active list");
6499 continue;
6500 }
6501
Kuowei Li23666472021-01-20 10:23:25 +08006502 if (track->isPausePending()) {
6503 track->pauseAck();
6504 // It is possible a track might have been flushed or stopped.
6505 // Other operations such as flush pending might occur on the next prepare.
6506 if (track->isPausing()) {
6507 track->setPaused();
6508 }
6509 // Always perform pause if last, as an immediate flush will change
6510 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006511 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006512 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006513 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006514 mHwPaused = true;
6515 }
6516 // If we were part way through writing the mixbuffer to
6517 // the HAL we must save this until we resume
6518 // BUG - this will be wrong if a different track is made active,
6519 // in that case we want to discard the pending data in the
6520 // mixbuffer and tell the client to present it again when the
6521 // track is resumed
6522 mPausedWriteLength = mCurrentWriteLength;
6523 mPausedBytesRemaining = mBytesRemaining;
6524 mBytesRemaining = 0; // stop writing
6525 }
6526 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006527 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006528 if (track->isStopping_1()) {
6529 track->mRetryCount = kMaxTrackStopRetriesOffload;
6530 } else {
6531 track->mRetryCount = kMaxTrackRetriesOffload;
6532 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006533 track->flushAck();
6534 if (last) {
6535 mFlushPending = true;
6536 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006537 } else if (track->isResumePending()){
6538 track->resumeAck();
6539 if (last) {
6540 if (mPausedBytesRemaining) {
6541 // Need to continue write that was interrupted
6542 mCurrentWriteLength = mPausedWriteLength;
6543 mBytesRemaining = mPausedBytesRemaining;
6544 mPausedBytesRemaining = 0;
6545 }
6546 if (mHwPaused) {
6547 doHwResume = true;
6548 mHwPaused = false;
6549 // threadLoop_mix() will handle the case that we need to
6550 // resume an interrupted write
6551 }
6552 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006553 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006554
Eric Laurent3df841a2016-07-15 15:15:40 -07006555 mLeftVolFloat = mRightVolFloat = -1.0;
6556
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006557 // Do not handle new data in this iteration even if track->framesReady()
6558 mixerStatus = MIXER_TRACKS_ENABLED;
6559 }
6560 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006561 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006562 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006563 if (track->mFillingUpStatus == Track::FS_FILLED) {
6564 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006565 if (last) {
6566 // make sure processVolume_l() will apply new volume even if 0
6567 mLeftVolFloat = mRightVolFloat = -1.0;
6568 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006569 }
6570
6571 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006572 sp<Track> previousTrack = mPreviousTrack.promote();
6573 if (previousTrack != 0) {
6574 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006575 // Flush any data still being written from last track
6576 mBytesRemaining = 0;
6577 if (mPausedBytesRemaining) {
6578 // Last track was paused so we also need to flush saved
6579 // mixbuffer state and invalidate track so that it will
6580 // re-submit that unwritten data when it is next resumed
6581 mPausedBytesRemaining = 0;
6582 // Invalidate is a bit drastic - would be more efficient
6583 // to have a flag to tell client that some of the
6584 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006585 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006586 }
6587 // flush data already sent to the DSP if changing audio session as audio
6588 // comes from a different source. Also invalidate previous track to force a
6589 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006590 if (previousTrack->sessionId() != track->sessionId()) {
6591 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006592 }
6593 }
6594 }
6595 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006596 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006597 if (track->isStopping_1()) {
6598 track->mRetryCount = kMaxTrackStopRetriesOffload;
6599 } else {
6600 track->mRetryCount = kMaxTrackRetriesOffload;
6601 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006602 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006603 mixerStatus = MIXER_TRACKS_READY;
6604 }
6605 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006606 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006607 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006608 if (--(track->mRetryCount) <= 0) {
6609 // Hardware buffer can hold a large amount of audio so we must
6610 // wait for all current track's data to drain before we say
6611 // that the track is stopped.
6612 if (mBytesRemaining == 0) {
6613 // Only start draining when all data in mixbuffer
6614 // has been written
6615 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6616 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6617 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6618 if (last && !mStandby) {
6619 // do not modify drain sequence if we are already draining. This happens
6620 // when resuming from pause after drain.
6621 if ((mDrainSequence & 1) == 0) {
6622 mSleepTimeUs = 0;
6623 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6624 mixerStatus = MIXER_DRAIN_TRACK;
6625 mDrainSequence += 2;
6626 }
6627 if (mHwPaused) {
6628 // It is possible to move from PAUSED to STOPPING_1 without
6629 // a resume so we must ensure hardware is running
6630 doHwResume = true;
6631 mHwPaused = false;
6632 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006633 }
6634 }
Eric Laurente93cc032016-05-05 10:15:10 -07006635 } else if (last) {
6636 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6637 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006638 }
6639 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006640 // Drain has completed or we are in standby, signal presentation complete
6641 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006642 track->mState = TrackBase::STOPPED;
Andy Hung59de4262021-06-14 10:53:54 -07006643 track->presentationComplete(latency_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006644 track->reset();
6645 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006646 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006647 if (!mUseAsyncWrite) {
6648 // If we don't get explicit drain notification we must
6649 // register discontinuity regardless of whether this is
6650 // the previous (!last) or the upcoming (last) track
6651 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006652 mTimestampVerifier.discontinuity(
6653 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006654 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006655 }
6656 } else {
6657 // No buffers for this track. Give it a few chances to
6658 // fill a buffer, then remove it from active list.
6659 if (--(track->mRetryCount) <= 0) {
ziyangch09204bd2021-12-01 13:48:04 -08006660 const bool running = checkRunningTimestamp();
Andy Hungf8044752016-07-27 14:58:11 -07006661 if (running) { // still running, give us more time.
6662 track->mRetryCount = kMaxTrackRetriesOffload;
6663 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006664 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6665 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006666 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006667 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006668 // it will then automatically call start() when data is available
6669 track->disable();
6670 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006671 } else if (last){
6672 mixerStatus = MIXER_TRACKS_ENABLED;
6673 }
6674 }
6675 }
6676 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006677 if (track->isReady()) { // check ready to prevent premature start.
6678 processVolume_l(track, last);
6679 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006680 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006681
Eric Laurentea0fade2013-10-04 16:23:48 -07006682 // make sure the pause/flush/resume sequence is executed in the right order.
6683 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6684 // before flush and then resume HW. This can happen in case of pause/flush/resume
6685 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006686 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006687 status_t result = mOutput->stream->pause();
6688 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006689 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006690 if (mFlushPending) {
6691 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006692 }
Eric Laurentfd477972013-10-25 18:10:40 -07006693 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006694 status_t result = mOutput->stream->resume();
6695 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006696 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006697
Eric Laurentbfb1b832013-01-07 09:53:42 -08006698 // remove all the tracks that need to be...
6699 removeTracks_l(*tracksToRemove);
6700
6701 return mixerStatus;
6702}
6703
Eric Laurentbfb1b832013-01-07 09:53:42 -08006704// must be called with thread mutex locked
6705bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6706{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006707 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6708 mWriteAckSequence, mDrainSequence);
6709 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006710 return true;
6711 }
6712 return false;
6713}
6714
Eric Laurentbfb1b832013-01-07 09:53:42 -08006715bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6716{
6717 Mutex::Autolock _l(mLock);
6718 return waitingAsyncCallback_l();
6719}
6720
6721void AudioFlinger::OffloadThread::flushHw_l()
6722{
Eric Laurente659ef42014-09-29 13:06:46 -07006723 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006724 // Flush anything still waiting in the mixbuffer
6725 mCurrentWriteLength = 0;
6726 mBytesRemaining = 0;
6727 mPausedWriteLength = 0;
6728 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006729 // reset bytes written count to reflect that DSP buffers are empty after flush.
6730 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006731
Eric Laurentbfb1b832013-01-07 09:53:42 -08006732 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006733 // discard any pending drain or write ack by incrementing sequence
6734 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6735 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006736 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006737 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6738 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006739 }
6740}
6741
Haynes Mathew George05317d22016-05-03 16:34:26 -07006742void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6743{
6744 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006745 if (PlaybackThread::invalidateTracks_l(streamType)) {
6746 mFlushPending = true;
6747 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006748}
6749
Eric Laurentbfb1b832013-01-07 09:53:42 -08006750// ----------------------------------------------------------------------------
6751
Eric Laurent81784c32012-11-19 14:55:58 -08006752AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006753 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006754 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006755 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006756 mWaitTimeMs(UINT_MAX)
6757{
6758 addOutputTrack(mainThread);
6759}
6760
6761AudioFlinger::DuplicatingThread::~DuplicatingThread()
6762{
6763 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6764 mOutputTracks[i]->destroy();
6765 }
6766}
6767
6768void AudioFlinger::DuplicatingThread::threadLoop_mix()
6769{
6770 // mix buffers...
6771 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006772 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006773 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006774 if (mMixerBufferValid) {
6775 memset(mMixerBuffer, 0, mMixerBufferSize);
6776 } else {
6777 memset(mSinkBuffer, 0, mSinkBufferSize);
6778 }
Eric Laurent81784c32012-11-19 14:55:58 -08006779 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006780 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006781 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006782 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006783 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006784}
6785
6786void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6787{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006788 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006789 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006790 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006791 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006792 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006793 }
6794 } else if (mBytesWritten != 0) {
6795 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6796 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006797 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006798 } else {
6799 // flush remaining overflow buffers in output tracks
6800 writeFrames = 0;
6801 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006802 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006803 }
6804}
6805
Eric Laurentbfb1b832013-01-07 09:53:42 -08006806ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006807{
6808 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006809 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6810
6811 // Consider the first OutputTrack for timestamp and frame counting.
6812
6813 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6814 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6815 // we always claim success.
6816 if (i == 0) {
6817 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6818 ALOGD_IF(correction != 0 && writeFrames != 0,
6819 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6820 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6821 mFramesWritten -= correction;
6822 }
6823
6824 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006825 }
Andy Hungcf10d742020-04-28 15:38:24 -07006826 if (mStandby) {
6827 mThreadMetrics.logBeginInterval();
6828 mStandby = false;
6829 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006830 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006831}
6832
6833void AudioFlinger::DuplicatingThread::threadLoop_standby()
6834{
6835 // DuplicatingThread implements standby by stopping all tracks
6836 for (size_t i = 0; i < outputTracks.size(); i++) {
6837 outputTracks[i]->stop();
6838 }
6839}
6840
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006841void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006842{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006843 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006844
6845 std::stringstream ss;
6846 const size_t numTracks = mOutputTracks.size();
6847 ss << " " << numTracks << " OutputTracks";
6848 if (numTracks > 0) {
6849 ss << ":";
6850 for (const auto &track : mOutputTracks) {
6851 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006852 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006853 if (thread.get() != nullptr) {
6854 ss << thread.get() << ", " << thread->id();
6855 } else {
6856 ss << "null";
6857 }
6858 ss << ")";
6859 }
6860 }
6861 ss << "\n";
6862 std::string result = ss.str();
6863 write(fd, result.c_str(), result.size());
6864}
6865
Eric Laurent81784c32012-11-19 14:55:58 -08006866void AudioFlinger::DuplicatingThread::saveOutputTracks()
6867{
6868 outputTracks = mOutputTracks;
6869}
6870
6871void AudioFlinger::DuplicatingThread::clearOutputTracks()
6872{
6873 outputTracks.clear();
6874}
6875
6876void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6877{
6878 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006879 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6880 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6881 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6882 const size_t frameCount =
6883 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6884 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6885 // from different OutputTracks and their associated MixerThreads (e.g. one may
6886 // nearly empty and the other may be dropping data).
6887
Svet Ganov33761132021-05-13 22:51:08 +00006888 // TODO b/182392769: use attribution source util, move to server edge
6889 AttributionSourceState attributionSource = AttributionSourceState();
6890 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006891 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00006892 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006893 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00006894 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08006895 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006896 this,
6897 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006898 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006899 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006900 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00006901 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006902 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6903 if (status != NO_ERROR) {
6904 ALOGE("addOutputTrack() initCheck failed %d", status);
6905 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006906 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006907 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6908 mOutputTracks.add(outputTrack);
6909 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6910 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006911}
6912
6913void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6914{
6915 Mutex::Autolock _l(mLock);
6916 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6917 if (mOutputTracks[i]->thread() == thread) {
6918 mOutputTracks[i]->destroy();
6919 mOutputTracks.removeAt(i);
6920 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006921 if (thread->getOutput() == mOutput) {
6922 mOutput = NULL;
6923 }
Eric Laurent81784c32012-11-19 14:55:58 -08006924 return;
6925 }
6926 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006927 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006928}
6929
6930// caller must hold mLock
6931void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6932{
6933 mWaitTimeMs = UINT_MAX;
6934 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6935 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6936 if (strong != 0) {
6937 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6938 if (waitTimeMs < mWaitTimeMs) {
6939 mWaitTimeMs = waitTimeMs;
6940 }
6941 }
6942 }
6943}
6944
6945
6946bool AudioFlinger::DuplicatingThread::outputsReady(
6947 const SortedVector< sp<OutputTrack> > &outputTracks)
6948{
6949 for (size_t i = 0; i < outputTracks.size(); i++) {
6950 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6951 if (thread == 0) {
6952 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6953 outputTracks[i].get());
6954 return false;
6955 }
6956 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6957 // see note at standby() declaration
6958 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6959 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6960 thread.get());
6961 return false;
6962 }
6963 }
6964 return true;
6965}
6966
Kevin Rocard12381092018-04-11 09:19:59 -07006967void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6968 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006969{
Kevin Rocard12381092018-04-11 09:19:59 -07006970 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6971 outputTrack->setMetadatas(metadata.tracks);
6972 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006973}
6974
Eric Laurent81784c32012-11-19 14:55:58 -08006975uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6976{
6977 return (mWaitTimeMs * 1000) / 2;
6978}
6979
6980void AudioFlinger::DuplicatingThread::cacheParameters_l()
6981{
6982 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6983 updateWaitTime_l();
6984
6985 MixerThread::cacheParameters_l();
6986}
6987
Eric Laurent6acd1d42017-01-04 14:23:29 -08006988
Eric Laurent81784c32012-11-19 14:55:58 -08006989// ----------------------------------------------------------------------------
6990// Record
6991// ----------------------------------------------------------------------------
6992
6993AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6994 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006995 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006996 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006997 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006998 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006999 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007000 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007001 mActiveTracks(&this->mLocalLog),
7002 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007003 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007004 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007005 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7006 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007007 // mFastCapture below
7008 , mFastCaptureFutex(0)
7009 // mInputSource
7010 // mPipeSink
7011 // mPipeSource
7012 , mPipeFramesP2(0)
7013 // mPipeMemory
7014 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007015 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007016 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007017{
Glenn Kastend7dca052015-03-05 16:05:54 -08007018 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7019 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007020
George Burgess IVa8f90c12020-05-14 11:27:19 -07007021 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007022 mIsMsdDevice = strcmp(
7023 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7024 }
7025
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007026 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007027
Andy Hungc8fddf32018-08-08 18:32:37 -07007028 // TODO: We may also match on address as well as device type for
7029 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007030 // TODO: This property should be ensure that only contains one single device type.
7031 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7032 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007033 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7034 : AUDIO_DEVICE_NONE));
7035
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007036 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007037 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007038 size_t numCounterOffers = 0;
7039 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007040#if !LOG_NDEBUG
7041 ssize_t index =
7042#else
7043 (void)
7044#endif
7045 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007046 ALOG_ASSERT(index == 0);
7047
7048 // initialize fast capture depending on configuration
7049 bool initFastCapture;
7050 switch (kUseFastCapture) {
7051 case FastCapture_Never:
7052 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007053 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007054 break;
7055 case FastCapture_Always:
7056 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007057 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007058 break;
7059 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007060 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007061 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7062 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7063 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007064 break;
7065 // case FastCapture_Dynamic:
7066 }
7067
7068 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007069 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007070 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007071 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7072 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007073 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007074 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007075 const sp<MemoryDealer> roHeap(readOnlyHeap());
7076 sp<IMemory> pipeMemory;
7077 if ((roHeap == 0) ||
7078 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007079 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007080 ALOGE("not enough memory for pipe buffer size=%zu; "
7081 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7082 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7083 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007084 goto failed;
7085 }
7086 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7087 memset(pipeBuffer, 0, pipeSize);
7088 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7089 const NBAIO_Format offers[1] = {format};
7090 size_t numCounterOffers = 0;
7091 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7092 ALOG_ASSERT(index == 0);
7093 mPipeSink = pipe;
7094 PipeReader *pipeReader = new PipeReader(*pipe);
7095 numCounterOffers = 0;
7096 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7097 ALOG_ASSERT(index == 0);
7098 mPipeSource = pipeReader;
7099 mPipeFramesP2 = pipeFramesP2;
7100 mPipeMemory = pipeMemory;
7101
7102 // create fast capture
7103 mFastCapture = new FastCapture();
7104 FastCaptureStateQueue *sq = mFastCapture->sq();
7105#ifdef STATE_QUEUE_DUMP
7106 // FIXME
7107#endif
7108 FastCaptureState *state = sq->begin();
7109 state->mCblk = NULL;
7110 state->mInputSource = mInputSource.get();
7111 state->mInputSourceGen++;
7112 state->mPipeSink = pipe;
7113 state->mPipeSinkGen++;
7114 state->mFrameCount = mFrameCount;
7115 state->mCommand = FastCaptureState::COLD_IDLE;
7116 // already done in constructor initialization list
7117 //mFastCaptureFutex = 0;
7118 state->mColdFutexAddr = &mFastCaptureFutex;
7119 state->mColdGen++;
7120 state->mDumpState = &mFastCaptureDumpState;
7121#ifdef TEE_SINK
7122 // FIXME
7123#endif
7124 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7125 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7126 sq->end();
7127 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7128
7129 // start the fast capture
7130 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7131 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007132 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007133 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007134#ifdef AUDIO_WATCHDOG
7135 // FIXME
7136#endif
7137
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007138 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007139 }
Andy Hung8946a282018-04-19 20:04:56 -07007140#ifdef TEE_SINK
7141 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7142 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7143#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007144failed: ;
7145
7146 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007147}
7148
Eric Laurent81784c32012-11-19 14:55:58 -08007149AudioFlinger::RecordThread::~RecordThread()
7150{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007151 if (mFastCapture != 0) {
7152 FastCaptureStateQueue *sq = mFastCapture->sq();
7153 FastCaptureState *state = sq->begin();
7154 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7155 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7156 if (old == -1) {
7157 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7158 }
7159 }
7160 state->mCommand = FastCaptureState::EXIT;
7161 sq->end();
7162 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7163 mFastCapture->join();
7164 mFastCapture.clear();
7165 }
7166 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007167 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007168 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007169}
7170
7171void AudioFlinger::RecordThread::onFirstRef()
7172{
Glenn Kastend7dca052015-03-05 16:05:54 -08007173 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007174}
7175
Eric Laurent555530a2017-02-07 18:17:24 -08007176void AudioFlinger::RecordThread::preExit()
7177{
7178 ALOGV(" preExit()");
7179 Mutex::Autolock _l(mLock);
7180 for (size_t i = 0; i < mTracks.size(); i++) {
7181 sp<RecordTrack> track = mTracks[i];
7182 track->invalidate();
7183 }
7184 mActiveTracks.clear();
7185 mStartStopCond.broadcast();
7186}
7187
Eric Laurent81784c32012-11-19 14:55:58 -08007188bool AudioFlinger::RecordThread::threadLoop()
7189{
Eric Laurent81784c32012-11-19 14:55:58 -08007190 nsecs_t lastWarning = 0;
7191
7192 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007193
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007194reacquire_wakelock:
7195 sp<RecordTrack> activeTrack;
7196 {
7197 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007198 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007199 }
7200
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007201 // used to request a deferred sleep, to be executed later while mutex is unlocked
7202 uint32_t sleepUs = 0;
7203
Andy Hung446f4df2019-02-21 12:26:41 -08007204 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7205
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007206 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007207 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007208 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007209
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007210 // activeTracks accumulates a copy of a subset of mActiveTracks
7211 Vector< sp<RecordTrack> > activeTracks;
7212
Glenn Kasten735f45f2014-08-18 15:51:59 -07007213 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007214 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007215
Glenn Kasten735f45f2014-08-18 15:51:59 -07007216 // reference to a fast track which is about to be removed
7217 sp<RecordTrack> fastTrackToRemove;
7218
Eric Laurent33403f02020-05-29 18:35:06 -07007219 bool silenceFastCapture = false;
7220
Eric Laurent81784c32012-11-19 14:55:58 -08007221 { // scope for mLock
7222 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007223
Eric Laurent021cf962014-05-13 10:18:14 -07007224 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007225
Eric Laurent000a4192014-01-29 15:17:32 -08007226 // check exitPending here because checkForNewParameters_l() and
7227 // checkForNewParameters_l() can temporarily release mLock
7228 if (exitPending()) {
7229 break;
7230 }
7231
Eric Laurent5c25d562016-07-13 17:17:45 -07007232 // sleep with mutex unlocked
7233 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007234 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007235 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7236 ATRACE_END();
7237 sleepUs = 0;
7238 continue;
7239 }
7240
Glenn Kasten2b806402013-11-20 16:37:38 -08007241 // if no active track(s), then standby and release wakelock
7242 size_t size = mActiveTracks.size();
7243 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007244 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007245 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007246 releaseWakeLock_l();
7247 ALOGV("RecordThread: loop stopping");
7248 // go to sleep
7249 mWaitWorkCV.wait(mLock);
7250 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007251 goto reacquire_wakelock;
7252 }
7253
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007254 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007255 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007256 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007257
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007258 activeTrack = mActiveTracks[i];
7259 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007260 if (activeTrack->isFastTrack()) {
7261 ALOG_ASSERT(fastTrackToRemove == 0);
7262 fastTrackToRemove = activeTrack;
7263 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007264 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007265 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007266 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007267 continue;
7268 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007269
7270 TrackBase::track_state activeTrackState = activeTrack->mState;
7271 switch (activeTrackState) {
7272
7273 case TrackBase::PAUSING:
7274 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007275 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007276 doBroadcast = true;
7277 size--;
7278 continue;
7279
7280 case TrackBase::STARTING_1:
7281 sleepUs = 10000;
7282 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007283 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007284 continue;
7285
7286 case TrackBase::STARTING_2:
7287 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007288 if (mStandby) {
7289 mThreadMetrics.logBeginInterval();
7290 mStandby = false;
7291 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007292 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007293 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007294 break;
7295
7296 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007297 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007298 break;
7299
Andy Hungce685402018-10-05 17:23:27 -07007300 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7301 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7302 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007303 default:
Andy Hungce685402018-10-05 17:23:27 -07007304 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7305 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007306 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007307
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007308 if (activeTrack->isFastTrack()) {
7309 ALOG_ASSERT(!mFastTrackAvail);
7310 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007311 // if the active fast track is silenced either:
7312 // 1) silence the whole capture from fast capture buffer if this is
7313 // the only active track
7314 // 2) invalidate this track: this will cause the client to reconnect and possibly
7315 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007316 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007317 if (activeTrack->isSilenced()) {
7318 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007319 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007320 } else {
7321 silenceFastCapture = true;
7322 }
7323 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007324 // Invalidate fast tracks if access to audio history is required as this is not
7325 // possible with fast tracks. Once the fast track has been invalidated, no new
7326 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7327 if (mMaxSharedAudioHistoryMs != 0) {
7328 invalidate = true;
7329 }
7330 if (invalidate) {
7331 activeTrack->invalidate();
7332 ALOG_ASSERT(fastTrackToRemove == 0);
7333 fastTrackToRemove = activeTrack;
7334 removeTrack_l(activeTrack);
7335 mActiveTracks.remove(activeTrack);
7336 size--;
7337 continue;
7338 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007339 fastTrack = activeTrack;
7340 }
Eric Laurent33403f02020-05-29 18:35:06 -07007341
7342 activeTracks.add(activeTrack);
7343 i++;
7344
Glenn Kasten9e982352013-08-14 14:39:50 -07007345 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007346
Andy Hungdae27702016-10-31 14:01:16 -07007347 mActiveTracks.updatePowerState(this);
7348
Kevin Rocard069c2712018-03-29 19:09:14 -07007349 updateMetadata_l();
7350
Eric Laurent5c25d562016-07-13 17:17:45 -07007351 if (allStopped) {
7352 standbyIfNotAlreadyInStandby();
7353 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007354 if (doBroadcast) {
7355 mStartStopCond.broadcast();
7356 }
7357
7358 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007359 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007360 if (sleepUs == 0) {
7361 sleepUs = kRecordThreadSleepUs;
7362 }
7363 continue;
7364 }
7365 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007366
Eric Laurent81784c32012-11-19 14:55:58 -08007367 lockEffectChains_l(effectChains);
7368 }
7369
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007370 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007371
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007372 size_t size = effectChains.size();
7373 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007374 // thread mutex is not locked, but effect chain is locked
7375 effectChains[i]->process_l();
7376 }
7377
Glenn Kasten735f45f2014-08-18 15:51:59 -07007378 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007379 if (mFastCapture != 0) {
7380 FastCaptureStateQueue *sq = mFastCapture->sq();
7381 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007382 bool didModify = false;
7383 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007384 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7385 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7386 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7387 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7388 if (old == -1) {
7389 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7390 }
7391 }
7392 state->mCommand = FastCaptureState::READ_WRITE;
7393#if 0 // FIXME
7394 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007395 FastThreadDumpState::kSamplingNforLowRamDevice :
7396 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007397#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007398 didModify = true;
7399 }
7400 audio_track_cblk_t *cblkOld = state->mCblk;
7401 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7402 if (cblkNew != cblkOld) {
7403 state->mCblk = cblkNew;
7404 // block until acked if removing a fast track
7405 if (cblkOld != NULL) {
7406 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7407 }
7408 didModify = true;
7409 }
jiabin01c8f562018-07-19 17:47:28 -07007410 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7411 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7412 if (state->mFastPatchRecordBufferProvider != abp) {
7413 state->mFastPatchRecordBufferProvider = abp;
7414 state->mFastPatchRecordFormat = fastTrack == 0 ?
7415 AUDIO_FORMAT_INVALID : fastTrack->format();
7416 didModify = true;
7417 }
Eric Laurent33403f02020-05-29 18:35:06 -07007418 if (state->mSilenceCapture != silenceFastCapture) {
7419 state->mSilenceCapture = silenceFastCapture;
7420 didModify = true;
7421 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007422 sq->end(didModify);
7423 if (didModify) {
7424 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007425#if 0
7426 if (kUseFastCapture == FastCapture_Dynamic) {
7427 mNormalSource = mPipeSource;
7428 }
7429#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007430 }
7431 }
7432
Glenn Kasten735f45f2014-08-18 15:51:59 -07007433 // now run the fast track destructor with thread mutex unlocked
7434 fastTrackToRemove.clear();
7435
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007436 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7437 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7438 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7439 // If destination is non-contiguous, first read past the nominal end of buffer, then
7440 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007441
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007442 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007443 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007444 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007445
7446 // If an NBAIO source is present, use it to read the normal capture's data
7447 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007448 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007449
7450 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7451 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7452 // we immediately retry the read() to get data and prevent another overflow.
7453 for (int retries = 0; retries <= 2; ++retries) {
7454 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7455 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7456 framesToRead);
7457 if (framesRead != OVERRUN) break;
7458 }
7459
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007460 const ssize_t availableToRead = mPipeSource->availableToRead();
7461 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007462 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007463 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7464 "more frames to read than fifo size, %zd > %zu",
7465 availableToRead, mPipeFramesP2);
7466 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7467 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7468 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7469 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007470 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7471 }
7472 if (framesRead < 0) {
7473 status_t status = (status_t) framesRead;
7474 switch (status) {
7475 case OVERRUN:
7476 ALOGW("overrun on read from pipe");
7477 framesRead = 0;
7478 break;
7479 case NEGOTIATE:
7480 ALOGE("re-negotiation is needed");
7481 framesRead = -1; // Will cause an attempt to recover.
7482 break;
7483 default:
7484 ALOGE("unknown error %d on read from pipe", status);
7485 break;
7486 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007487 }
7488 // otherwise use the HAL / AudioStreamIn directly
7489 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007490 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007491 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007492 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007493 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007494 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007495 if (result < 0) {
7496 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007497 } else {
7498 framesRead = bytesRead / mFrameSize;
7499 }
7500 }
7501
Andy Hung446f4df2019-02-21 12:26:41 -08007502 const int64_t lastIoEndNs = systemTime(); // end IO timing
7503
Andy Hung3f0c9022016-01-15 17:49:46 -08007504 // Update server timestamp with server stats
7505 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007506 if (framesRead >= 0) {
7507 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7508 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7509 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007510
7511 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007512 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007513 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007514 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007515 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7516 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7517 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007518 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007519 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7520
7521 mTimestampVerifier.add(position, time, mSampleRate);
7522
7523 // Correct timestamps
7524 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007525 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007526 id(), (long long)time, (long long)position);
7527 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7528 position = correctedTimestamp.mFrames;
7529 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007530 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007531 id(), (long long)time, (long long)position);
7532 }
7533
Andy Hung3f0c9022016-01-15 17:49:46 -08007534 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7535 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7536 // Note: In general record buffers should tend to be empty in
7537 // a properly running pipeline.
7538 //
7539 // Also, it is not advantageous to call get_presentation_position during the read
7540 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007541 } else {
7542 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007543 }
7544 }
Andy Hunge6c37112019-02-26 17:38:10 -08007545
7546 // From the timestamp, input read latency is negative output write latency.
7547 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7548 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7549 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7550 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7551 mLatencyMs.add(latencyMs);
7552 }
7553
Andy Hung3f0c9022016-01-15 17:49:46 -08007554 // Use this to track timestamp information
7555 // ALOGD("%s", mTimestamp.toString().c_str());
7556
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007557 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007558 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007559 // Force input into standby so that it tries to recover at next read attempt
7560 inputStandBy();
7561 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007562 }
7563 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007564 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007565 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007566 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007567 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007568
Andy Hung8946a282018-04-19 20:04:56 -07007569#ifdef TEE_SINK
7570 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7571#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007572 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007573 {
7574 size_t part1 = mRsmpInFramesP2 - rear;
7575 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007576 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007577 (framesRead - part1) * mFrameSize);
7578 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007579 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007580 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007581
7582 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007583
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007584 // loop over each active track
7585 for (size_t i = 0; i < size; i++) {
7586 activeTrack = activeTracks[i];
7587
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007588 // skip fast tracks, as those are handled directly by FastCapture
7589 if (activeTrack->isFastTrack()) {
7590 continue;
7591 }
7592
Andy Hung73c02e42015-03-29 01:13:58 -07007593 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007594 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7595
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007596 enum {
7597 OVERRUN_UNKNOWN,
7598 OVERRUN_TRUE,
7599 OVERRUN_FALSE
7600 } overrun = OVERRUN_UNKNOWN;
7601
7602 // loop over getNextBuffer to handle circular sink
7603 for (;;) {
7604
7605 activeTrack->mSink.frameCount = ~0;
7606 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7607 size_t framesOut = activeTrack->mSink.frameCount;
7608 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7609
Andy Hung73c02e42015-03-29 01:13:58 -07007610 // check available frames and handle overrun conditions
7611 // if the record track isn't draining fast enough.
7612 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007613 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007614 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7615 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007616 overrun = OVERRUN_TRUE;
7617 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007618 if (framesOut == 0 || framesIn == 0) {
7619 break;
7620 }
7621
Andy Hung6770c6f2015-04-07 13:43:36 -07007622 // Don't allow framesOut to be larger than what is possible with resampling
7623 // from framesIn.
7624 // This isn't strictly necessary but helps limit buffer resizing in
7625 // RecordBufferConverter. TODO: remove when no longer needed.
7626 framesOut = min(framesOut,
7627 destinationFramesPossible(
7628 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007629
7630 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007631 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007632 // straight from RecordThread buffer to RecordTrack buffer.
7633 AudioBufferProvider::Buffer buffer;
7634 buffer.frameCount = framesOut;
7635 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7636 if (status == OK && buffer.frameCount != 0) {
7637 ALOGV_IF(buffer.frameCount != framesOut,
7638 "%s() read less than expected (%zu vs %zu)",
7639 __func__, buffer.frameCount, framesOut);
7640 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007641 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007642 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7643 } else {
7644 framesOut = 0;
7645 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7646 __func__, status, buffer.frameCount);
7647 }
7648 } else {
7649 // process frames from the RecordThread buffer provider to the RecordTrack
7650 // buffer
7651 framesOut = activeTrack->mRecordBufferConverter->convert(
7652 activeTrack->mSink.raw,
7653 activeTrack->mResamplerBufferProvider,
7654 framesOut);
7655 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007656
7657 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7658 overrun = OVERRUN_FALSE;
7659 }
7660
7661 if (activeTrack->mFramesToDrop == 0) {
7662 if (framesOut > 0) {
7663 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007664 // Sanitize before releasing if the track has no access to the source data
7665 // An idle UID receives silence from non virtual devices until active
7666 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007667 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007668 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007669 activeTrack->releaseBuffer(&activeTrack->mSink);
7670 }
7671 } else {
7672 // FIXME could do a partial drop of framesOut
7673 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007674 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007675 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007676 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007677 }
7678 } else {
7679 activeTrack->mFramesToDrop += framesOut;
7680 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7681 activeTrack->mSyncStartEvent->isCancelled()) {
7682 ALOGW("Synced record %s, session %d, trigger session %d",
7683 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7684 activeTrack->sessionId(),
7685 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007686 activeTrack->mSyncStartEvent->triggerSession() :
7687 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007688 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007689 }
7690 }
7691 }
7692
7693 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007694 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007695 }
7696 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007697
7698 switch (overrun) {
7699 case OVERRUN_TRUE:
7700 // client isn't retrieving buffers fast enough
7701 if (!activeTrack->setOverflow()) {
7702 nsecs_t now = systemTime();
7703 // FIXME should lastWarning per track?
7704 if ((now - lastWarning) > kWarningThrottleNs) {
7705 ALOGW("RecordThread: buffer overflow");
7706 lastWarning = now;
7707 }
7708 }
7709 break;
7710 case OVERRUN_FALSE:
7711 activeTrack->clearOverflow();
7712 break;
7713 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007714 break;
7715 }
7716
Andy Hung3f0c9022016-01-15 17:49:46 -08007717 // update frame information and push timestamp out
7718 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007719 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007720 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7721 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007722 }
7723
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007724unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007725 // enable changes in effect chain
7726 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007727 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007728 if (audio_has_proportional_frames(mFormat)
7729 && loopCount == lastLoopCountRead + 1) {
7730 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7731 const double jitterMs =
7732 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7733 {framesRead, readPeriodNs},
7734 {0, 0} /* lastTimestamp */, mSampleRate);
7735 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7736
7737 Mutex::Autolock _l(mLock);
7738 mIoJitterMs.add(jitterMs);
7739 mProcessTimeMs.add(processMs);
7740 }
7741 // update timing info.
7742 mLastIoBeginNs = lastIoBeginNs;
7743 mLastIoEndNs = lastIoEndNs;
7744 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007745 }
7746
Glenn Kasten93e471f2013-08-19 08:40:07 -07007747 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007748
7749 {
7750 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007751 for (size_t i = 0; i < mTracks.size(); i++) {
7752 sp<RecordTrack> track = mTracks[i];
7753 track->invalidate();
7754 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007755 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007756 mStartStopCond.broadcast();
7757 }
7758
7759 releaseWakeLock();
7760
7761 ALOGV("RecordThread %p exiting", this);
7762 return false;
7763}
7764
Glenn Kasten93e471f2013-08-19 08:40:07 -07007765void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007766{
7767 if (!mStandby) {
7768 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007769 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007770 mStandby = true;
7771 }
7772}
7773
7774void AudioFlinger::RecordThread::inputStandBy()
7775{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007776 // Idle the fast capture if it's currently running
7777 if (mFastCapture != 0) {
7778 FastCaptureStateQueue *sq = mFastCapture->sq();
7779 FastCaptureState *state = sq->begin();
7780 if (!(state->mCommand & FastCaptureState::IDLE)) {
7781 state->mCommand = FastCaptureState::COLD_IDLE;
7782 state->mColdFutexAddr = &mFastCaptureFutex;
7783 state->mColdGen++;
7784 mFastCaptureFutex = 0;
7785 sq->end();
7786 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7787 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7788#if 0
7789 if (kUseFastCapture == FastCapture_Dynamic) {
7790 // FIXME
7791 }
7792#endif
7793#ifdef AUDIO_WATCHDOG
7794 // FIXME
7795#endif
7796 } else {
7797 sq->end(false /*didModify*/);
7798 }
7799 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007800 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007801 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007802
7803 // If going into standby, flush the pipe source.
7804 if (mPipeSource.get() != nullptr) {
7805 const ssize_t flushed = mPipeSource->flush();
7806 if (flushed > 0) {
7807 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7808 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7809 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7810 }
7811 }
Eric Laurent81784c32012-11-19 14:55:58 -08007812}
7813
Glenn Kasten05997e22014-03-13 15:08:33 -07007814// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007815sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007816 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007817 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007818 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007819 audio_format_t format,
7820 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007821 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007822 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007823 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007824 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00007825 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07007826 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007827 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007828 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02007829 audio_port_handle_t portId,
7830 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08007831{
Glenn Kasten74935e42013-12-19 08:56:45 -08007832 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007833 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007834 sp<RecordTrack> track;
7835 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007836 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007837 audio_input_flags_t requestedFlags = *flags;
7838 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00007839 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
7840 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007841
7842 lStatus = initCheck();
7843 if (lStatus != NO_ERROR) {
7844 ALOGE("createRecordTrack_l() audio driver not initialized");
7845 goto Exit;
7846 }
7847
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007848 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7849 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7850 lStatus = BAD_VALUE;
7851 goto Exit;
7852 }
7853
Eric Laurentec376dc2021-04-08 20:41:22 +02007854 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00007855 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02007856 lStatus = PERMISSION_DENIED;
7857 goto Exit;
7858 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007859 if (maxSharedAudioHistoryMs < 0
7860 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
7861 lStatus = BAD_VALUE;
7862 goto Exit;
7863 }
7864 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08007865 if (*pSampleRate == 0) {
7866 *pSampleRate = mSampleRate;
7867 }
7868 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007869
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007870 // special case for FAST flag considered OK if fast capture is present and access to
7871 // audio history is not required
7872 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07007873 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7874 }
7875
Eric Laurentf14db3c2017-12-08 14:20:36 -08007876 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007877 if ((*flags & inputFlags) != *flags) {
7878 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7879 " input flags (%08x)",
7880 *flags, inputFlags);
7881 *flags = (audio_input_flags_t)(*flags & inputFlags);
7882 }
Eric Laurent81784c32012-11-19 14:55:58 -08007883
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007884 // client expresses a preference for FAST and no access to audio history,
7885 // but we get the final say
7886 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007887 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007888 // we formerly checked for a callback handler (non-0 tid),
7889 // but that is no longer required for TRANSFER_OBTAIN mode
7890 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007891 // Frame count is not specified (0), or is less than or equal the pipe depth.
7892 // It is OK to provide a higher capacity than requested.
7893 // We will force it to mPipeFramesP2 below.
7894 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007895 // PCM data
7896 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007897 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007898 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007899 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007900 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007901 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007902 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007903 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007904 hasFastCapture() &&
7905 // there are sufficient fast track slots available
7906 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007907 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007908 // check compatibility with audio effects.
7909 Mutex::Autolock _l(mLock);
7910 // Do not accept FAST flag if the session has software effects
7911 sp<EffectChain> chain = getEffectChain_l(sessionId);
7912 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007913 audio_input_flags_t old = *flags;
7914 chain->checkInputFlagCompatibility(flags);
7915 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007916 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7917 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007918 }
7919 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007920 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007921 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7922 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007923 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007924 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7925 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007926 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007927 this, frameCount, mFrameCount, mPipeFramesP2,
7928 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007929 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007930 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007931 }
7932 }
7933
Eric Laurentf14db3c2017-12-08 14:20:36 -08007934 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7935 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7936 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7937 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7938 lStatus = BAD_TYPE;
7939 goto Exit;
7940 }
7941
Glenn Kasten74105912014-07-03 12:28:53 -07007942 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007943 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007944 // fast track: frame count is exactly the pipe depth
7945 frameCount = mPipeFramesP2;
7946 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007947 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007948 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007949 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7950 // or 20 ms if there is a fast capture
7951 // TODO This could be a roundupRatio inline, and const
7952 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7953 * sampleRate + mSampleRate - 1) / mSampleRate;
7954 // minimum number of notification periods is at least kMinNotifications,
7955 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7956 static const size_t kMinNotifications = 3;
7957 static const uint32_t kMinMs = 30;
7958 // TODO This could be a roundupRatio inline
7959 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7960 // TODO This could be a roundupRatio inline
7961 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7962 maxNotificationFrames;
7963 const size_t minFrameCount = maxNotificationFrames *
7964 max(kMinNotifications, minNotificationsByMs);
7965 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007966 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7967 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007968 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007969 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007970 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007971 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007972
7973 { // scope for mLock
7974 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02007975 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02007976 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00007977 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02007978 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00007979 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02007980 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02007981 }
Eric Laurent81784c32012-11-19 14:55:58 -08007982
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007983 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007984 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007985 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00007986 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
7987 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08007988
Glenn Kasten03003332013-08-06 15:40:54 -07007989 lStatus = track->initCheck();
7990 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007991 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007992 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007993 goto Exit;
7994 }
7995 mTracks.add(track);
7996
Eric Laurent05067782016-06-01 18:27:28 -07007997 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007998 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7999 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8000 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008001 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008002 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008003
8004 if (maxSharedAudioHistoryMs != 0) {
8005 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8006 }
Eric Laurent81784c32012-11-19 14:55:58 -08008007 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008008
Eric Laurent81784c32012-11-19 14:55:58 -08008009 lStatus = NO_ERROR;
8010
8011Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008012 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008013 return track;
8014}
8015
8016status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8017 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008018 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008019{
8020 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8021 sp<ThreadBase> strongMe = this;
8022 status_t status = NO_ERROR;
8023
8024 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008025 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008026 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008027 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008028 triggerSession,
8029 recordTrack->sessionId(),
8030 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008031 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008032 // Sync event can be cancelled by the trigger session if the track is not in a
8033 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008034 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008035 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008036 } else {
8037 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008038 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008039 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008040 }
8041 }
8042
8043 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008044 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008045 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008046 if (recordTrack->isInvalid()) {
8047 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008048 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8049 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008050 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008051 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8052 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008053 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8054 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008055 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008056 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008057 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008058 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008059 }
8060 return status;
8061 }
8062
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008063 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8064 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8065 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008066 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008067 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008068 status_t status = NO_ERROR;
8069 if (recordTrack->isExternalTrack()) {
8070 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008071 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008072 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008073 if (recordTrack->isInvalid()) {
8074 recordTrack->clearSyncStartEvent();
8075 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8076 recordTrack->mState = TrackBase::STARTING_2;
8077 // STARTING_2 forces destroy to call stopInput.
8078 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008079 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8080 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008081 }
8082 if (recordTrack->mState != TrackBase::STARTING_1) {
8083 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008084 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008085 // Someone else has changed state, let them take over,
8086 // leave mState in the new state.
8087 recordTrack->clearSyncStartEvent();
8088 return INVALID_OPERATION;
8089 }
8090 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008091 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008092 ALOGW("%s(%d): startInput failed, status %d",
8093 __func__, recordTrack->id(), status);
8094 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8095 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008096 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008097 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008098 return status;
8099 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008100 sendIoConfigEvent_l(
8101 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008102 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008103
8104 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8105
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008106 // Catch up with current buffer indices if thread is already running.
8107 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8108 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8109 // see previously buffered data before it called start(), but with greater risk of overrun.
8110
Andy Hung73c02e42015-03-29 01:13:58 -07008111 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008112 if (!recordTrack->isDirect()) {
8113 // clear any converter state as new data will be discontinuous
8114 recordTrack->mRecordBufferConverter->reset();
8115 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008116 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008117 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008118 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008119 return status;
8120 }
Eric Laurent81784c32012-11-19 14:55:58 -08008121}
8122
Eric Laurent81784c32012-11-19 14:55:58 -08008123void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8124{
8125 sp<SyncEvent> strongEvent = event.promote();
8126
8127 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008128 sp<RefBase> ptr = strongEvent->cookie().promote();
8129 if (ptr != 0) {
8130 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8131 recordTrack->handleSyncStartEvent(strongEvent);
8132 }
Eric Laurent81784c32012-11-19 14:55:58 -08008133 }
8134}
8135
Glenn Kastena8356f62013-07-25 14:37:52 -07008136bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008137 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008138 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008139 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008140 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008141 return false;
8142 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008143 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008144 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008145
Andy Hungabfab202019-03-07 19:45:54 -08008146 // NOTE: Waiting here is important to keep stop synchronous.
8147 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008148 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8149 mWaitWorkCV.broadcast(); // signal thread to stop
8150 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008151 }
Andy Hungce685402018-10-05 17:23:27 -07008152
8153 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008154 ALOGV("Record stopped OK");
8155 return true;
8156 }
Andy Hungce685402018-10-05 17:23:27 -07008157
8158 // don't handle anything - we've been invalidated or restarted and in a different state
8159 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8160 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008161 return false;
8162}
8163
Glenn Kasten0f11b512014-01-31 16:18:54 -08008164bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008165{
8166 return false;
8167}
8168
Glenn Kasten0f11b512014-01-31 16:18:54 -08008169status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008170{
8171#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8172 if (!isValidSyncEvent(event)) {
8173 return BAD_VALUE;
8174 }
8175
Glenn Kastend848eb42016-03-08 13:42:11 -08008176 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008177 status_t ret = NAME_NOT_FOUND;
8178
8179 Mutex::Autolock _l(mLock);
8180
8181 for (size_t i = 0; i < mTracks.size(); i++) {
8182 sp<RecordTrack> track = mTracks[i];
8183 if (eventSession == track->sessionId()) {
8184 (void) track->setSyncEvent(event);
8185 ret = NO_ERROR;
8186 }
8187 }
8188 return ret;
8189#else
8190 return BAD_VALUE;
8191#endif
8192}
8193
jiabin653cc0a2018-01-17 17:54:10 -08008194status_t AudioFlinger::RecordThread::getActiveMicrophones(
8195 std::vector<media::MicrophoneInfo>* activeMicrophones)
8196{
8197 ALOGV("RecordThread::getActiveMicrophones");
8198 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008199 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008200 return NO_INIT;
8201 }
jiabin9ff780e2018-03-19 18:19:52 -07008202 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8203 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008204}
8205
Paul McLean12340082019-03-19 09:35:05 -06008206status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8207 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008208{
Paul McLean12340082019-03-19 09:35:05 -06008209 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008210 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008211 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008212 return NO_INIT;
8213 }
Paul McLean12340082019-03-19 09:35:05 -06008214 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008215}
8216
Paul McLean12340082019-03-19 09:35:05 -06008217status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008218{
Paul McLean12340082019-03-19 09:35:05 -06008219 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008220 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008221 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008222 return NO_INIT;
8223 }
Paul McLean12340082019-03-19 09:35:05 -06008224 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008225}
8226
Eric Laurentec376dc2021-04-08 20:41:22 +02008227status_t AudioFlinger::RecordThread::shareAudioHistory(
8228 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8229 int64_t sharedAudioStartMs) {
8230 AutoMutex _l(mLock);
8231 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8232}
8233
8234status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8235 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8236 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008237
Eric Laurentec376dc2021-04-08 20:41:22 +02008238 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8239 return BAD_VALUE;
8240 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008241
8242 if (sharedAudioStartMs < 0
8243 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008244 return BAD_VALUE;
8245 }
8246
Eric Laurent2407ce32021-04-26 14:56:03 +02008247 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8248 // As we cannot detect more than one wraparound, only accept values up current write position
8249 // after one wraparound
8250 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8251 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008252 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008253 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8254 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008255 // Bring the start frame position within the input buffer to match the documented
8256 // "best effort" behavior of the API.
8257 if (sharedOffset < 0) {
8258 sharedAudioStartFrames = mRsmpInRear;
8259 } else if (sharedOffset > mRsmpInFrames) {
8260 sharedAudioStartFrames =
8261 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008262 }
8263
Eric Laurentec376dc2021-04-08 20:41:22 +02008264 mSharedAudioPackageName = sharedAudioPackageName;
8265 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008266 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008267 } else {
8268 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008269 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008270 }
8271 return NO_ERROR;
8272}
8273
Eric Laurent92d0a322021-07-16 15:32:33 +02008274void AudioFlinger::RecordThread::resetAudioHistory_l() {
8275 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8276 mSharedAudioStartFrames = -1;
8277 mSharedAudioPackageName = "";
8278}
8279
Kevin Rocard069c2712018-03-29 19:09:14 -07008280void AudioFlinger::RecordThread::updateMetadata_l()
8281{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008282 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8283 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008284 }
8285 StreamInHalInterface::SinkMetadata metadata;
8286 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008287 // Do not forward PatchRecord metadata to audio HAL
8288 if (track->isPatchTrack()) {
8289 continue;
8290 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008291 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008292 record_track_metadata_v7_t trackMetadata;
8293 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008294 .source = track->attributes().source,
8295 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008296 };
8297 trackMetadata.channel_mask = track->channelMask(),
8298 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8299
8300 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008301 }
8302 mInput->stream->updateSinkMetadata(metadata);
8303}
8304
Eric Laurent81784c32012-11-19 14:55:58 -08008305// destroyTrack_l() must be called with ThreadBase::mLock held
8306void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8307{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008308 track->terminate();
8309 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008310
Eric Laurent81784c32012-11-19 14:55:58 -08008311 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008312 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008313 removeTrack_l(track);
8314 }
8315}
8316
8317void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8318{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008319 String8 result;
8320 track->appendDump(result, false /* active */);
8321 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8322
Eric Laurent81784c32012-11-19 14:55:58 -08008323 mTracks.remove(track);
8324 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008325 if (track->isFastTrack()) {
8326 ALOG_ASSERT(!mFastTrackAvail);
8327 mFastTrackAvail = true;
8328 }
Eric Laurent81784c32012-11-19 14:55:58 -08008329}
8330
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008331void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008332{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008333 AudioStreamIn *input = mInput;
8334 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8335 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008336 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008337 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008338 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008339 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008340 }
Andy Hungbfa64962017-06-12 14:43:19 -07008341
8342 if (input != nullptr) {
8343 dprintf(fd, " Hal stream dump:\n");
8344 (void)input->stream->dump(fd);
8345 }
8346
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008347 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008348 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008349
Glenn Kasten2f90c512015-12-02 11:40:09 -08008350 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8351 // while we are dumping it. It may be inconsistent, but it won't mutate!
8352 // This is a large object so we place it on the heap.
8353 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008354 const std::unique_ptr<FastCaptureDumpState> copy =
8355 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008356 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008357}
8358
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008359void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008360{
Eric Laurent81784c32012-11-19 14:55:58 -08008361 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008362 size_t numtracks = mTracks.size();
8363 size_t numactive = mActiveTracks.size();
8364 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008365 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008366 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008367 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008368 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008369 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008370 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008371 for (size_t i = 0; i < numtracks ; ++i) {
8372 sp<RecordTrack> track = mTracks[i];
8373 if (track != 0) {
8374 bool active = mActiveTracks.indexOf(track) >= 0;
8375 if (active) {
8376 numactiveseen++;
8377 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008378 result.append(prefix);
8379 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008380 }
Eric Laurent81784c32012-11-19 14:55:58 -08008381 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008382 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008383 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008384 }
8385
Marco Nelissenb2208842014-02-07 14:00:50 -08008386 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008387 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008388 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008389 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008390 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008391 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008392 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008393 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008394 result.append(prefix);
8395 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008396 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008397 }
Eric Laurent81784c32012-11-19 14:55:58 -08008398
8399 }
8400 write(fd, result.string(), result.size());
8401}
8402
Eric Laurent5ada82e2019-08-29 17:53:54 -07008403void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008404{
8405 Mutex::Autolock _l(mLock);
8406 for (size_t i = 0; i < mTracks.size() ; i++) {
8407 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008408 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008409 track->setSilenced(silenced);
8410 }
8411 }
8412}
Andy Hung73c02e42015-03-29 01:13:58 -07008413
8414void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8415{
8416 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8417 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008418 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008419 const int32_t rear = recordThread->mRsmpInRear;
8420 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008421 if (mRecordTrack->startFrames() >= 0) {
8422 int32_t startFrames = mRecordTrack->startFrames();
8423 // Accept a recent wraparound of mRsmpInRear
8424 if (startFrames <= rear) {
8425 deltaFrames = rear - startFrames;
8426 } else {
8427 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008428 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008429 // start frame cannot be further in the past than start of resampling buffer
8430 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8431 deltaFrames = recordThread->mRsmpInFrames;
8432 }
8433 }
8434 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008435}
8436
8437void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8438 size_t *framesAvailable, bool *hasOverrun)
8439{
8440 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8441 RecordThread *recordThread = (RecordThread *) threadBase.get();
8442 const int32_t rear = recordThread->mRsmpInRear;
8443 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008444 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008445
8446 size_t framesIn;
8447 bool overrun = false;
8448 if (filled < 0) {
8449 // should not happen, but treat like a massive overrun and re-sync
8450 framesIn = 0;
8451 mRsmpInFront = rear;
8452 overrun = true;
8453 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8454 framesIn = (size_t) filled;
8455 } else {
8456 // client is not keeping up with server, but give it latest data
8457 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008458 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8459 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008460 overrun = true;
8461 }
8462 if (framesAvailable != NULL) {
8463 *framesAvailable = framesIn;
8464 }
8465 if (hasOverrun != NULL) {
8466 *hasOverrun = overrun;
8467 }
8468}
8469
Eric Laurent81784c32012-11-19 14:55:58 -08008470// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008471status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008472 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008473{
Andy Hung73c02e42015-03-29 01:13:58 -07008474 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008475 if (threadBase == 0) {
8476 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008477 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008478 return NOT_ENOUGH_DATA;
8479 }
8480 RecordThread *recordThread = (RecordThread *) threadBase.get();
8481 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008482 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008483 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008484 // FIXME should not be P2 (don't want to increase latency)
8485 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008486 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008487 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008488
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008489 front &= recordThread->mRsmpInFramesP2 - 1;
8490 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008491 if (part1 > (size_t) filled) {
8492 part1 = filled;
8493 }
8494 size_t ask = buffer->frameCount;
8495 ALOG_ASSERT(ask > 0);
8496 if (part1 > ask) {
8497 part1 = ask;
8498 }
8499 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008500 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008501 buffer->raw = NULL;
8502 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008503 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008504 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008505 }
8506
Andy Hung57446612015-04-19 23:56:46 -07008507 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008508 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008509 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008510 return NO_ERROR;
8511}
8512
8513// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008514void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8515 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008516{
Hongwei Wang95e37682019-04-12 11:13:36 -07008517 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008518 if (stepCount == 0) {
8519 return;
8520 }
Andy Hung73c02e42015-03-29 01:13:58 -07008521 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8522 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008523 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008524 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008525 buffer->frameCount = 0;
8526}
8527
Eric Laurentd8365c52017-07-16 15:27:05 -07008528void AudioFlinger::RecordThread::checkBtNrec()
8529{
8530 Mutex::Autolock _l(mLock);
8531 checkBtNrec_l();
8532}
8533
8534void AudioFlinger::RecordThread::checkBtNrec_l()
8535{
8536 // disable AEC and NS if the device is a BT SCO headset supporting those
8537 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008538 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008539 mAudioFlinger->btNrecIsOff();
8540 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8541 for (size_t i = 0; i < mEffectChains.size(); i++) {
8542 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8543 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8544 }
8545 }
8546}
8547
Andy Hung97a893e2015-03-29 01:03:07 -07008548
Eric Laurent10351942014-05-08 18:49:52 -07008549bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8550 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008551{
8552 bool reconfig = false;
8553
Eric Laurent10351942014-05-08 18:49:52 -07008554 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008555
Eric Laurent10351942014-05-08 18:49:52 -07008556 audio_format_t reqFormat = mFormat;
8557 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008558 // 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 -07008559 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8560
8561 AudioParameter param = AudioParameter(keyValuePair);
8562 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008563
8564 // scope for AutoPark extends to end of method
8565 AutoPark<FastCapture> park(mFastCapture);
8566
Eric Laurent10351942014-05-08 18:49:52 -07008567 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8568 // channel count change can be requested. Do we mandate the first client defines the
8569 // HAL sampling rate and channel count or do we allow changes on the fly?
8570 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8571 samplingRate = value;
8572 reconfig = true;
8573 }
8574 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008575 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008576 status = BAD_VALUE;
8577 } else {
8578 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008579 reconfig = true;
8580 }
Eric Laurent10351942014-05-08 18:49:52 -07008581 }
8582 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8583 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008584 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07008585 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07008586 status = BAD_VALUE;
8587 } else {
8588 channelMask = mask;
8589 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008590 }
Eric Laurent10351942014-05-08 18:49:52 -07008591 }
8592 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8593 // do not accept frame count changes if tracks are open as the track buffer
8594 // size depends on frame count and correct behavior would not be guaranteed
8595 // if frame count is changed after track creation
8596 if (mActiveTracks.size() > 0) {
8597 status = INVALID_OPERATION;
8598 } else {
8599 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008600 }
Eric Laurent10351942014-05-08 18:49:52 -07008601 }
8602 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008603 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008604 }
8605 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8606 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008607 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008608 }
Glenn Kastene198c362013-08-13 09:13:36 -07008609
Eric Laurent10351942014-05-08 18:49:52 -07008610 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008611 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008612 if (status == INVALID_OPERATION) {
8613 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008614 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008615 }
8616 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008617 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008618 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8619 if (mInput->stream->getAudioProperties(&config) == OK &&
8620 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8621 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07008622 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008623 status = NO_ERROR;
8624 }
Eric Laurent81784c32012-11-19 14:55:58 -08008625 }
Eric Laurent10351942014-05-08 18:49:52 -07008626 if (status == NO_ERROR) {
8627 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008628 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008629 }
8630 }
Eric Laurent81784c32012-11-19 14:55:58 -08008631 }
Eric Laurent10351942014-05-08 18:49:52 -07008632
Eric Laurent81784c32012-11-19 14:55:58 -08008633 return reconfig;
8634}
8635
8636String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8637{
Eric Laurent81784c32012-11-19 14:55:58 -08008638 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008639 if (initCheck() == NO_ERROR) {
8640 String8 out_s8;
8641 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8642 return out_s8;
8643 }
Eric Laurent81784c32012-11-19 14:55:58 -08008644 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008645 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008646}
8647
Eric Laurent09f1ed22019-04-24 17:45:17 -07008648void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8649 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008650 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8651
8652 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008653
8654 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008655 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008656 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008657 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008658 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008659 desc->mChannelMask = mChannelMask;
8660 desc->mSamplingRate = mSampleRate;
8661 desc->mFormat = mFormat;
8662 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008663 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008664 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008665 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008666 case AUDIO_CLIENT_STARTED:
8667 desc->mPatch = mPatch;
8668 desc->mPortId = portId;
8669 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008670 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008671 default:
8672 break;
8673 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008674 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008675}
8676
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008677void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008678{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008679 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8680 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008681 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008682 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8683 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07008684 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
8685 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008686 } else {
Andy Hung936845a2021-06-08 00:09:06 -07008687 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008688 ALOGI("HAL format %#x is not linear pcm", mFormat);
8689 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008690 result = mInput->stream->getFrameSize(&mFrameSize);
8691 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008692 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8693 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008694 result = mInput->stream->getBufferSize(&mBufferSize);
8695 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008696 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008697 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8698 "mBufferSize=%zu, mFrameCount=%zu",
8699 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008700
Eric Laurentec376dc2021-04-08 20:41:22 +02008701 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8702 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008703 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08008704
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008705 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8706 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008707
8708 audio_input_flags_t flags = mInput->flags;
8709 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8710 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8711 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8712 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8713 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8714 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8715 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8716 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8717 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008718}
8719
Glenn Kasten5f972c02014-01-13 09:59:31 -08008720uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008721{
8722 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008723 uint32_t result;
8724 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8725 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008726 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008727 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008728}
8729
Glenn Kastend848eb42016-03-08 13:42:11 -08008730KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008731{
Glenn Kastend848eb42016-03-08 13:42:11 -08008732 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008733 Mutex::Autolock _l(mLock);
8734 for (size_t j = 0; j < mTracks.size(); ++j) {
8735 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008736 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008737 if (ids.indexOfKey(sessionId) < 0) {
8738 ids.add(sessionId, true);
8739 }
8740 }
8741 return ids;
8742}
8743
8744AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8745{
8746 Mutex::Autolock _l(mLock);
8747 AudioStreamIn *input = mInput;
8748 mInput = NULL;
8749 return input;
8750}
8751
8752// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008753sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008754{
8755 if (mInput == NULL) {
8756 return NULL;
8757 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008758 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008759}
8760
8761status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8762{
Eric Laurent81784c32012-11-19 14:55:58 -08008763 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008764 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008765 chain->setInBuffer(NULL);
8766 chain->setOutBuffer(NULL);
8767
8768 checkSuspendOnAddEffectChain_l(chain);
8769
Eric Laurent1b928682014-10-02 19:41:47 -07008770 // make sure enabled pre processing effects state is communicated to the HAL as we
8771 // just moved them to a new input stream.
8772 chain->syncHalEffectsState();
8773
Eric Laurent81784c32012-11-19 14:55:58 -08008774 mEffectChains.add(chain);
8775
8776 return NO_ERROR;
8777}
8778
8779size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8780{
8781 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008782
8783 for (size_t i = 0; i < mEffectChains.size(); i++) {
8784 if (chain == mEffectChains[i]) {
8785 mEffectChains.removeAt(i);
8786 break;
8787 }
Eric Laurent81784c32012-11-19 14:55:58 -08008788 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008789 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008790}
8791
Eric Laurent1c333e22014-05-20 10:48:17 -07008792status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8793 audio_patch_handle_t *handle)
8794{
8795 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008796
8797 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008798 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008799 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008800 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008801 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008802 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008803 }
8804
Eric Laurentd8365c52017-07-16 15:27:05 -07008805 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008806
8807 // store new source and send to effects
8808 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8809 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008810 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008811 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008812 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008813 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008814
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008815 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008816 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8817 status = hwDevice->createAudioPatch(patch->num_sources,
8818 patch->sources,
8819 patch->num_sinks,
8820 patch->sinks,
8821 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008822 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008823 char *address;
8824 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8825 address = audio_device_address_to_parameter(
8826 patch->sources[0].ext.device.type,
8827 patch->sources[0].ext.device.address);
8828 } else {
8829 address = (char *)calloc(1, 1);
8830 }
8831 AudioParameter param = AudioParameter(String8(address));
8832 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008833 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008834 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008835 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008836 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008837 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008838 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008839 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008840
jiabinc52b1ff2019-10-31 17:20:42 -07008841 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008842 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008843 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008844 }
Eric Laurent296fb132015-05-01 11:38:42 -07008845
Andy Hungc2b11cb2020-04-22 09:04:01 -07008846 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008847 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008848 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008849 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008850 // also dispatch to active AudioRecords
8851 for (const auto &track : mActiveTracks) {
8852 track->logEndInterval();
8853 track->logBeginInterval(pathSourcesAsString);
8854 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008855 return status;
8856}
8857
8858status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8859{
8860 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008861
jiabinc52b1ff2019-10-31 17:20:42 -07008862 mPatch = audio_patch{};
8863 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008864
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008865 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008866 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8867 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008868 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008869 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008870 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008871 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008872 }
8873 return status;
8874}
8875
jiabinc52b1ff2019-10-31 17:20:42 -07008876void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8877{
wendy lin56aa82b2020-12-02 15:19:55 +08008878 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07008879 mOutDevices = outDevices;
8880 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8881 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008882 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008883 }
8884}
8885
Eric Laurentec376dc2021-04-08 20:41:22 +02008886int32_t AudioFlinger::RecordThread::getOldestFront_l()
8887{
8888 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008889 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02008890 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008891 int32_t oldestFront = mRsmpInRear;
8892 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008893 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008894 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8895 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02008896 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02008897 if (filled > maxFilled) {
8898 oldestFront = front;
8899 maxFilled = filled;
8900 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008901 }
Eric Laurent92d0a322021-07-16 15:32:33 +02008902 if (maxFilled > mRsmpInFrames) {
8903 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
8904 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008905 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02008906}
8907
8908void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
8909{
8910 if (offset == 0) {
8911 return;
8912 }
8913 for (size_t i = 0; i < mTracks.size(); i++) {
8914 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8915 front = audio_utils::safe_sub_overflow(front, offset);
8916 mTracks[i]->mResamplerBufferProvider->setFront(front);
8917 }
8918}
8919
8920void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
8921{
8922 // This is the formula for calculating the temporary buffer size.
8923 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
8924 // 1 full output buffer, regardless of the alignment of the available input.
8925 // The value is somewhat arbitrary, and could probably be even larger.
8926 // A larger value should allow more old data to be read after a track calls start(),
8927 // without increasing latency.
8928 //
8929 // Note this is independent of the maximum downsampling ratio permitted for capture.
8930 size_t minRsmpInFrames = mFrameCount * 7;
8931
8932 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
8933 // capture history available to another client using the same session ID:
8934 // dimension the resampler input buffer accordingly.
8935
8936 // Get oldest client read position: getOldestFront_l() must be called before altering
8937 // mRsmpInRear, or mRsmpInFrames
8938 int32_t previousFront = getOldestFront_l();
8939 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
8940 int32_t previousRear = mRsmpInRear;
8941 mRsmpInRear = 0;
8942
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008943 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
8944 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
8945 "resizeInputBuffer_l() called with invalid max shared history %d",
8946 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02008947 if (maxSharedAudioHistoryMs != 0) {
8948 // resizeInputBuffer_l should never be called with a non zero shared history if the
8949 // buffer was not already allocated
8950 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
8951 "resizeInputBuffer_l() called with shared history and unallocated buffer");
8952 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
8953 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02008954 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008955 return;
8956 }
8957 mRsmpInFrames = rsmpInFrames;
8958 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008959 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02008960 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
8961 // initialized
8962 if (mRsmpInFrames < minRsmpInFrames) {
8963 mRsmpInFrames = minRsmpInFrames;
8964 }
8965 mRsmpInFramesP2 = roundup(mRsmpInFrames);
8966
8967 // TODO optimize audio capture buffer sizes ...
8968 // Here we calculate the size of the sliding buffer used as a source
8969 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8970 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8971 // be better to have it derived from the pipe depth in the long term.
8972 // The current value is higher than necessary. However it should not add to latency.
8973
8974 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
8975 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8976
8977 void *rsmpInBuffer;
8978 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
8979 // if posix_memalign fails, will segv here.
8980 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
8981
8982 // Copy audio history if any from old buffer before freeing it
8983 if (previousRear != 0) {
8984 ALOG_ASSERT(mRsmpInBuffer != nullptr,
8985 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
8986
8987 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
8988 previousFront &= previousRsmpInFramesP2 - 1;
8989 size_t part1 = previousRsmpInFramesP2 - previousFront;
8990 if (part1 > (size_t) unread) {
8991 part1 = unread;
8992 }
8993 if (part1 != 0) {
8994 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
8995 part1 * mFrameSize);
8996 mRsmpInRear = part1;
8997 part1 = unread - part1;
8998 if (part1 != 0) {
8999 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9000 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9001 mRsmpInRear += part1;
9002 }
9003 }
9004 // Update front for all clients according to new rear
9005 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9006 } else {
9007 mRsmpInRear = 0;
9008 }
9009 free(mRsmpInBuffer);
9010 mRsmpInBuffer = rsmpInBuffer;
9011}
9012
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009013void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009014{
9015 Mutex::Autolock _l(mLock);
9016 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009017 if (record->getSource()) {
9018 mSource = record->getSource();
9019 }
Eric Laurent83b88082014-06-20 18:31:16 -07009020}
9021
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009022void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009023{
9024 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009025 if (mSource == record->getSource()) {
9026 mSource = mInput;
9027 }
Eric Laurent83b88082014-06-20 18:31:16 -07009028 destroyTrack_l(record);
9029}
9030
Mikhail Naganovdc769682018-05-04 15:34:08 -07009031void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009032{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009033 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009034 config->role = AUDIO_PORT_ROLE_SINK;
9035 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9036 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009037 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9038 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9039 config->flags.input = mInput->flags;
9040 }
Eric Laurent83b88082014-06-20 18:31:16 -07009041}
Eric Laurent1c333e22014-05-20 10:48:17 -07009042
Eric Laurent6acd1d42017-01-04 14:23:29 -08009043// ----------------------------------------------------------------------------
9044// Mmap
9045// ----------------------------------------------------------------------------
9046
9047AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9048 : mThread(thread)
9049{
Phil Burk9fabbf82017-08-03 12:02:00 -07009050 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009051}
9052
9053AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9054{
Phil Burk9fabbf82017-08-03 12:02:00 -07009055 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009056}
9057
9058status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9059 struct audio_mmap_buffer_info *info)
9060{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009061 return mThread->createMmapBuffer(minSizeFrames, info);
9062}
9063
9064status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9065{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009066 return mThread->getMmapPosition(position);
9067}
9068
jiabinb7d8c5a2020-08-26 17:24:52 -07009069status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9070 int64_t *timeNanos) {
9071 return mThread->getExternalPosition(position, timeNanos);
9072}
9073
Eric Laurenta54f1282017-07-01 19:39:32 -07009074status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009075 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009076
9077{
jiabind1f1cb62020-03-24 11:57:57 -07009078 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009079}
9080
9081status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9082{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009083 return mThread->stop(handle);
9084}
9085
Eric Laurent18b57012017-02-13 16:23:52 -08009086status_t AudioFlinger::MmapThreadHandle::standby()
9087{
Eric Laurent18b57012017-02-13 16:23:52 -08009088 return mThread->standby();
9089}
9090
Eric Laurent6acd1d42017-01-04 14:23:29 -08009091
9092AudioFlinger::MmapThread::MmapThread(
9093 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009094 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009095 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009096 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009097 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009098 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009099 mActiveTracks(&this->mLocalLog),
9100 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9101 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009102{
Eric Laurent18b57012017-02-13 16:23:52 -08009103 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009104 readHalParameters_l();
9105}
9106
9107AudioFlinger::MmapThread::~MmapThread()
9108{
9109}
9110
9111void AudioFlinger::MmapThread::onFirstRef()
9112{
9113 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9114}
9115
9116void AudioFlinger::MmapThread::disconnect()
9117{
Eric Laurent331679c2018-04-16 17:03:16 -07009118 ActiveTracks<MmapTrack> activeTracks;
9119 {
9120 Mutex::Autolock _l(mLock);
9121 for (const sp<MmapTrack> &t : mActiveTracks) {
9122 activeTracks.add(t);
9123 }
9124 }
9125 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009126 stop(t->portId());
9127 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009128 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009129 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009130 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009131 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009132 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009133 }
9134}
9135
9136
9137void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9138 audio_stream_type_t streamType __unused,
9139 audio_session_t sessionId,
9140 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009141 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009142 audio_port_handle_t portId)
9143{
9144 mAttr = *attr;
9145 mSessionId = sessionId;
9146 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009147 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009148 mPortId = portId;
9149}
9150
9151status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9152 struct audio_mmap_buffer_info *info)
9153{
9154 if (mHalStream == 0) {
9155 return NO_INIT;
9156 }
Eric Laurent18b57012017-02-13 16:23:52 -08009157 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009158 return mHalStream->createMmapBuffer(minSizeFrames, info);
9159}
9160
9161status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9162{
9163 if (mHalStream == 0) {
9164 return NO_INIT;
9165 }
9166 return mHalStream->getMmapPosition(position);
9167}
9168
Eric Laurent331679c2018-04-16 17:03:16 -07009169status_t AudioFlinger::MmapThread::exitStandby()
9170{
9171 status_t ret = mHalStream->start();
9172 if (ret != NO_ERROR) {
9173 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9174 return ret;
9175 }
Andy Hungcf10d742020-04-28 15:38:24 -07009176 if (mStandby) {
9177 mThreadMetrics.logBeginInterval();
9178 mStandby = false;
9179 }
Eric Laurent331679c2018-04-16 17:03:16 -07009180 return NO_ERROR;
9181}
9182
Eric Laurenta54f1282017-07-01 19:39:32 -07009183status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009184 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009185 audio_port_handle_t *handle)
9186{
Eric Laurenta54f1282017-07-01 19:39:32 -07009187 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009188 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009189 if (mHalStream == 0) {
9190 return NO_INIT;
9191 }
9192
9193 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009194
Eric Laurenta54f1282017-07-01 19:39:32 -07009195 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009196 // For the first track, reuse portId and session allocated when the stream was opened.
9197 ret = exitStandby();
9198 if (ret == NO_ERROR) {
9199 acquireWakeLock();
9200 }
9201 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009202 }
9203
9204 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9205
9206 audio_io_handle_t io = mId;
9207 if (isOutput()) {
9208 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9209 config.sample_rate = mSampleRate;
9210 config.channel_mask = mChannelMask;
9211 config.format = mFormat;
9212 audio_stream_type_t stream = streamType();
9213 audio_output_flags_t flags =
9214 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009215 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009216 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009217 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9218 mSessionId,
9219 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009220 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009221 &config,
9222 flags,
9223 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009224 &portId,
9225 &secondaryOutputs);
9226 ALOGD_IF(!secondaryOutputs.empty(),
9227 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009228 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009229 audio_config_base_t config;
9230 config.sample_rate = mSampleRate;
9231 config.channel_mask = mChannelMask;
9232 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009233 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009234 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009235 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009236 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009237 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009238 &config,
9239 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9240 &deviceId,
9241 &portId);
9242 }
9243 // APM should not chose a different input or output stream for the same set of attributes
9244 // and audo configuration
9245 if (ret != NO_ERROR || io != mId) {
9246 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9247 __FUNCTION__, ret, io, mId);
9248 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009249 }
9250
9251 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009252 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009253 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009254 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009255 }
9256
Eric Laurent331679c2018-04-16 17:03:16 -07009257 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009258 // abort if start is rejected by audio policy manager
9259 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009260 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009261 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009262 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009263 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009264 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009265 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009266 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009267 }
Eric Laurent331679c2018-04-16 17:03:16 -07009268 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009269 } else {
9270 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009271 }
9272 return PERMISSION_DENIED;
9273 }
9274
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009275 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009276 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009277 mChannelMask, mSessionId, isOutput(),
9278 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009279 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009280
Eric Laurent4eb58f12018-12-07 16:41:02 -08009281 if (isOutput()) {
9282 // force volume update when a new track is added
9283 mHalVolFloat = -1.0f;
9284 } else if (!track->isSilenced_l()) {
9285 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009286 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009287 t->invalidate();
9288 }
9289 }
9290
9291
Eric Laurent6acd1d42017-01-04 14:23:29 -08009292 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009293 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009294 if (chain != 0) {
Eric Laurent39934ea2021-07-13 13:35:32 +02009295 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009296 chain->incTrackCnt();
9297 chain->incActiveTrackCnt();
9298 }
9299
Andy Hungc2b11cb2020-04-22 09:04:01 -07009300 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009301 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009302 broadcast_l();
9303
Eric Laurenta54f1282017-07-01 19:39:32 -07009304 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009305
9306 return NO_ERROR;
9307}
9308
9309status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9310{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009311 ALOGV("%s handle %d", __FUNCTION__, handle);
9312
9313 if (mHalStream == 0) {
9314 return NO_INIT;
9315 }
9316
Eric Laurenta54f1282017-07-01 19:39:32 -07009317 if (handle == mPortId) {
9318 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009319 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009320 return NO_ERROR;
9321 }
9322
Eric Laurent331679c2018-04-16 17:03:16 -07009323 Mutex::Autolock _l(mLock);
9324
Eric Laurent6acd1d42017-01-04 14:23:29 -08009325 sp<MmapTrack> track;
9326 for (const sp<MmapTrack> &t : mActiveTracks) {
9327 if (handle == t->portId()) {
9328 track = t;
9329 break;
9330 }
9331 }
9332 if (track == 0) {
9333 return BAD_VALUE;
9334 }
9335
9336 mActiveTracks.remove(track);
9337
Eric Laurent331679c2018-04-16 17:03:16 -07009338 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009339 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009340 AudioSystem::stopOutput(track->portId());
9341 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009342 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009343 AudioSystem::stopInput(track->portId());
9344 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009345 }
Eric Laurent331679c2018-04-16 17:03:16 -07009346 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009347
9348 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9349 if (chain != 0) {
9350 chain->decActiveTrackCnt();
9351 chain->decTrackCnt();
9352 }
9353
9354 broadcast_l();
9355
Eric Laurent6acd1d42017-01-04 14:23:29 -08009356 return NO_ERROR;
9357}
9358
Eric Laurent18b57012017-02-13 16:23:52 -08009359status_t AudioFlinger::MmapThread::standby()
9360{
9361 ALOGV("%s", __FUNCTION__);
9362
9363 if (mHalStream == 0) {
9364 return NO_INIT;
9365 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009366 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009367 return INVALID_OPERATION;
9368 }
9369 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009370 if (!mStandby) {
9371 mThreadMetrics.logEndInterval();
9372 mStandby = true;
9373 }
Eric Laurent18b57012017-02-13 16:23:52 -08009374 releaseWakeLock();
9375 return NO_ERROR;
9376}
9377
Eric Laurent6acd1d42017-01-04 14:23:29 -08009378
9379void AudioFlinger::MmapThread::readHalParameters_l()
9380{
9381 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9382 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9383 mFormat = mHALFormat;
9384 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9385 result = mHalStream->getFrameSize(&mFrameSize);
9386 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009387 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9388 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009389 result = mHalStream->getBufferSize(&mBufferSize);
9390 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9391 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009392
Andy Hungcf10d742020-04-28 15:38:24 -07009393 // TODO: make a readHalParameters call?
9394 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009395 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9396 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9397 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9398 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9399 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9400 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9401 /*
9402 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9403 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9404 (int32_t)mHapticChannelMask)
9405 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9406 (int32_t)mHapticChannelCount)
9407 */
9408 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9409 formatToString(mHALFormat).c_str())
9410 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9411 (int32_t)mFrameCount) // sic - added HAL
9412 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009413}
9414
9415bool AudioFlinger::MmapThread::threadLoop()
9416{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009417 checkSilentMode_l();
9418
9419 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9420
9421 while (!exitPending())
9422 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009423 Vector< sp<EffectChain> > effectChains;
9424
Andy Hung13850be2019-03-14 11:33:09 -07009425 { // under Thread lock
9426 Mutex::Autolock _l(mLock);
9427
Eric Laurent6acd1d42017-01-04 14:23:29 -08009428 if (mSignalPending) {
9429 // A signal was raised while we were unlocked
9430 mSignalPending = false;
9431 } else {
9432 if (mConfigEvents.isEmpty()) {
9433 // we're about to wait, flush the binder command buffer
9434 IPCThreadState::self()->flushCommands();
9435
9436 if (exitPending()) {
9437 break;
9438 }
9439
Eric Laurent6acd1d42017-01-04 14:23:29 -08009440 // wait until we have something to do...
9441 ALOGV("%s going to sleep", myName.string());
9442 mWaitWorkCV.wait(mLock);
9443 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009444
9445 checkSilentMode_l();
9446
9447 continue;
9448 }
9449 }
9450
9451 processConfigEvents_l();
9452
9453 processVolume_l();
9454
9455 checkInvalidTracks_l();
9456
9457 mActiveTracks.updatePowerState(this);
9458
Kevin Rocard069c2712018-03-29 19:09:14 -07009459 updateMetadata_l();
9460
Eric Laurent6acd1d42017-01-04 14:23:29 -08009461 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009462 } // release Thread lock
9463
Eric Laurent6acd1d42017-01-04 14:23:29 -08009464 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009465 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009466 }
Andy Hung13850be2019-03-14 11:33:09 -07009467
9468 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009469 unlockEffectChains(effectChains);
9470 // Effect chains will be actually deleted here if they were removed from
9471 // mEffectChains list during mixing or effects processing
9472 }
9473
9474 threadLoop_exit();
9475
9476 if (!mStandby) {
9477 threadLoop_standby();
9478 mStandby = true;
9479 }
9480
Eric Laurent6acd1d42017-01-04 14:23:29 -08009481 ALOGV("Thread %p type %d exiting", this, mType);
9482 return false;
9483}
9484
9485// checkForNewParameter_l() must be called with ThreadBase::mLock held
9486bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9487 status_t& status)
9488{
9489 AudioParameter param = AudioParameter(keyValuePair);
9490 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009491 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009492 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009493 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009494 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009495 if (sendToHal) {
9496 status = mHalStream->setParameters(keyValuePair);
9497 } else {
9498 status = NO_ERROR;
9499 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009500
9501 return false;
9502}
9503
9504String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9505{
9506 Mutex::Autolock _l(mLock);
9507 String8 out_s8;
9508 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9509 return out_s8;
9510 }
9511 return String8();
9512}
9513
Eric Laurent09f1ed22019-04-24 17:45:17 -07009514void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9515 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009516 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9517
9518 desc->mIoHandle = mId;
9519
9520 switch (event) {
9521 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009522 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009523 case AUDIO_INPUT_CONFIG_CHANGED:
9524 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009525 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009526 case AUDIO_OUTPUT_CONFIG_CHANGED:
9527 desc->mPatch = mPatch;
9528 desc->mChannelMask = mChannelMask;
9529 desc->mSamplingRate = mSampleRate;
9530 desc->mFormat = mFormat;
9531 desc->mFrameCount = mFrameCount;
9532 desc->mFrameCountHAL = mFrameCount;
9533 desc->mLatency = 0;
9534 break;
9535
9536 case AUDIO_INPUT_CLOSED:
9537 case AUDIO_OUTPUT_CLOSED:
9538 default:
9539 break;
9540 }
9541 mAudioFlinger->ioConfigChanged(event, desc, pid);
9542}
9543
9544status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9545 audio_patch_handle_t *handle)
9546{
9547 status_t status = NO_ERROR;
9548
9549 // store new device and send to effects
9550 audio_devices_t type = AUDIO_DEVICE_NONE;
9551 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009552 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9553 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9554 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009555 if (isOutput()) {
9556 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009557 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9558 && !mAudioHwDev->supportsAudioPatches(),
9559 "Enumerated device type(%#x) must not be used "
9560 "as it does not support audio patches",
9561 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009562 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009563 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9564 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009565 }
9566 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009567 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009568 } else {
9569 type = patch->sources[0].ext.device.type;
9570 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009571 numDevices = mPatch.num_sources;
9572 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009573 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009574 }
9575
9576 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009577 if (isOutput()) {
9578 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9579 } else {
9580 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9581 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009582 }
9583
jiabinc52b1ff2019-10-31 17:20:42 -07009584 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009585 // store new source and send to effects
9586 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9587 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9588 for (size_t i = 0; i < mEffectChains.size(); i++) {
9589 mEffectChains[i]->setAudioSource_l(mAudioSource);
9590 }
9591 }
9592 }
9593
9594 if (mAudioHwDev->supportsAudioPatches()) {
9595 status = mHalDevice->createAudioPatch(patch->num_sources,
9596 patch->sources,
9597 patch->num_sinks,
9598 patch->sinks,
9599 handle);
9600 } else {
9601 char *address;
9602 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9603 //FIXME: we only support address on first sink with HAL version < 3.0
9604 address = audio_device_address_to_parameter(
9605 patch->sinks[0].ext.device.type,
9606 patch->sinks[0].ext.device.address);
9607 } else {
9608 address = (char *)calloc(1, 1);
9609 }
9610 AudioParameter param = AudioParameter(String8(address));
9611 free(address);
9612 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9613 if (!isOutput()) {
9614 param.addInt(String8(AudioParameter::keyInputSource),
9615 (int)patch->sinks[0].ext.mix.usecase.source);
9616 }
9617 status = mHalStream->setParameters(param.toString());
9618 *handle = AUDIO_PATCH_HANDLE_NONE;
9619 }
9620
jiabinc52b1ff2019-10-31 17:20:42 -07009621 if (numDevices == 0 || mDeviceId != deviceId) {
9622 if (isOutput()) {
9623 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9624 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009625 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009626 } else {
9627 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9628 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9629 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009630 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009631 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009632 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009633 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009634 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009635 }
jiabinc52b1ff2019-10-31 17:20:42 -07009636 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009637 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009638 }
9639 return status;
9640}
9641
9642status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9643{
9644 status_t status = NO_ERROR;
9645
jiabinc52b1ff2019-10-31 17:20:42 -07009646 mPatch = audio_patch{};
9647 mOutDeviceTypeAddrs.clear();
9648 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009649
9650 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9651 supportsAudioPatches : false;
9652
9653 if (supportsAudioPatches) {
9654 status = mHalDevice->releaseAudioPatch(handle);
9655 } else {
9656 AudioParameter param;
9657 param.addInt(String8(AudioParameter::keyRouting), 0);
9658 status = mHalStream->setParameters(param.toString());
9659 }
9660 return status;
9661}
9662
Mikhail Naganovdc769682018-05-04 15:34:08 -07009663void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009664{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009665 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009666 if (isOutput()) {
9667 config->role = AUDIO_PORT_ROLE_SOURCE;
9668 config->ext.mix.hw_module = mAudioHwDev->handle();
9669 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9670 } else {
9671 config->role = AUDIO_PORT_ROLE_SINK;
9672 config->ext.mix.hw_module = mAudioHwDev->handle();
9673 config->ext.mix.usecase.source = mAudioSource;
9674 }
9675}
9676
9677status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9678{
9679 audio_session_t session = chain->sessionId();
9680
9681 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9682 // Attach all tracks with same session ID to this chain.
9683 // indicate all active tracks in the chain
9684 for (const sp<MmapTrack> &track : mActiveTracks) {
9685 if (session == track->sessionId()) {
9686 chain->incTrackCnt();
9687 chain->incActiveTrackCnt();
9688 }
9689 }
9690
9691 chain->setThread(this);
9692 chain->setInBuffer(nullptr);
9693 chain->setOutBuffer(nullptr);
9694 chain->syncHalEffectsState();
9695
9696 mEffectChains.add(chain);
9697 checkSuspendOnAddEffectChain_l(chain);
9698 return NO_ERROR;
9699}
9700
9701size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9702{
9703 audio_session_t session = chain->sessionId();
9704
9705 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9706
9707 for (size_t i = 0; i < mEffectChains.size(); i++) {
9708 if (chain == mEffectChains[i]) {
9709 mEffectChains.removeAt(i);
9710 // detach all active tracks from the chain
9711 // detach all tracks with same session ID from this chain
9712 for (const sp<MmapTrack> &track : mActiveTracks) {
9713 if (session == track->sessionId()) {
9714 chain->decActiveTrackCnt();
9715 chain->decTrackCnt();
9716 }
9717 }
9718 break;
9719 }
9720 }
9721 return mEffectChains.size();
9722}
9723
Eric Laurent6acd1d42017-01-04 14:23:29 -08009724void AudioFlinger::MmapThread::threadLoop_standby()
9725{
9726 mHalStream->standby();
9727}
9728
9729void AudioFlinger::MmapThread::threadLoop_exit()
9730{
Phil Burk7dce7282017-09-27 13:51:41 -07009731 // Do not call callback->onTearDown() because it is redundant for thread exit
9732 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009733}
9734
9735status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9736{
9737 return BAD_VALUE;
9738}
9739
9740bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9741{
9742 return false;
9743}
9744
9745status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9746 const effect_descriptor_t *desc, audio_session_t sessionId)
9747{
9748 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009749 if (audio_is_global_session(sessionId)) {
9750 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009751 desc->name, mThreadName);
9752 return BAD_VALUE;
9753 }
9754
9755 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9756 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9757 desc->name);
9758 return BAD_VALUE;
9759 }
9760 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009761 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9762 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009763 return BAD_VALUE;
9764 }
9765
9766 // Only allow effects without processing load or latency
9767 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9768 return BAD_VALUE;
9769 }
9770
jiabineb3bda02020-06-30 14:07:03 -07009771 if (EffectModule::isHapticGenerator(&desc->type)) {
9772 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9773 return BAD_VALUE;
9774 }
9775
Eric Laurent6acd1d42017-01-04 14:23:29 -08009776 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009777}
9778
9779void AudioFlinger::MmapThread::checkInvalidTracks_l()
9780{
9781 for (const sp<MmapTrack> &track : mActiveTracks) {
9782 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009783 sp<MmapStreamCallback> callback = mCallback.promote();
9784 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009785 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009786 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009787 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009788 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9789 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9790 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009791 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009792 }
9793 }
9794}
9795
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009796void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009797{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009798 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9799 mAttr.content_type, mAttr.usage, mAttr.source);
9800 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009801 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009802 dprintf(fd, " No active clients\n");
9803 }
9804}
9805
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009806void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009807{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009808 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009809 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009810 dprintf(fd, " %zu Tracks\n", numtracks);
9811 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009812 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009813 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009814 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009815 for (size_t i = 0; i < numtracks ; ++i) {
9816 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009817 result.append(prefix);
9818 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009819 }
9820 } else {
9821 dprintf(fd, "\n");
9822 }
9823 write(fd, result.string(), result.size());
9824}
9825
9826AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9827 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009828 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009829 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009830 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009831 mStreamVolume(1.0),
9832 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009833 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009834{
9835 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9836 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9837 mMasterVolume = audioFlinger->masterVolume_l();
9838 mMasterMute = audioFlinger->masterMute_l();
9839 if (mAudioHwDev) {
9840 if (mAudioHwDev->canSetMasterVolume()) {
9841 mMasterVolume = 1.0;
9842 }
9843
9844 if (mAudioHwDev->canSetMasterMute()) {
9845 mMasterMute = false;
9846 }
9847 }
9848}
9849
9850void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9851 audio_stream_type_t streamType,
9852 audio_session_t sessionId,
9853 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009854 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009855 audio_port_handle_t portId)
9856{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009857 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009858 mStreamType = streamType;
9859}
9860
9861AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9862{
9863 Mutex::Autolock _l(mLock);
9864 AudioStreamOut *output = mOutput;
9865 mOutput = NULL;
9866 return output;
9867}
9868
9869void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9870{
9871 Mutex::Autolock _l(mLock);
9872 // Don't apply master volume in SW if our HAL can do it for us.
9873 if (mAudioHwDev &&
9874 mAudioHwDev->canSetMasterVolume()) {
9875 mMasterVolume = 1.0;
9876 } else {
9877 mMasterVolume = value;
9878 }
9879}
9880
9881void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9882{
9883 Mutex::Autolock _l(mLock);
9884 // Don't apply master mute in SW if our HAL can do it for us.
9885 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9886 mMasterMute = false;
9887 } else {
9888 mMasterMute = muted;
9889 }
9890}
9891
9892void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9893{
9894 Mutex::Autolock _l(mLock);
9895 if (stream == mStreamType) {
9896 mStreamVolume = value;
9897 broadcast_l();
9898 }
9899}
9900
9901float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9902{
9903 Mutex::Autolock _l(mLock);
9904 if (stream == mStreamType) {
9905 return mStreamVolume;
9906 }
9907 return 0.0f;
9908}
9909
9910void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9911{
9912 Mutex::Autolock _l(mLock);
9913 if (stream == mStreamType) {
9914 mStreamMute= muted;
9915 broadcast_l();
9916 }
9917}
9918
9919void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9920{
9921 Mutex::Autolock _l(mLock);
9922 if (streamType == mStreamType) {
9923 for (const sp<MmapTrack> &track : mActiveTracks) {
9924 track->invalidate();
9925 }
9926 broadcast_l();
9927 }
9928}
9929
9930void AudioFlinger::MmapPlaybackThread::processVolume_l()
9931{
9932 float volume;
9933
9934 if (mMasterMute || mStreamMute) {
9935 volume = 0;
9936 } else {
9937 volume = mMasterVolume * mStreamVolume;
9938 }
9939
9940 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009941
9942 // Convert volumes from float to 8.24
9943 uint32_t vol = (uint32_t)(volume * (1 << 24));
9944
9945 // Delegate volume control to effect in track effect chain if needed
9946 // only one effect chain can be present on DirectOutputThread, so if
9947 // there is one, the track is connected to it
9948 if (!mEffectChains.isEmpty()) {
9949 mEffectChains[0]->setVolume_l(&vol, &vol);
9950 volume = (float)vol / (1 << 24);
9951 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009952 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009953 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9954 mHalVolFloat = volume; // HW volume control worked, so update value.
9955 mNoCallbackWarningCount = 0;
9956 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009957 sp<MmapStreamCallback> callback = mCallback.promote();
9958 if (callback != 0) {
9959 int channelCount;
9960 if (isOutput()) {
9961 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9962 } else {
9963 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9964 }
9965 Vector<float> values;
9966 for (int i = 0; i < channelCount; i++) {
9967 values.add(volume);
9968 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009969 mHalVolFloat = volume; // SW volume control worked, so update value.
9970 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009971 mLock.unlock();
9972 callback->onVolumeChanged(mChannelMask, values);
9973 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009974 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009975 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9976 ALOGW("Could not set MMAP stream volume: no volume callback!");
9977 mNoCallbackWarningCount++;
9978 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009979 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009980 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009981 for (const sp<MmapTrack> &track : mActiveTracks) {
9982 track->setMetadataHasChanged();
9983 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009984 }
9985}
9986
Kevin Rocard069c2712018-03-29 19:09:14 -07009987void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9988{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009989 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
9990 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009991 }
9992 StreamOutHalInterface::SourceMetadata metadata;
9993 for (const sp<MmapTrack> &track : mActiveTracks) {
9994 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01009995 playback_track_metadata_v7_t trackMetadata;
9996 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009997 .usage = track->attributes().usage,
9998 .content_type = track->attributes().content_type,
9999 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010000 };
10001 trackMetadata.channel_mask = track->channelMask(),
10002 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10003 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010004 }
10005 mOutput->stream->updateSourceMetadata(metadata);
10006}
10007
Eric Laurent6acd1d42017-01-04 14:23:29 -080010008void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10009{
10010 if (!mMasterMute) {
10011 char value[PROPERTY_VALUE_MAX];
10012 if (property_get("ro.audio.silent", value, "0") > 0) {
10013 char *endptr;
10014 unsigned long ul = strtoul(value, &endptr, 0);
10015 if (*endptr == '\0' && ul != 0) {
10016 ALOGD("Silence is golden");
10017 // The setprop command will not allow a property to be changed after
10018 // the first time it is set, so we don't have to worry about un-muting.
10019 setMasterMute_l(true);
10020 }
10021 }
10022 }
10023}
10024
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010025void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10026{
10027 MmapThread::toAudioPortConfig(config);
10028 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10029 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10030 config->flags.output = mOutput->flags;
10031 }
10032}
10033
jiabinb7d8c5a2020-08-26 17:24:52 -070010034status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10035 int64_t *timeNanos)
10036{
10037 if (mOutput == nullptr) {
10038 return NO_INIT;
10039 }
10040 struct timespec timestamp;
10041 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10042 if (status == NO_ERROR) {
10043 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10044 }
10045 return status;
10046}
10047
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010048void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010049{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010050 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010051
Glenn Kastend3bb6452016-12-05 18:14:37 -080010052 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10053 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010054 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10055}
10056
10057AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10058 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010059 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010060 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010061 mInput(input)
10062{
10063 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10064 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10065}
10066
Eric Laurent331679c2018-04-16 17:03:16 -070010067status_t AudioFlinger::MmapCaptureThread::exitStandby()
10068{
Phil Burkf054fc32018-12-06 09:45:59 -080010069 {
10070 // mInput might have been cleared by clearInput()
10071 Mutex::Autolock _l(mLock);
10072 if (mInput != nullptr && mInput->stream != nullptr) {
10073 mInput->stream->setGain(1.0f);
10074 }
10075 }
Eric Laurent331679c2018-04-16 17:03:16 -070010076 return MmapThread::exitStandby();
10077}
10078
Eric Laurent6acd1d42017-01-04 14:23:29 -080010079AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10080{
10081 Mutex::Autolock _l(mLock);
10082 AudioStreamIn *input = mInput;
10083 mInput = NULL;
10084 return input;
10085}
Kevin Rocard069c2712018-03-29 19:09:14 -070010086
Eric Laurent331679c2018-04-16 17:03:16 -070010087
10088void AudioFlinger::MmapCaptureThread::processVolume_l()
10089{
10090 bool changed = false;
10091 bool silenced = false;
10092
10093 sp<MmapStreamCallback> callback = mCallback.promote();
10094 if (callback == 0) {
10095 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10096 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10097 mNoCallbackWarningCount++;
10098 }
10099 }
10100
10101 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10102 // track is silenced and unmute otherwise
10103 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10104 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10105 changed = true;
10106 silenced = mActiveTracks[i]->isSilenced_l();
10107 }
10108 }
10109
10110 if (changed) {
10111 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10112 }
10113}
10114
Kevin Rocard069c2712018-03-29 19:09:14 -070010115void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10116{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010117 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10118 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010119 }
10120 StreamInHalInterface::SinkMetadata metadata;
10121 for (const sp<MmapTrack> &track : mActiveTracks) {
10122 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010123 record_track_metadata_v7_t trackMetadata;
10124 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010125 .source = track->attributes().source,
10126 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010127 };
10128 trackMetadata.channel_mask = track->channelMask(),
10129 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10130 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010131 }
10132 mInput->stream->updateSinkMetadata(metadata);
10133}
10134
Eric Laurent5ada82e2019-08-29 17:53:54 -070010135void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010136{
10137 Mutex::Autolock _l(mLock);
10138 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010139 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010140 mActiveTracks[i]->setSilenced_l(silenced);
10141 broadcast_l();
10142 }
10143 }
10144}
10145
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010146void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10147{
10148 MmapThread::toAudioPortConfig(config);
10149 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10150 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10151 config->flags.input = mInput->flags;
10152 }
10153}
10154
jiabinb7d8c5a2020-08-26 17:24:52 -070010155status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10156 uint64_t *position, int64_t *timeNanos)
10157{
10158 if (mInput == nullptr) {
10159 return NO_INIT;
10160 }
10161 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10162}
10163
Glenn Kasten63238ef2015-03-02 15:50:29 -080010164} // namespace android