blob: 152274664b4e0c370b1e439dc92da4227709cee3 [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>
jiabin10d86fd2019-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))
Andy Hung6770c6f2015-04-07 13:43:36 -0700111template <typename T>
112static inline T min(const T& a, const T& b)
113{
114 return a < b ? a : b;
115}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700116
Eric Laurent81784c32012-11-19 14:55:58 -0800117namespace android {
118
119// retry counts for buffer fill timeout
120// 50 * ~20msecs = 1 second
121static const int8_t kMaxTrackRetries = 50;
122static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung0765c9a2021-04-27 17:46:12 -0700123
Eric Laurent81784c32012-11-19 14:55:58 -0800124// allow less retry attempts on direct output thread.
125// direct outputs can be a scarce resource in audio hardware and should
126// be released as quickly as possible.
Andy Hung0765c9a2021-04-27 17:46:12 -0700127// Notes:
128// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
129// in case the data write is bursty for the AudioTrack. The application
130// should endeavor to write at least once every kMaxTrackRetriesDirectMs
131// to prevent an underrun situation. If the data is bursty, then
132// the application can also throttle the data sent to be even.
133// 2) For compressed audio data, any data present in the AudioTrack buffer
134// will be sent and reset the retry count. This delivers data as
135// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
136// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
137// of data to be available, then any remaining data is delivered.
138// This is required to ensure the last bit of data is delivered before underrun.
139//
140// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
141// or the size of the HAL period for proportional / linear PCM tracks.
142static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800143
144// don't warn about blocked writes or record buffer overflows more often than this
145static const nsecs_t kWarningThrottleNs = seconds(5);
146
147// RecordThread loop sleep time upon application overrun or audio HAL read error
148static const int kRecordThreadSleepUs = 5000;
149
Eric Laurent10351942014-05-08 18:49:52 -0700150// maximum time to wait in sendConfigEvent_l() for a status to be received
151static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800152
153// minimum sleep time for the mixer thread loop when tracks are active but in underrun
154static const uint32_t kMinThreadSleepTimeUs = 5000;
155// maximum divider applied to the active sleep time in the mixer thread loop
156static const uint32_t kMaxThreadSleepTimeShift = 2;
157
Andy Hung09a50072014-02-27 14:30:47 -0800158// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700159// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800160static const uint32_t kMinNormalSinkBufferSizeMs = 20;
161// maximum normal sink buffer size
162static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700164// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
165// FIXME This should be based on experimentally observed scheduling jitter
166static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
167
Eric Laurent972a1732013-09-04 09:42:59 -0700168// Offloaded output thread standby delay: allows track transition without going to standby
169static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
170
Eric Laurent51716182016-02-29 18:00:56 -0800171// Direct output thread minimum sleep time in idle or active(underrun) state
172static const nsecs_t kDirectMinSleepTimeUs = 10000;
173
Glenn Kasten1b291842016-07-18 14:55:21 -0700174// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
175// balance between power consumption and latency, and allows threads to be scheduled reliably
176// by the CFS scheduler.
177// FIXME Express other hardcoded references to 20ms with references to this constant and move
178// it appropriately.
179#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800180
Eric Laurent81784c32012-11-19 14:55:58 -0800181// Whether to use fast mixer
182static const enum {
183 FastMixer_Never, // never initialize or use: for debugging only
184 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
185 // normal mixer multiplier is 1
186 FastMixer_Static, // initialize if needed, then use all the time if initialized,
187 // multiplier is calculated based on min & max normal mixer buffer size
188 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
189 // multiplier is calculated based on min & max normal mixer buffer size
190 // FIXME for FastMixer_Dynamic:
191 // Supporting this option will require fixing HALs that can't handle large writes.
192 // For example, one HAL implementation returns an error from a large write,
193 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
194 // We could either fix the HAL implementations, or provide a wrapper that breaks
195 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
196} kUseFastMixer = FastMixer_Static;
197
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700198// Whether to use fast capture
199static const enum {
200 FastCapture_Never, // never initialize or use: for debugging only
201 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
202 FastCapture_Static, // initialize if needed, then use all the time if initialized
203} kUseFastCapture = FastCapture_Static;
204
Eric Laurent81784c32012-11-19 14:55:58 -0800205// Priorities for requestPriority
206static const int kPriorityAudioApp = 2;
207static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700208static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800209
Glenn Kastenea38ee72016-04-18 11:08:01 -0700210// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
211// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
212// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700213
214// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800215static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800216
Glenn Kasten03490092014-05-27 12:30:54 -0700217// The minimum and maximum allowed values
218static const int kFastTrackMultiplierMin = 1;
219static const int kFastTrackMultiplierMax = 2;
220
221// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
222static int sFastTrackMultiplier = kFastTrackMultiplier;
223
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700224// See Thread::readOnlyHeap().
225// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
226// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
227// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700228static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700229
Eric Laurent81784c32012-11-19 14:55:58 -0800230// ----------------------------------------------------------------------------
231
Andy Hungb68f5eb2019-12-03 16:49:17 -0800232// TODO: move all toString helpers to audio.h
233// under #ifdef __cplusplus #endif
234static std::string patchSinksToString(const struct audio_patch *patch)
235{
236 std::stringstream ss;
237 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700238 if (i > 0) {
239 ss << "|";
240 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800241 ss << "(" << toString(patch->sinks[i].ext.device.type)
242 << ", " << patch->sinks[i].ext.device.address << ")";
243 }
244 return ss.str();
245}
246
247static std::string patchSourcesToString(const struct audio_patch *patch)
248{
249 std::stringstream ss;
250 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700251 if (i > 0) {
252 ss << "|";
253 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800254 ss << "(" << toString(patch->sources[i].ext.device.type)
255 << ", " << patch->sources[i].ext.device.address << ")";
256 }
257 return ss.str();
258}
259
Glenn Kasten03490092014-05-27 12:30:54 -0700260static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
261
262static void sFastTrackMultiplierInit()
263{
264 char value[PROPERTY_VALUE_MAX];
265 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
266 char *endptr;
267 unsigned long ul = strtoul(value, &endptr, 0);
268 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
269 sFastTrackMultiplier = (int) ul;
270 }
271 }
272}
273
274// ----------------------------------------------------------------------------
275
Eric Laurent81784c32012-11-19 14:55:58 -0800276#ifdef ADD_BATTERY_DATA
277// To collect the amplifier usage
278static void addBatteryData(uint32_t params) {
279 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
280 if (service == NULL) {
281 // it already logged
282 return;
283 }
284
285 service->addBatteryData(params);
286}
287#endif
288
Andy Hung3f0c9022016-01-15 17:49:46 -0800289// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
290struct {
291 // call when you acquire a partial wakelock
292 void acquire(const sp<IBinder> &wakeLockToken) {
293 pthread_mutex_lock(&mLock);
294 if (wakeLockToken.get() == nullptr) {
295 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
296 } else {
297 if (mCount == 0) {
298 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
299 }
300 ++mCount;
301 }
302 pthread_mutex_unlock(&mLock);
303 }
304
305 // call when you release a partial wakelock.
306 void release(const sp<IBinder> &wakeLockToken) {
307 if (wakeLockToken.get() == nullptr) {
308 return;
309 }
310 pthread_mutex_lock(&mLock);
311 if (--mCount < 0) {
312 ALOGE("negative wakelock count");
313 mCount = 0;
314 }
315 pthread_mutex_unlock(&mLock);
316 }
317
318 // retrieves the boottime timebase offset from monotonic.
319 int64_t getBoottimeOffset() {
320 pthread_mutex_lock(&mLock);
321 int64_t boottimeOffset = mBoottimeOffset;
322 pthread_mutex_unlock(&mLock);
323 return boottimeOffset;
324 }
325
326 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
327 // and the selected timebase.
328 // Currently only TIMEBASE_BOOTTIME is allowed.
329 //
330 // This only needs to be called upon acquiring the first partial wakelock
331 // after all other partial wakelocks are released.
332 //
333 // We do an empirical measurement of the offset rather than parsing
334 // /proc/timer_list since the latter is not a formal kernel ABI.
335 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
336 int clockbase;
337 switch (timebase) {
338 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
339 clockbase = SYSTEM_TIME_BOOTTIME;
340 break;
341 default:
342 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
343 break;
344 }
345 // try three times to get the clock offset, choose the one
346 // with the minimum gap in measurements.
347 const int tries = 3;
348 nsecs_t bestGap, measured;
349 for (int i = 0; i < tries; ++i) {
350 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
351 const nsecs_t tbase = systemTime(clockbase);
352 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
353 const nsecs_t gap = tmono2 - tmono;
354 if (i == 0 || gap < bestGap) {
355 bestGap = gap;
356 measured = tbase - ((tmono + tmono2) >> 1);
357 }
358 }
359
360 // to avoid micro-adjusting, we don't change the timebase
361 // unless it is significantly different.
362 //
363 // Assumption: It probably takes more than toleranceNs to
364 // suspend and resume the device.
365 static int64_t toleranceNs = 10000; // 10 us
366 if (llabs(*offset - measured) > toleranceNs) {
367 ALOGV("Adjusting timebase offset old: %lld new: %lld",
368 (long long)*offset, (long long)measured);
369 *offset = measured;
370 }
371 }
372
373 pthread_mutex_t mLock;
374 int32_t mCount;
375 int64_t mBoottimeOffset;
376} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800377
378// ----------------------------------------------------------------------------
379// CPU Stats
380// ----------------------------------------------------------------------------
381
382class CpuStats {
383public:
384 CpuStats();
385 void sample(const String8 &title);
386#ifdef DEBUG_CPU_USAGE
387private:
388 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700389 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800390
Andy Hung16698b82018-08-01 10:48:38 -0700391 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800392
393 int mCpuNum; // thread's current CPU number
394 int mCpukHz; // frequency of thread's current CPU in kHz
395#endif
396};
397
398CpuStats::CpuStats()
399#ifdef DEBUG_CPU_USAGE
400 : mCpuNum(-1), mCpukHz(-1)
401#endif
402{
403}
404
Glenn Kasten0f11b512014-01-31 16:18:54 -0800405void CpuStats::sample(const String8 &title
406#ifndef DEBUG_CPU_USAGE
407 __unused
408#endif
409 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800410#ifdef DEBUG_CPU_USAGE
411 // get current thread's delta CPU time in wall clock ns
412 double wcNs;
413 bool valid = mCpuUsage.sampleAndEnable(wcNs);
414
415 // record sample for wall clock statistics
416 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700417 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800418 }
419
420 // get the current CPU number
421 int cpuNum = sched_getcpu();
422
423 // get the current CPU frequency in kHz
424 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
425
426 // check if either CPU number or frequency changed
427 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
428 mCpuNum = cpuNum;
429 mCpukHz = cpukHz;
430 // ignore sample for purposes of cycles
431 valid = false;
432 }
433
434 // if no change in CPU number or frequency, then record sample for cycle statistics
435 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700436 const double cycles = wcNs * cpukHz * 0.000001;
437 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800438 }
439
Eric Tan5b13ff82018-07-27 11:20:17 -0700440 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800441 // mCpuUsage.elapsed() is expensive, so don't call it every loop
442 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700443 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800444 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700445 const double perLoop = elapsed / (double) n;
446 const double perLoop100 = perLoop * 0.01;
447 const double perLoop1k = perLoop * 0.001;
448 const double mean = mWcStats.getMean();
449 const double stddev = mWcStats.getStdDev();
450 const double minimum = mWcStats.getMin();
451 const double maximum = mWcStats.getMax();
452 const double meanCycles = mHzStats.getMean();
453 const double stddevCycles = mHzStats.getStdDev();
454 const double minCycles = mHzStats.getMin();
455 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800456 mCpuUsage.resetElapsed();
457 mWcStats.reset();
458 mHzStats.reset();
459 ALOGD("CPU usage for %s over past %.1f secs\n"
460 " (%u mixer loops at %.1f mean ms per loop):\n"
461 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
462 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
463 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
464 title.string(),
465 elapsed * .000000001, n, perLoop * .000001,
466 mean * .001,
467 stddev * .001,
468 minimum * .001,
469 maximum * .001,
470 mean / perLoop100,
471 stddev / perLoop100,
472 minimum / perLoop100,
473 maximum / perLoop100,
474 meanCycles / perLoop1k,
475 stddevCycles / perLoop1k,
476 minCycles / perLoop1k,
477 maxCycles / perLoop1k);
478
479 }
480 }
481#endif
482};
483
484// ----------------------------------------------------------------------------
485// ThreadBase
486// ----------------------------------------------------------------------------
487
Glenn Kasten97b7b752014-09-28 13:04:24 -0700488// static
489const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
490{
491 switch (type) {
492 case MIXER:
493 return "MIXER";
494 case DIRECT:
495 return "DIRECT";
496 case DUPLICATING:
497 return "DUPLICATING";
498 case RECORD:
499 return "RECORD";
500 case OFFLOAD:
501 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700502 case MMAP_PLAYBACK:
503 return "MMAP_PLAYBACK";
504 case MMAP_CAPTURE:
505 return "MMAP_CAPTURE";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700506 default:
507 return "unknown";
508 }
509}
510
Eric Laurent81784c32012-11-19 14:55:58 -0800511AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700512 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800513 : Thread(false /*canCallJava*/),
514 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700515 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700516 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
517 isOut),
518 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700519 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800520 // are set by PlaybackThread::readOutputParameters_l() or
521 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700522 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabin10d86fd2019-10-31 17:20:42 -0700523 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700524 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800525 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700526 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800527 mSystemReady(systemReady),
528 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800529{
Andy Hungcf10d742020-04-28 15:38:24 -0700530 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700531 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800532}
533
534AudioFlinger::ThreadBase::~ThreadBase()
535{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700536 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700537 mConfigEvents.clear();
538
Eric Laurent81784c32012-11-19 14:55:58 -0800539 // do not lock the mutex in destructor
540 releaseWakeLock_l();
541 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800542 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800543 binder->unlinkToDeath(mDeathRecipient);
544 }
Andy Hungd0979812019-02-21 15:51:44 -0800545
546 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800547}
548
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700549status_t AudioFlinger::ThreadBase::readyToRun()
550{
551 status_t status = initCheck();
552 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800553 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700554 } else {
555 ALOGE("No working audio driver found.");
556 }
557 return status;
558}
559
Eric Laurent81784c32012-11-19 14:55:58 -0800560void AudioFlinger::ThreadBase::exit()
561{
562 ALOGV("ThreadBase::exit");
563 // do any cleanup required for exit to succeed
564 preExit();
565 {
566 // This lock prevents the following race in thread (uniprocessor for illustration):
567 // if (!exitPending()) {
568 // // context switch from here to exit()
569 // // exit() calls requestExit(), what exitPending() observes
570 // // exit() calls signal(), which is dropped since no waiters
571 // // context switch back from exit() to here
572 // mWaitWorkCV.wait(...);
573 // // now thread is hung
574 // }
575 AutoMutex lock(mLock);
576 requestExit();
577 mWaitWorkCV.broadcast();
578 }
579 // When Thread::requestExitAndWait is made virtual and this method is renamed to
580 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
581 requestExitAndWait();
582}
583
584status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
585{
Eric Laurent81784c32012-11-19 14:55:58 -0800586 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
587 Mutex::Autolock _l(mLock);
588
Eric Laurent10351942014-05-08 18:49:52 -0700589 return sendSetParameterConfigEvent_l(keyValuePairs);
590}
591
592// sendConfigEvent_l() must be called with ThreadBase::mLock held
593// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
594status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
595{
596 status_t status = NO_ERROR;
597
Eric Laurent72e3f392015-05-20 14:43:50 -0700598 if (event->mRequiresSystemReady && !mSystemReady) {
599 event->mWaitStatus = false;
600 mPendingConfigEvents.add(event);
601 return status;
602 }
Eric Laurent10351942014-05-08 18:49:52 -0700603 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700604 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800605 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700606 mLock.unlock();
607 {
608 Mutex::Autolock _l(event->mLock);
609 while (event->mWaitStatus) {
610 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
611 event->mStatus = TIMED_OUT;
612 event->mWaitStatus = false;
613 }
614 }
615 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800616 }
Eric Laurent10351942014-05-08 18:49:52 -0700617 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800618 return status;
619}
620
Eric Laurent09f1ed22019-04-24 17:45:17 -0700621void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
622 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800623{
624 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700625 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800626}
627
628// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700629void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
630 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
Andy Hungd0979812019-02-21 15:51:44 -0800632 // The audio statistics history is exponentially weighted to forget events
633 // about five or more seconds in the past. In order to have
634 // crisper statistics for mediametrics, we reset the statistics on
635 // an IoConfigEvent, to reflect different properties for a new device.
636 mIoJitterMs.reset();
637 mLatencyMs.reset();
638 mProcessTimeMs.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100639 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800640
Eric Laurent09f1ed22019-04-24 17:45:17 -0700641 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700642 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800643}
644
Mikhail Naganov83f04272017-02-07 10:45:09 -0800645void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700646{
647 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800648 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700649}
650
Eric Laurent81784c32012-11-19 14:55:58 -0800651// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800652void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
653 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800654{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800655 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700656 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800657}
658
Eric Laurent10351942014-05-08 18:49:52 -0700659// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
660status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800661{
Andy Hung2ddee192015-12-18 17:34:44 -0800662 sp<ConfigEvent> configEvent;
663 AudioParameter param(keyValuePair);
664 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700665 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800666 setMasterMono_l(value != 0);
667 if (param.size() == 1) {
668 return NO_ERROR; // should be a solo parameter - we don't pass down
669 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700670 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800671 configEvent = new SetParameterConfigEvent(param.toString());
672 } else {
673 configEvent = new SetParameterConfigEvent(keyValuePair);
674 }
Eric Laurent10351942014-05-08 18:49:52 -0700675 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700676}
677
Eric Laurent1c333e22014-05-20 10:48:17 -0700678status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
679 const struct audio_patch *patch,
680 audio_patch_handle_t *handle)
681{
682 Mutex::Autolock _l(mLock);
683 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
684 status_t status = sendConfigEvent_l(configEvent);
685 if (status == NO_ERROR) {
686 CreateAudioPatchConfigEventData *data =
687 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
688 *handle = data->mHandle;
689 }
690 return status;
691}
692
693status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
694 const audio_patch_handle_t handle)
695{
696 Mutex::Autolock _l(mLock);
697 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
698 return sendConfigEvent_l(configEvent);
699}
700
jiabin10d86fd2019-10-31 17:20:42 -0700701status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
702 const DeviceDescriptorBaseVector& outDevices)
703{
704 if (type() != RECORD) {
705 // The update out device operation is only for record thread.
706 return INVALID_OPERATION;
707 }
708 Mutex::Autolock _l(mLock);
709 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
710 return sendConfigEvent_l(configEvent);
711}
712
Eric Laurent1c333e22014-05-20 10:48:17 -0700713
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700714// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700715void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700716{
Eric Laurent10351942014-05-08 18:49:52 -0700717 bool configChanged = false;
718
Eric Laurent81784c32012-11-19 14:55:58 -0800719 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700720 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700721 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800722 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700723 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700724 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700725 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
726 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800727 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700728 true /*asynchronous*/);
729 if (err != 0) {
730 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700731 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700732 }
733 } break;
734 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700735 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700736 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700737 } break;
738 case CFG_EVENT_SET_PARAMETER: {
739 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
740 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
741 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700742 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
743 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700744 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700745 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700746 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabin10d86fd2019-10-31 17:20:42 -0700747 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700748 CreateAudioPatchConfigEventData *data =
749 (CreateAudioPatchConfigEventData *)event->mData.get();
750 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabin10d86fd2019-10-31 17:20:42 -0700751 const DeviceTypeSet newDevices = getDeviceTypes();
752 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
753 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
754 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700755 } break;
756 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabin10d86fd2019-10-31 17:20:42 -0700757 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700758 ReleaseAudioPatchConfigEventData *data =
759 (ReleaseAudioPatchConfigEventData *)event->mData.get();
760 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabin10d86fd2019-10-31 17:20:42 -0700761 const DeviceTypeSet newDevices = getDeviceTypes();
762 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
763 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
764 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
765 } break;
766 case CFG_EVENT_UPDATE_OUT_DEVICE: {
767 UpdateOutDevicesConfigEventData *data =
768 (UpdateOutDevicesConfigEventData *)event->mData.get();
769 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700770 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700771 default:
Eric Laurent10351942014-05-08 18:49:52 -0700772 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700773 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800774 }
Eric Laurent10351942014-05-08 18:49:52 -0700775 {
776 Mutex::Autolock _l(event->mLock);
777 if (event->mWaitStatus) {
778 event->mWaitStatus = false;
779 event->mCond.signal();
780 }
781 }
782 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
783 }
784
785 if (configChanged) {
786 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800787 }
Eric Laurent81784c32012-11-19 14:55:58 -0800788}
789
Marco Nelissenb2208842014-02-07 14:00:50 -0800790String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
791 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700792 const audio_channel_representation_t representation =
793 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794
795 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800796 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700797 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
798 if (output) {
799 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
800 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
801 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
802 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
803 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
804 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
805 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
806 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
807 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
808 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
809 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
810 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
811 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
812 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
813 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
814 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
815 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
816 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700817 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
818 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800819 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
820 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700821 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
822 } else {
823 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
824 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
825 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
826 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
827 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
828 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
829 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
830 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
831 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
832 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
833 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
834 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700835 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
836 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
837 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
838 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
839 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
840 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700841 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
842 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
843 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
844 }
845 const int len = s.length();
846 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700847 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700848 s.unlockBuffer(len - 2); // remove trailing ", "
849 }
850 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800851 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700852 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
853 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
854 return s;
855 default:
856 s.appendFormat("unknown mask, representation:%d bits:%#x",
857 representation, audio_channel_mask_get_bits(mask));
858 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800859 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800860}
861
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700862void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800863{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800864 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
865 this, mThreadName, getTid(), type(), threadTypeToString(type()));
866
Eric Laurent81784c32012-11-19 14:55:58 -0800867 bool locked = AudioFlinger::dumpTryLock(mLock);
868 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800869 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800870 }
871
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700872 dumpBase_l(fd, args);
873 dumpInternals_l(fd, args);
874 dumpTracks_l(fd, args);
875 dumpEffectChains_l(fd, args);
876
877 if (locked) {
878 mLock.unlock();
879 }
880
881 dprintf(fd, " Local log:\n");
882 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
883}
884
885void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
886{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700887 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700888 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700889 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700890 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700891 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700892 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700893 dprintf(fd, " Channel count: %u\n", mChannelCount);
894 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800895 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700896 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700897 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700898 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800899 size_t numConfig = mConfigEvents.size();
900 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700901 const size_t SIZE = 256;
902 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800903 for (size_t i = 0; i < numConfig; i++) {
904 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700905 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800906 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700907 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800908 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700909 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800910 }
Andy Hung293558a2017-03-21 12:19:20 -0700911 // Note: output device may be used by capture threads for effects such as AEC.
jiabin10d86fd2019-10-31 17:20:42 -0700912 dprintf(fd, " Output devices: %s (%s)\n",
913 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
914 dprintf(fd, " Input device: %#x (%s)\n",
915 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800916 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800917
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700918 // Dump timestamp statistics for the Thread types that support it.
919 if (mType == RECORD
920 || mType == MIXER
921 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700922 || mType == DIRECT
923 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700924 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700925 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700926 }
927
Andy Hung446f4df2019-02-21 12:26:41 -0800928 if (mLastIoBeginNs > 0) { // MMAP may not set this
929 dprintf(fd, " Last %s occurred (msecs): %lld\n",
930 isOutput() ? "write" : "read",
931 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
932 }
933
934 if (mProcessTimeMs.getN() > 0) {
935 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
936 }
937
938 if (mIoJitterMs.getN() > 0) {
939 dprintf(fd, " Hal %s jitter ms stats: %s\n",
940 isOutput() ? "write" : "read",
941 mIoJitterMs.toString().c_str());
942 }
943
Andy Hunge6c37112019-02-26 17:38:10 -0800944 if (mLatencyMs.getN() > 0) {
945 dprintf(fd, " Threadloop %s latency stats: %s\n",
946 isOutput() ? "write" : "read",
947 mLatencyMs.toString().c_str());
948 }
Eric Laurent81784c32012-11-19 14:55:58 -0800949}
950
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700951void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800952{
953 const size_t SIZE = 256;
954 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800955
Marco Nelissenb2208842014-02-07 14:00:50 -0800956 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000957 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800958 write(fd, buffer, strlen(buffer));
959
Marco Nelissenb2208842014-02-07 14:00:50 -0800960 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800961 sp<EffectChain> chain = mEffectChains[i];
962 if (chain != 0) {
963 chain->dump(fd, args);
964 }
965 }
966}
967
Andy Hungdae27702016-10-31 14:01:16 -0700968void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800969{
970 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700971 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800972}
973
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100974String16 AudioFlinger::ThreadBase::getWakeLockTag()
975{
976 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800977 case MIXER:
978 return String16("AudioMix");
979 case DIRECT:
980 return String16("AudioDirectOut");
981 case DUPLICATING:
982 return String16("AudioDup");
983 case RECORD:
984 return String16("AudioIn");
985 case OFFLOAD:
986 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -0700987 case MMAP_PLAYBACK:
988 return String16("MmapPlayback");
989 case MMAP_CAPTURE:
990 return String16("MmapCapture");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800991 default:
992 ALOG_ASSERT(false);
993 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100994 }
995}
996
Andy Hungdae27702016-10-31 14:01:16 -0700997void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800998{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800999 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001000 if (mPowerManager != 0) {
1001 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001002 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
1003 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001004 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001005 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001006 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001007 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001008 if (status == NO_ERROR) {
1009 mWakeLockToken = binder;
1010 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001011 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001012 }
Wei Jia3f273d12015-11-24 09:06:49 -08001013
Andy Hung3f0c9022016-01-15 17:49:46 -08001014 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001015 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1016 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001017}
1018
1019void AudioFlinger::ThreadBase::releaseWakeLock()
1020{
1021 Mutex::Autolock _l(mLock);
1022 releaseWakeLock_l();
1023}
1024
1025void AudioFlinger::ThreadBase::releaseWakeLock_l()
1026{
Andy Hung3f0c9022016-01-15 17:49:46 -08001027 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001028 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001029 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001030 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001031 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1032 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001033 }
1034 mWakeLockToken.clear();
1035 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001036}
1037
1038void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001039 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001040 // use checkService() to avoid blocking if power service is not up yet
1041 sp<IBinder> binder =
1042 defaultServiceManager()->checkService(String16("power"));
1043 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001044 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001045 } else {
1046 mPowerManager = interface_cast<IPowerManager>(binder);
1047 binder->linkToDeath(mDeathRecipient);
1048 }
1049 }
1050}
1051
Andy Hungd01b0f12016-11-07 16:10:30 -08001052void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001053 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001054
1055#if !LOG_NDEBUG
1056 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001057 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001058 s << uid << " ";
1059 }
1060 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1061#endif
1062
Andy Hung438e7572015-12-14 15:51:17 -08001063 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1064 if (mSystemReady) {
1065 ALOGE("no wake lock to update, but system ready!");
1066 } else {
1067 ALOGW("no wake lock to update, system not ready yet");
1068 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001069 return;
1070 }
1071 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001072 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
1073 status_t status = mPowerManager->updateWakeLockUids(
1074 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
1075 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001076 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001077 }
1078}
1079
Eric Laurent81784c32012-11-19 14:55:58 -08001080void AudioFlinger::ThreadBase::clearPowerManager()
1081{
1082 Mutex::Autolock _l(mLock);
1083 releaseWakeLock_l();
1084 mPowerManager.clear();
1085}
1086
jiabin10d86fd2019-10-31 17:20:42 -07001087void AudioFlinger::ThreadBase::updateOutDevices(
1088 const DeviceDescriptorBaseVector& outDevices __unused)
1089{
1090 ALOGE("%s should only be called in RecordThread", __func__);
1091}
1092
Glenn Kasten0f11b512014-01-31 16:18:54 -08001093void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001094{
1095 sp<ThreadBase> thread = mThread.promote();
1096 if (thread != 0) {
1097 thread->clearPowerManager();
1098 }
1099 ALOGW("power manager service died !!!");
1100}
1101
Eric Laurent81784c32012-11-19 14:55:58 -08001102void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001103 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001104{
1105 sp<EffectChain> chain = getEffectChain_l(sessionId);
1106 if (chain != 0) {
1107 if (type != NULL) {
1108 chain->setEffectSuspended_l(type, suspend);
1109 } else {
1110 chain->setEffectSuspendedAll_l(suspend);
1111 }
1112 }
1113
1114 updateSuspendedSessions_l(type, suspend, sessionId);
1115}
1116
1117void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1118{
1119 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1120 if (index < 0) {
1121 return;
1122 }
1123
1124 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1125 mSuspendedSessions.valueAt(index);
1126
1127 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001128 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001129 for (int j = 0; j < desc->mRefCount; j++) {
1130 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1131 chain->setEffectSuspendedAll_l(true);
1132 } else {
1133 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1134 desc->mType.timeLow);
1135 chain->setEffectSuspended_l(&desc->mType, true);
1136 }
1137 }
1138 }
1139}
1140
1141void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1142 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001143 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001144{
1145 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1146
1147 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1148
1149 if (suspend) {
1150 if (index >= 0) {
1151 sessionEffects = mSuspendedSessions.valueAt(index);
1152 } else {
1153 mSuspendedSessions.add(sessionId, sessionEffects);
1154 }
1155 } else {
1156 if (index < 0) {
1157 return;
1158 }
1159 sessionEffects = mSuspendedSessions.valueAt(index);
1160 }
1161
1162
1163 int key = EffectChain::kKeyForSuspendAll;
1164 if (type != NULL) {
1165 key = type->timeLow;
1166 }
1167 index = sessionEffects.indexOfKey(key);
1168
1169 sp<SuspendedSessionDesc> desc;
1170 if (suspend) {
1171 if (index >= 0) {
1172 desc = sessionEffects.valueAt(index);
1173 } else {
1174 desc = new SuspendedSessionDesc();
1175 if (type != NULL) {
1176 desc->mType = *type;
1177 }
1178 sessionEffects.add(key, desc);
1179 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1180 }
1181 desc->mRefCount++;
1182 } else {
1183 if (index < 0) {
1184 return;
1185 }
1186 desc = sessionEffects.valueAt(index);
1187 if (--desc->mRefCount == 0) {
1188 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1189 sessionEffects.removeItemsAt(index);
1190 if (sessionEffects.isEmpty()) {
1191 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1192 sessionId);
1193 mSuspendedSessions.removeItem(sessionId);
1194 }
1195 }
1196 }
1197 if (!sessionEffects.isEmpty()) {
1198 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1199 }
1200}
1201
Eric Laurent5d885392019-12-13 10:56:31 -08001202void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1203 audio_session_t sessionId,
1204 bool threadLocked) {
1205 if (!threadLocked) {
1206 mLock.lock();
1207 }
Eric Laurent81784c32012-11-19 14:55:58 -08001208
Eric Laurent81784c32012-11-19 14:55:58 -08001209 if (mType != RECORD) {
1210 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1211 // another session. This gives the priority to well behaved effect control panels
1212 // and applications not using global effects.
1213 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1214 // global effects
Eric Laurenta20c4e92019-11-12 15:55:51 -08001215 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001216 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1217 }
1218 }
1219
Eric Laurent5d885392019-12-13 10:56:31 -08001220 if (!threadLocked) {
1221 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001222 }
1223}
1224
Eric Laurent4c415062016-06-17 16:14:16 -07001225// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1226status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1227 const effect_descriptor_t *desc, audio_session_t sessionId)
1228{
Eric Laurenta20c4e92019-11-12 15:55:51 -08001229 // No global output effect sessions on record threads
1230 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1231 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001232 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1233 desc->name, mThreadName);
1234 return BAD_VALUE;
1235 }
1236 // only pre processing effects on record thread
1237 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1238 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1239 desc->name, mThreadName);
1240 return BAD_VALUE;
1241 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001242
1243 // always allow effects without processing load or latency
1244 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1245 return NO_ERROR;
1246 }
1247
Eric Laurent4c415062016-06-17 16:14:16 -07001248 audio_input_flags_t flags = mInput->flags;
1249 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1250 if (flags & AUDIO_INPUT_FLAG_RAW) {
1251 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1252 desc->name, mThreadName);
1253 return BAD_VALUE;
1254 }
1255 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1256 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1257 desc->name, mThreadName);
1258 return BAD_VALUE;
1259 }
1260 }
1261 return NO_ERROR;
1262}
1263
1264// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1265status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1266 const effect_descriptor_t *desc, audio_session_t sessionId)
1267{
1268 // no preprocessing on playback threads
1269 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1270 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1271 " thread %s", desc->name, mThreadName);
1272 return BAD_VALUE;
1273 }
1274
Eric Laurent3e4de772017-07-16 16:55:08 -07001275 // always allow effects without processing load or latency
1276 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1277 return NO_ERROR;
1278 }
1279
Eric Laurent4c415062016-06-17 16:14:16 -07001280 switch (mType) {
1281 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001282#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001283 // Reject any effect on mixer multichannel sinks.
1284 // TODO: fix both format and multichannel issues with effects.
1285 if (mChannelCount != FCC_2) {
1286 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1287 " thread %s", desc->name, mChannelCount, mThreadName);
1288 return BAD_VALUE;
1289 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001290#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001291 audio_output_flags_t flags = mOutput->flags;
1292 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1293 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1294 // global effects are applied only to non fast tracks if they are SW
1295 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1296 break;
1297 }
1298 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1299 // only post processing on output stage session
1300 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1301 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1302 " on output stage session", desc->name);
1303 return BAD_VALUE;
1304 }
Eric Laurenta20c4e92019-11-12 15:55:51 -08001305 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1306 // only post processing on output stage session
1307 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1308 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1309 " on device session", desc->name);
1310 return BAD_VALUE;
1311 }
Eric Laurent4c415062016-06-17 16:14:16 -07001312 } else {
1313 // no restriction on effects applied on non fast tracks
1314 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1315 break;
1316 }
1317 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001318
Eric Laurent4c415062016-06-17 16:14:16 -07001319 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1320 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1321 desc->name);
1322 return BAD_VALUE;
1323 }
1324 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1325 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1326 " in fast mode", desc->name);
1327 return BAD_VALUE;
1328 }
1329 }
1330 } break;
1331 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001332 // nothing actionable on offload threads, if the effect:
1333 // - is offloadable: the effect can be created
1334 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1335 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001336 break;
1337 case DIRECT:
1338 // Reject any effect on Direct output threads for now, since the format of
1339 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1340 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1341 desc->name, mThreadName);
1342 return BAD_VALUE;
1343 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001344#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001345 // Reject any effect on mixer multichannel sinks.
1346 // TODO: fix both format and multichannel issues with effects.
1347 if (mChannelCount != FCC_2) {
1348 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1349 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1350 return BAD_VALUE;
1351 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001352#endif
Eric Laurenta20c4e92019-11-12 15:55:51 -08001353 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001354 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1355 " thread %s", desc->name, mThreadName);
1356 return BAD_VALUE;
1357 }
1358 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1359 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1360 " DUPLICATING thread %s", desc->name, mThreadName);
1361 return BAD_VALUE;
1362 }
1363 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1364 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1365 " DUPLICATING thread %s", desc->name, mThreadName);
1366 return BAD_VALUE;
1367 }
1368 break;
1369 default:
1370 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1371 }
1372
1373 return NO_ERROR;
1374}
1375
Eric Laurent81784c32012-11-19 14:55:58 -08001376// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1377sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1378 const sp<AudioFlinger::Client>& client,
1379 const sp<IEffectClient>& effectClient,
1380 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001381 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001382 effect_descriptor_t *desc,
1383 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001384 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001385 bool pinned,
1386 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001387{
1388 sp<EffectModule> effect;
1389 sp<EffectHandle> handle;
1390 status_t lStatus;
1391 sp<EffectChain> chain;
1392 bool chainCreated = false;
1393 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001394 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001395
1396 lStatus = initCheck();
1397 if (lStatus != NO_ERROR) {
1398 ALOGW("createEffect_l() Audio driver not initialized.");
1399 goto Exit;
1400 }
1401
Eric Laurent81784c32012-11-19 14:55:58 -08001402 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1403
1404 { // scope for mLock
1405 Mutex::Autolock _l(mLock);
1406
Eric Laurent4c415062016-06-17 16:14:16 -07001407 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001408 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001409 goto Exit;
1410 }
1411
Eric Laurent81784c32012-11-19 14:55:58 -08001412 // check for existing effect chain with the requested audio session
1413 chain = getEffectChain_l(sessionId);
1414 if (chain == 0) {
1415 // create a new chain for this session
1416 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1417 chain = new EffectChain(this, sessionId);
1418 addEffectChain_l(chain);
1419 chain->setStrategy(getStrategyForSession_l(sessionId));
1420 chainCreated = true;
1421 } else {
1422 effect = chain->getEffectFromDesc_l(desc);
1423 }
1424
1425 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1426
1427 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001428 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001429 // create a new effect module if none present in the chain
Eric Laurent5d885392019-12-13 10:56:31 -08001430 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001431 if (lStatus != NO_ERROR) {
1432 goto Exit;
1433 }
1434 effectCreated = true;
1435
jiabin10d86fd2019-10-31 17:20:42 -07001436 // FIXME: use vector of device and address when effect interface is ready.
jiabinb8269fd2019-11-11 12:16:27 -08001437 effect->setDevices(outDeviceTypeAddrs());
1438 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001439 effect->setMode(mAudioFlinger->getMode());
1440 effect->setAudioSource(mAudioSource);
1441 }
1442 // create effect handle and connect it to effect module
1443 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001444 lStatus = handle->initCheck();
1445 if (lStatus == OK) {
1446 lStatus = effect->addHandle(handle.get());
1447 }
Eric Laurent81784c32012-11-19 14:55:58 -08001448 if (enabled != NULL) {
1449 *enabled = (int)effect->isEnabled();
1450 }
1451 }
1452
1453Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001454 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001455 Mutex::Autolock _l(mLock);
1456 if (effectCreated) {
1457 chain->removeEffect_l(effect);
1458 }
Eric Laurent81784c32012-11-19 14:55:58 -08001459 if (chainCreated) {
1460 removeEffectChain_l(chain);
1461 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001462 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001463 }
1464
Glenn Kasten9156ef32013-08-06 15:39:08 -07001465 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001466 return handle;
1467}
1468
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001469void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1470 bool unpinIfLast)
1471{
1472 bool remove = false;
1473 sp<EffectModule> effect;
1474 {
1475 Mutex::Autolock _l(mLock);
Eric Laurente0b9a362019-12-16 19:34:05 -08001476 sp<EffectBase> effectBase = handle->effect().promote();
1477 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001478 return;
1479 }
Eric Laurent9b2064c2019-11-22 17:25:04 -08001480 effect = effectBase->asEffectModule();
1481 if (effect == nullptr) {
1482 return;
1483 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001484 // restore suspended effects if the disconnected handle was enabled and the last one.
1485 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1486 if (remove) {
1487 removeEffect_l(effect, true);
1488 }
1489 }
1490 if (remove) {
1491 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001492 if (handle->enabled()) {
Eric Laurent5d885392019-12-13 10:56:31 -08001493 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001494 }
1495 }
1496}
1497
Eric Laurent5d885392019-12-13 10:56:31 -08001498void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001499 if (isOffloadOrMmap()) {
Eric Laurent5d885392019-12-13 10:56:31 -08001500 Mutex::Autolock _l(mLock);
1501 broadcast_l();
1502 }
1503 if (!effect->isOffloadable()) {
1504 if (mType == ThreadBase::OFFLOAD) {
1505 PlaybackThread *t = (PlaybackThread *)this;
1506 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1507 }
1508 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1509 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1510 }
1511 }
1512}
1513
1514void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001515 if (isOffloadOrMmap()) {
Eric Laurent5d885392019-12-13 10:56:31 -08001516 Mutex::Autolock _l(mLock);
1517 broadcast_l();
1518 }
1519}
1520
Glenn Kastend848eb42016-03-08 13:42:11 -08001521sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1522 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001523{
1524 Mutex::Autolock _l(mLock);
1525 return getEffect_l(sessionId, effectId);
1526}
1527
Glenn Kastend848eb42016-03-08 13:42:11 -08001528sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1529 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001530{
1531 sp<EffectChain> chain = getEffectChain_l(sessionId);
1532 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1533}
1534
Eric Laurent6c796322019-04-09 14:13:17 -07001535std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1536{
1537 sp<EffectChain> chain = getEffectChain_l(sessionId);
1538 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1539}
1540
Eric Laurent81784c32012-11-19 14:55:58 -08001541// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1542// PlaybackThread::mLock held
1543status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1544{
1545 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001546 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001547 sp<EffectChain> chain = getEffectChain_l(sessionId);
1548 bool chainCreated = false;
1549
Eric Laurent5baf2af2013-09-12 17:37:00 -07001550 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001551 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001552 this, effect->desc().name, effect->desc().flags);
1553
Eric Laurent81784c32012-11-19 14:55:58 -08001554 if (chain == 0) {
1555 // create a new chain for this session
1556 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1557 chain = new EffectChain(this, sessionId);
1558 addEffectChain_l(chain);
1559 chain->setStrategy(getStrategyForSession_l(sessionId));
1560 chainCreated = true;
1561 }
1562 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1563
1564 if (chain->getEffectFromId_l(effect->id()) != 0) {
1565 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1566 this, effect->desc().name, chain.get());
1567 return BAD_VALUE;
1568 }
1569
Eric Laurent5baf2af2013-09-12 17:37:00 -07001570 effect->setOffloaded(mType == OFFLOAD, mId);
1571
Eric Laurent81784c32012-11-19 14:55:58 -08001572 status_t status = chain->addEffect_l(effect);
1573 if (status != NO_ERROR) {
1574 if (chainCreated) {
1575 removeEffectChain_l(chain);
1576 }
1577 return status;
1578 }
1579
jiabinb8269fd2019-11-11 12:16:27 -08001580 effect->setDevices(outDeviceTypeAddrs());
1581 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001582 effect->setMode(mAudioFlinger->getMode());
1583 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001584
Eric Laurent81784c32012-11-19 14:55:58 -08001585 return NO_ERROR;
1586}
1587
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001588void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001589
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001590 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001591 effect_descriptor_t desc = effect->desc();
1592 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1593 detachAuxEffect_l(effect->id());
1594 }
1595
Eric Laurent5d885392019-12-13 10:56:31 -08001596 sp<EffectChain> chain = effect->callback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001597 if (chain != 0) {
1598 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001599 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001600 removeEffectChain_l(chain);
1601 }
1602 } else {
1603 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1604 }
1605}
1606
1607void AudioFlinger::ThreadBase::lockEffectChains_l(
1608 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1609{
1610 effectChains = mEffectChains;
1611 for (size_t i = 0; i < mEffectChains.size(); i++) {
1612 mEffectChains[i]->lock();
1613 }
1614}
1615
1616void AudioFlinger::ThreadBase::unlockEffectChains(
1617 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1618{
1619 for (size_t i = 0; i < effectChains.size(); i++) {
1620 effectChains[i]->unlock();
1621 }
1622}
1623
Glenn Kastend848eb42016-03-08 13:42:11 -08001624sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001625{
1626 Mutex::Autolock _l(mLock);
1627 return getEffectChain_l(sessionId);
1628}
1629
Glenn Kastend848eb42016-03-08 13:42:11 -08001630sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1631 const
Eric Laurent81784c32012-11-19 14:55:58 -08001632{
1633 size_t size = mEffectChains.size();
1634 for (size_t i = 0; i < size; i++) {
1635 if (mEffectChains[i]->sessionId() == sessionId) {
1636 return mEffectChains[i];
1637 }
1638 }
1639 return 0;
1640}
1641
1642void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1643{
1644 Mutex::Autolock _l(mLock);
1645 size_t size = mEffectChains.size();
1646 for (size_t i = 0; i < size; i++) {
1647 mEffectChains[i]->setMode_l(mode);
1648 }
1649}
1650
Mikhail Naganovdc769682018-05-04 15:34:08 -07001651void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001652{
1653 config->type = AUDIO_PORT_TYPE_MIX;
1654 config->ext.mix.handle = mId;
1655 config->sample_rate = mSampleRate;
1656 config->format = mFormat;
1657 config->channel_mask = mChannelMask;
1658 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1659 AUDIO_PORT_CONFIG_FORMAT;
1660}
1661
Eric Laurent72e3f392015-05-20 14:43:50 -07001662void AudioFlinger::ThreadBase::systemReady()
1663{
1664 Mutex::Autolock _l(mLock);
1665 if (mSystemReady) {
1666 return;
1667 }
1668 mSystemReady = true;
1669
1670 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1671 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1672 }
1673 mPendingConfigEvents.clear();
1674}
1675
Andy Hungdae27702016-10-31 14:01:16 -07001676template <typename T>
1677ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1678 ssize_t index = mActiveTracks.indexOf(track);
1679 if (index >= 0) {
1680 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1681 return index;
1682 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001683 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001684 mActiveTracksGeneration++;
1685 mLatestActiveTrack = track;
1686 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001687 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001688 return mActiveTracks.add(track);
1689}
1690
1691template <typename T>
1692ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1693 ssize_t index = mActiveTracks.remove(track);
1694 if (index < 0) {
1695 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1696 return index;
1697 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001698 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001699 mActiveTracksGeneration++;
1700 --mBatteryCounter[track->uid()].second;
1701 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001702 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001703#ifdef TEE_SINK
1704 track->dumpTee(-1 /* fd */, "_REMOVE");
1705#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001706 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001707 return index;
1708}
1709
1710template <typename T>
1711void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1712 for (const sp<T> &track : mActiveTracks) {
1713 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001714 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001715 }
1716 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001717 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001718 mActiveTracks.clear();
1719 mLatestActiveTrack.clear();
1720 mBatteryCounter.clear();
1721}
1722
1723template <typename T>
1724void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1725 sp<ThreadBase> thread, bool force) {
1726 // Updates ActiveTracks client uids to the thread wakelock.
1727 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1728 thread->updateWakeLockUids_l(getWakeLockUids());
1729 mLastActiveTracksGeneration = mActiveTracksGeneration;
1730 }
1731
1732 // Updates BatteryNotifier uids
1733 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1734 const uid_t uid = it->first;
1735 ssize_t &previous = it->second.first;
1736 ssize_t &current = it->second.second;
1737 if (current > 0) {
1738 if (previous == 0) {
1739 BatteryNotifier::getInstance().noteStartAudio(uid);
1740 }
1741 previous = current;
1742 ++it;
1743 } else if (current == 0) {
1744 if (previous > 0) {
1745 BatteryNotifier::getInstance().noteStopAudio(uid);
1746 }
1747 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1748 } else /* (current < 0) */ {
1749 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1750 }
1751 }
1752}
Eric Laurent83b88082014-06-20 18:31:16 -07001753
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001754template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001755bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1756 const bool hasChanged = mHasChanged;
1757 mHasChanged = false;
1758 return hasChanged;
1759}
1760
1761template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001762void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1763 const char *funcName, const sp<T> &track) const {
1764 if (mLocalLog != nullptr) {
1765 String8 result;
1766 track->appendDump(result, false /* active */);
1767 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1768 }
1769}
1770
Eric Laurent6acd1d42017-01-04 14:23:29 -08001771void AudioFlinger::ThreadBase::broadcast_l()
1772{
1773 // Thread could be blocked waiting for async
1774 // so signal it to handle state changes immediately
1775 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1776 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1777 mSignalPending = true;
1778 mWaitWorkCV.broadcast();
1779}
1780
Andy Hungd0979812019-02-21 15:51:44 -08001781// Call only from threadLoop() or when it is idle.
1782// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1783void AudioFlinger::ThreadBase::sendStatistics(bool force)
1784{
1785 // Do not log if we have no stats.
1786 // We choose the timestamp verifier because it is the most likely item to be present.
1787 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1788 if (nstats == 0) {
1789 return;
1790 }
1791
1792 // Don't log more frequently than once per 12 hours.
1793 // We use BOOTTIME to include suspend time.
1794 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1795 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1796 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1797 return;
1798 }
1799
1800 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1801 mLastRecordedTimeNs = timeNs;
1802
Ray Essickf27e9872019-12-07 06:28:46 -08001803 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001804
1805#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1806
1807 // thread configuration
1808 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1809 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1810 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1811 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1812 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1813 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1814 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabin10d86fd2019-10-31 17:20:42 -07001815 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1816 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001817
1818 // thread statistics
1819 if (mIoJitterMs.getN() > 0) {
1820 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1821 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1822 }
1823 if (mProcessTimeMs.getN() > 0) {
1824 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1825 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1826 }
1827 const auto tsjitter = mTimestampVerifier.getJitterMs();
1828 if (tsjitter.getN() > 0) {
1829 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1830 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1831 }
1832 if (mLatencyMs.getN() > 0) {
1833 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1834 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1835 }
1836
1837 item->selfrecord();
1838}
1839
Eric Laurent81784c32012-11-19 14:55:58 -08001840// ----------------------------------------------------------------------------
1841// Playback
1842// ----------------------------------------------------------------------------
1843
1844AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1845 AudioStreamOut* output,
1846 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001847 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001848 bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07001849 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001850 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001851 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001852 mMixerBuffer(NULL),
1853 mMixerBufferSize(0),
1854 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1855 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001856 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001857 mEffectBuffer(NULL),
1858 mEffectBufferSize(0),
1859 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1860 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001861 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001862 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001863 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001864 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001865 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001866 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001867 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001868 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001869 mMixerStatus(MIXER_IDLE),
1870 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001871 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001872 mBytesRemaining(0),
1873 mCurrentWriteLength(0),
1874 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001875 mWriteAckSequence(0),
1876 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001877 mScreenState(AudioFlinger::mScreenState),
1878 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001879 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001880 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent029e33e2020-12-23 18:19:44 +01001881 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1882 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001883{
Glenn Kastend7dca052015-03-05 16:05:54 -08001884 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1885 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001886
1887 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1888 // it would be safer to explicitly pass initial masterVolume/masterMute as
1889 // parameter.
1890 //
1891 // If the HAL we are using has support for master volume or master mute,
1892 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1893 // and the mute set to false).
1894 mMasterVolume = audioFlinger->masterVolume_l();
1895 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001896 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001897 if (mOutput->audioHwDev->canSetMasterVolume()) {
1898 mMasterVolume = 1.0;
1899 }
1900
1901 if (mOutput->audioHwDev->canSetMasterMute()) {
1902 mMasterMute = false;
1903 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001904 mIsMsdDevice = strcmp(
1905 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001906 }
1907
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001908 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001909
Andy Hungc8fddf32018-08-08 18:32:37 -07001910 // TODO: We may also match on address as well as device type for
1911 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001912 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabin10d86fd2019-10-31 17:20:42 -07001913 // TODO: This property should be ensure that only contains one single device type.
1914 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1915 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001916 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1917 : AUDIO_DEVICE_NONE));
1918 }
1919
Mikhail Naganovdc6be0d2020-09-25 23:03:05 +00001920 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1921 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08001922 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001923 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1924 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001925 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001926 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1927 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001928 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1929 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001930}
1931
1932AudioFlinger::PlaybackThread::~PlaybackThread()
1933{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001934 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001935 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001936 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001937 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001938}
1939
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001940// Thread virtuals
1941
1942void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001943{
jiabinf6eb4c32020-02-25 14:06:25 -08001944 if (mOutput == nullptr || mOutput->stream == nullptr) {
1945 ALOGE("The stream is not open yet"); // This should not happen.
1946 } else {
1947 // setEventCallback will need a strong pointer as a parameter. Calling it
1948 // here instead of constructor of PlaybackThread so that the onFirstRef
1949 // callback would not be made on an incompletely constructed object.
1950 if (mOutput->stream->setEventCallback(this) != OK) {
1951 ALOGE("Failed to add event callback");
1952 }
1953 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001954 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001955}
1956
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001957// ThreadBase virtuals
1958void AudioFlinger::PlaybackThread::preExit()
1959{
1960 ALOGV(" preExit()");
1961 // FIXME this is using hard-coded strings but in the future, this functionality will be
1962 // converted to use audio HAL extensions required to support tunneling
1963 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1964 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1965}
1966
1967void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001968{
Eric Laurent81784c32012-11-19 14:55:58 -08001969 String8 result;
1970
Marco Nelissenb2208842014-02-07 14:00:50 -08001971 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001972 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1973 const stream_type_t *st = &mStreamTypes[i];
1974 if (i > 0) {
1975 result.appendFormat(", ");
1976 }
1977 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1978 if (st->mute) {
1979 result.append("M");
1980 }
1981 }
1982 result.append("\n");
1983 write(fd, result.string(), result.length());
1984 result.clear();
1985
Eric Laurent81784c32012-11-19 14:55:58 -08001986 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1987 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001988 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001989 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001990
1991 size_t numtracks = mTracks.size();
1992 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001993 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001994 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001995 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001996 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001997 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001998 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001999 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002000 for (size_t i = 0; i < numtracks; ++i) {
2001 sp<Track> track = mTracks[i];
2002 if (track != 0) {
2003 bool active = mActiveTracks.indexOf(track) >= 0;
2004 if (active) {
2005 numactiveseen++;
2006 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002007 result.append(prefix);
2008 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002009 }
2010 }
2011 } else {
2012 result.append("\n");
2013 }
2014 if (numactiveseen != numactive) {
2015 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002016 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002017 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002018 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002019 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002020 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002021 sp<Track> track = mActiveTracks[i];
2022 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002023 result.append(prefix);
2024 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002025 }
2026 }
2027 }
2028
2029 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002030}
2031
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002032void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002033{
Andy Hung04cb8f72020-03-20 13:44:33 -07002034 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002035 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002036 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2037 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2038 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2039 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002040 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002041 dprintf(fd, " Total writes: %d\n", mNumWrites);
2042 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2043 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2044 dprintf(fd, " Suspend count: %d\n", mSuspended);
2045 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2046 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2047 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2048 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002049 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002050 AudioStreamOut *output = mOutput;
2051 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002052 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002053 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002054 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2055 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2056 if (mPipeSink.get() != nullptr) {
2057 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2058 }
2059 if (output != nullptr) {
2060 dprintf(fd, " Hal stream dump:\n");
2061 (void)output->stream->dump(fd);
2062 }
Eric Laurent81784c32012-11-19 14:55:58 -08002063}
2064
Eric Laurent81784c32012-11-19 14:55:58 -08002065// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2066sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2067 const sp<AudioFlinger::Client>& client,
2068 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002069 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002070 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002071 audio_format_t format,
2072 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002073 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002074 size_t *pNotificationFrameCount,
2075 uint32_t notificationsPerBuffer,
2076 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002077 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002078 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002079 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002080 pid_t creatorPid,
Eric Laurent81784c32012-11-19 14:55:58 -08002081 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08002082 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002083 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002084 audio_port_handle_t portId,
jiabin375283d2020-08-21 18:14:43 -07002085 const sp<media::IAudioTrackCallback>& callback,
2086 const std::string& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08002087{
Glenn Kasten74935e42013-12-19 08:56:45 -08002088 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002089 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002090 sp<Track> track;
2091 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002092 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002093 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002094 uint32_t sampleRate;
2095
2096 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2097 lStatus = BAD_VALUE;
2098 goto Exit;
2099 }
Eric Laurent21da6472017-11-09 16:29:26 -08002100
2101 if (*pSampleRate == 0) {
2102 *pSampleRate = mSampleRate;
2103 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002104 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002105
2106 // special case for FAST flag considered OK if fast mixer is present
2107 if (hasFastMixer()) {
2108 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2109 }
2110
2111 // Check if requested flags are compatible with output stream flags
2112 if ((*flags & outputFlags) != *flags) {
2113 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2114 *flags, outputFlags);
2115 *flags = (audio_output_flags_t)(*flags & outputFlags);
2116 }
Eric Laurent81784c32012-11-19 14:55:58 -08002117
Eric Laurent81784c32012-11-19 14:55:58 -08002118 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002119 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002120 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002121 // PCM data
2122 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002123 // TODO: extract as a data library function that checks that a computationally
2124 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002125 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002126 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2127 (channelMask == AUDIO_CHANNEL_OUT_MONO
2128 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002129 // hardware sample rate
2130 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002131 // normal mixer has an associated fast mixer
2132 hasFastMixer() &&
2133 // there are sufficient fast track slots available
2134 (mFastTrackAvailMask != 0)
2135 // FIXME test that MixerThread for this fast track has a capable output HAL
2136 // FIXME add a permission test also?
2137 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002138 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2139 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002140 // read the fast track multiplier property the first time it is needed
2141 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2142 if (ok != 0) {
2143 ALOGE("%s pthread_once failed: %d", __func__, ok);
2144 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002145 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002146 }
Eric Laurent4c415062016-06-17 16:14:16 -07002147
2148 // check compatibility with audio effects.
2149 { // scope for mLock
2150 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002151 for (audio_session_t session : {
Eric Laurenta20c4e92019-11-12 15:55:51 -08002152 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002153 AUDIO_SESSION_OUTPUT_STAGE,
2154 AUDIO_SESSION_OUTPUT_MIX,
2155 sessionId,
2156 }) {
2157 sp<EffectChain> chain = getEffectChain_l(session);
2158 if (chain.get() != nullptr) {
2159 audio_output_flags_t old = *flags;
2160 chain->checkOutputFlagCompatibility(flags);
2161 if (old != *flags) {
2162 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2163 (int)session, (int)old, (int)*flags);
2164 }
Eric Laurent4c415062016-06-17 16:14:16 -07002165 }
2166 }
2167 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002168 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002169 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2170 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002171 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002172 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2173 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002174 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002175 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002176 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002177 audio_is_linear_pcm(format),
2178 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002179 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002180 }
2181 }
Eric Laurent21da6472017-11-09 16:29:26 -08002182
2183 if (!audio_has_proportional_frames(format)) {
2184 if (sharedBuffer != 0) {
2185 // Same comment as below about ignoring frameCount parameter for set()
2186 frameCount = sharedBuffer->size();
2187 } else if (frameCount == 0) {
2188 frameCount = mNormalFrameCount;
2189 }
2190 if (notificationFrameCount != frameCount) {
2191 notificationFrameCount = frameCount;
2192 }
2193 } else if (sharedBuffer != 0) {
2194 // FIXME: Ensure client side memory buffers need
2195 // not have additional alignment beyond sample
2196 // (e.g. 16 bit stereo accessed as 32 bit frame).
2197 size_t alignment = audio_bytes_per_sample(format);
2198 if (alignment & 1) {
2199 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2200 alignment = 1;
2201 }
2202 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2203 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2204 if (channelCount > 1) {
2205 // More than 2 channels does not require stronger alignment than stereo
2206 alignment <<= 1;
2207 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002208 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002209 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002210 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002211 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002212 goto Exit;
2213 }
Eric Laurent21da6472017-11-09 16:29:26 -08002214
2215 // When initializing a shared buffer AudioTrack via constructors,
2216 // there's no frameCount parameter.
2217 // But when initializing a shared buffer AudioTrack via set(),
2218 // there _is_ a frameCount parameter. We silently ignore it.
2219 frameCount = sharedBuffer->size() / frameSize;
2220 } else {
2221 size_t minFrameCount = 0;
2222 // For fast tracks we try to respect the application's request for notifications per buffer.
2223 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2224 if (notificationsPerBuffer > 0) {
2225 // Avoid possible arithmetic overflow during multiplication.
2226 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2227 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2228 notificationsPerBuffer, mFrameCount);
2229 } else {
2230 minFrameCount = mFrameCount * notificationsPerBuffer;
2231 }
2232 }
2233 } else {
2234 // For normal PCM streaming tracks, update minimum frame count.
2235 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2236 // cover audio hardware latency.
2237 // This is probably too conservative, but legacy application code may depend on it.
2238 // If you change this calculation, also review the start threshold which is related.
2239 uint32_t latencyMs = latency_l();
2240 if (latencyMs == 0) {
2241 ALOGE("Error when retrieving output stream latency");
2242 lStatus = UNKNOWN_ERROR;
2243 goto Exit;
2244 }
2245
2246 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2247 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2248
Eric Laurent81784c32012-11-19 14:55:58 -08002249 }
Eric Laurent21da6472017-11-09 16:29:26 -08002250 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002251 frameCount = minFrameCount;
2252 }
Eric Laurent81784c32012-11-19 14:55:58 -08002253 }
Eric Laurent21da6472017-11-09 16:29:26 -08002254
2255 // Make sure that application is notified with sufficient margin before underrun.
2256 // The client can divide the AudioTrack buffer into sub-buffers,
2257 // and expresses its desire to server as the notification frame count.
2258 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2259 size_t maxNotificationFrames;
2260 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2261 // notify every HAL buffer, regardless of the size of the track buffer
2262 maxNotificationFrames = mFrameCount;
2263 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002264 // Triple buffer the notification period for a triple buffered mixer period;
2265 // otherwise, double buffering for the notification period is fine.
2266 //
2267 // TODO: This should be moved to AudioTrack to modify the notification period
2268 // on AudioTrack::setBufferSizeInFrames() changes.
2269 const int nBuffering =
2270 (uint64_t{frameCount} * mSampleRate)
2271 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2272
Eric Laurent21da6472017-11-09 16:29:26 -08002273 maxNotificationFrames = frameCount / nBuffering;
2274 // If client requested a fast track but this was denied, then use the smaller maximum.
2275 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2276 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2277 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2278 maxNotificationFrames = maxNotificationFramesFastDenied;
2279 }
2280 }
2281 }
2282 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2283 if (notificationFrameCount == 0) {
2284 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2285 maxNotificationFrames, frameCount);
2286 } else {
2287 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2288 notificationFrameCount, maxNotificationFrames, frameCount);
2289 }
2290 notificationFrameCount = maxNotificationFrames;
2291 }
2292 }
2293
Glenn Kasten74935e42013-12-19 08:56:45 -08002294 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002295 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002296
Glenn Kastenc3df8382014-03-13 15:05:25 -07002297 switch (mType) {
2298
2299 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002300 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002301 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002302 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2303 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002304 sampleRate, format, channelMask, mOutput, mFormat);
2305 lStatus = BAD_VALUE;
2306 goto Exit;
2307 }
2308 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002309 break;
2310
2311 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002312 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002313 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2314 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002315 sampleRate, format, channelMask, mOutput, mFormat);
2316 lStatus = BAD_VALUE;
2317 goto Exit;
2318 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002319 break;
2320
2321 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002322 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002323 ALOGE("createTrack_l() Bad parameter: format %#x \""
2324 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002325 format, mOutput, mFormat);
2326 lStatus = BAD_VALUE;
2327 goto Exit;
2328 }
Andy Hungcd044842014-08-07 11:04:34 -07002329 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002330 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2331 lStatus = BAD_VALUE;
2332 goto Exit;
2333 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002334 break;
2335
Eric Laurent81784c32012-11-19 14:55:58 -08002336 }
2337
2338 lStatus = initCheck();
2339 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002340 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002341 goto Exit;
2342 }
2343
2344 { // scope for mLock
2345 Mutex::Autolock _l(mLock);
2346
2347 // all tracks in same audio session must share the same routing strategy otherwise
2348 // conflicts will happen when tracks are moved from one output to another by audio policy
2349 // manager
2350 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2351 for (size_t i = 0; i < mTracks.size(); ++i) {
2352 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002353 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002354 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2355 if (sessionId == t->sessionId() && strategy != actual) {
2356 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2357 strategy, actual);
2358 lStatus = BAD_VALUE;
2359 goto Exit;
2360 }
2361 }
2362 }
2363
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002364 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002365 channelMask, frameCount,
2366 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
jiabin375283d2020-08-21 18:14:43 -07002367 sessionId, creatorPid, uid, *flags, TrackBase::TYPE_DEFAULT, portId,
2368 SIZE_MAX /*frameCountToBeReady*/, opPackageName);
Glenn Kasten03003332013-08-06 15:40:54 -07002369
Glenn Kasten03003332013-08-06 15:40:54 -07002370 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2371 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002372 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002373 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002374 goto Exit;
2375 }
2376 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002377 {
2378 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2379 if (callback.get() != nullptr) {
jiabinb56e7432020-09-17 11:40:42 -07002380 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002381 }
2382 }
Eric Laurent81784c32012-11-19 14:55:58 -08002383
2384 sp<EffectChain> chain = getEffectChain_l(sessionId);
2385 if (chain != 0) {
2386 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2387 track->setMainBuffer(chain->inBuffer());
2388 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2389 chain->incTrackCnt();
2390 }
2391
Eric Laurent05067782016-06-01 18:27:28 -07002392 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002393 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2394 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2395 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002396 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002397 }
2398 }
2399
2400 lStatus = NO_ERROR;
2401
2402Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002403 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002404 return track;
2405}
2406
Andy Hung1bc088a2018-02-09 15:57:31 -08002407template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002408ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2409{
Andy Hungc0691382018-09-12 18:01:57 -07002410 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002411 const ssize_t index = mTracks.remove(track);
2412 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002413 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002414 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002415 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002416 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002417 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002418 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002419 }
2420 return index;
2421}
2422
Eric Laurent81784c32012-11-19 14:55:58 -08002423uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2424{
2425 return latency;
2426}
2427
2428uint32_t AudioFlinger::PlaybackThread::latency() const
2429{
2430 Mutex::Autolock _l(mLock);
2431 return latency_l();
2432}
2433uint32_t AudioFlinger::PlaybackThread::latency_l() const
2434{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002435 uint32_t latency;
2436 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2437 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002438 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002439 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002440}
2441
2442void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2443{
2444 Mutex::Autolock _l(mLock);
2445 // Don't apply master volume in SW if our HAL can do it for us.
2446 if (mOutput && mOutput->audioHwDev &&
2447 mOutput->audioHwDev->canSetMasterVolume()) {
2448 mMasterVolume = 1.0;
2449 } else {
2450 mMasterVolume = value;
2451 }
2452}
2453
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002454void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2455{
2456 mMasterBalance.store(balance);
2457}
2458
Eric Laurent81784c32012-11-19 14:55:58 -08002459void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2460{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002461 if (isDuplicating()) {
2462 return;
2463 }
Eric Laurent81784c32012-11-19 14:55:58 -08002464 Mutex::Autolock _l(mLock);
2465 // Don't apply master mute in SW if our HAL can do it for us.
2466 if (mOutput && mOutput->audioHwDev &&
2467 mOutput->audioHwDev->canSetMasterMute()) {
2468 mMasterMute = false;
2469 } else {
2470 mMasterMute = muted;
2471 }
2472}
2473
2474void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2475{
2476 Mutex::Autolock _l(mLock);
2477 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002478 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002479}
2480
2481void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2482{
2483 Mutex::Autolock _l(mLock);
2484 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002485 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002486}
2487
2488float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2489{
2490 Mutex::Autolock _l(mLock);
2491 return mStreamTypes[stream].volume;
2492}
2493
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002494void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2495{
2496 mOutput->stream->setVolume(left, right);
2497}
2498
Eric Laurent81784c32012-11-19 14:55:58 -08002499// addTrack_l() must be called with ThreadBase::mLock held
2500status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2501{
2502 status_t status = ALREADY_EXISTS;
2503
Eric Laurent81784c32012-11-19 14:55:58 -08002504 if (mActiveTracks.indexOf(track) < 0) {
2505 // the track is newly added, make sure it fills up all its
2506 // buffers before playing. This is to ensure the client will
2507 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002508 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002509 TrackBase::track_state state = track->mState;
2510 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002511 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002512 mLock.lock();
2513 // abort track was stopped/paused while we released the lock
2514 if (state != track->mState) {
2515 if (status == NO_ERROR) {
2516 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002517 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002518 mLock.lock();
2519 }
2520 return INVALID_OPERATION;
2521 }
2522 // abort if start is rejected by audio policy manager
2523 if (status != NO_ERROR) {
2524 return PERMISSION_DENIED;
2525 }
2526#ifdef ADD_BATTERY_DATA
2527 // to track the speaker usage
2528 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2529#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002530 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002531 }
2532
Eric Laurent51716182016-02-29 18:00:56 -08002533 // set retry count for buffer fill
2534 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002535 if (track->isStopping_1()) {
2536 track->mRetryCount = kMaxTrackStopRetriesOffload;
2537 } else {
2538 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2539 }
2540 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002541 } else {
2542 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002543 track->mFillingUpStatus =
2544 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002545 }
2546
jiabin245cdd92018-12-07 17:55:15 -08002547 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2548 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002549 // Unlock due to VibratorService will lock for this call and will
2550 // call Tracks.mute/unmute which also require thread's lock.
2551 mLock.unlock();
2552 const int intensity = AudioFlinger::onExternalVibrationStart(
2553 track->getExternalVibration());
2554 mLock.lock();
jiabinbf6b0ec2019-02-12 12:30:12 -08002555 track->setHapticIntensity(static_cast<AudioMixer::haptic_intensity_t>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002556 // Haptic playback should be enabled by vibrator service.
2557 if (track->getHapticPlaybackEnabled()) {
2558 // Disable haptic playback of all active track to ensure only
2559 // one track playing haptic if current track should play haptic.
2560 for (const auto &t : mActiveTracks) {
2561 t->setHapticPlaybackEnabled(false);
2562 }
jiabin245cdd92018-12-07 17:55:15 -08002563 }
jiabin245cdd92018-12-07 17:55:15 -08002564 }
2565
Eric Laurent81784c32012-11-19 14:55:58 -08002566 track->mResetDone = false;
2567 track->mPresentationCompleteFrames = 0;
2568 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002569 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2570 if (chain != 0) {
2571 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2572 track->sessionId());
2573 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002574 }
2575
Andy Hungc2b11cb2020-04-22 09:04:01 -07002576 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002577 status = NO_ERROR;
2578 }
2579
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002580 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002581 return status;
2582}
2583
Eric Laurentbfb1b832013-01-07 09:53:42 -08002584bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002585{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002586 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002587 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002588 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2589 track->mState = TrackBase::STOPPED;
2590 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002591 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002592 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002593 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002594 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595
2596 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002597}
2598
2599void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2600{
2601 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002602
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002603 String8 result;
2604 track->appendDump(result, false /* active */);
2605 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002606
Eric Laurent81784c32012-11-19 14:55:58 -08002607 mTracks.remove(track);
jiabinb56e7432020-09-17 11:40:42 -07002608 {
2609 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2610 mAudioTrackCallbacks.erase(track);
2611 }
Eric Laurent81784c32012-11-19 14:55:58 -08002612 if (track->isFastTrack()) {
2613 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002614 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002615 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2616 mFastTrackAvailMask |= 1 << index;
2617 // redundant as track is about to be destroyed, for dumpsys only
2618 track->mFastIndex = -1;
2619 }
2620 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2621 if (chain != 0) {
2622 chain->decTrackCnt();
2623 }
2624}
2625
2626String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2627{
Eric Laurent81784c32012-11-19 14:55:58 -08002628 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002629 String8 out_s8;
2630 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2631 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002632 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002633 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002634}
2635
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002636status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2637 Mutex::Autolock _l(mLock);
2638 if (mOutput == nullptr || mOutput->stream == nullptr) {
2639 return NO_INIT;
2640 }
2641 return mOutput->stream->selectPresentation(presentationId, programId);
2642}
2643
Eric Laurent09f1ed22019-04-24 17:45:17 -07002644void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2645 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002646 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2647 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002648
Eric Laurent73e26b62015-04-27 16:55:58 -07002649 desc->mIoHandle = mId;
Eric Laurent029e33e2020-12-23 18:19:44 +01002650 struct audio_patch patch = mPatch;
2651 if (isMsdDevice()) {
2652 patch = mDownStreamPatch;
2653 }
Eric Laurent81784c32012-11-19 14:55:58 -08002654
2655 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002656 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002657 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002658 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent029e33e2020-12-23 18:19:44 +01002659 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002660 desc->mChannelMask = mChannelMask;
2661 desc->mSamplingRate = mSampleRate;
2662 desc->mFormat = mFormat;
2663 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002664 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002665 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002666 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002667 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002668 case AUDIO_CLIENT_STARTED:
Eric Laurent029e33e2020-12-23 18:19:44 +01002669 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002670 desc->mPortId = portId;
2671 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002672 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002673 default:
2674 break;
2675 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002676 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002677}
2678
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002679void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002680{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002681 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682}
2683
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002684void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002685{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002686 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687}
2688
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002689void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002690{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002691 mCallbackThread->setAsyncError();
2692}
2693
jiabinf6eb4c32020-02-25 14:06:25 -08002694void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2695 const std::basic_string<uint8_t>& metadataBs)
2696{
2697 std::thread([this, metadataBs]() {
2698 audio_utils::metadata::Data metadata =
2699 audio_utils::metadata::dataFromByteString(metadataBs);
2700 if (metadata.empty()) {
2701 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2702 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2703 (int)metadataBs.size());
2704 return;
2705 }
2706
2707 audio_utils::metadata::ByteString metaDataStr =
2708 audio_utils::metadata::byteStringFromData(metadata);
2709 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2710 Mutex::Autolock _l(mAudioTrackCbLock);
jiabinb56e7432020-09-17 11:40:42 -07002711 for (const auto& callbackPair : mAudioTrackCallbacks) {
2712 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002713 }
2714 }).detach();
2715}
2716
Eric Laurent3b4529e2013-09-05 18:09:19 -07002717void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002718{
2719 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002720 // reject out of sequence requests
2721 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2722 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002723 mWaitWorkCV.signal();
2724 }
2725}
2726
Eric Laurent3b4529e2013-09-05 18:09:19 -07002727void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002728{
2729 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002730 // reject out of sequence requests
2731 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002732 // Register discontinuity when HW drain is completed because that can cause
2733 // the timestamp frame position to reset to 0 for direct and offload threads.
2734 // (Out of sequence requests are ignored, since the discontinuity would be handled
2735 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002736 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002737 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002738 mWaitWorkCV.signal();
2739 }
2740}
2741
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002742void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002743{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002744 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002745 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2746 mSampleRate = audioConfig.sample_rate;
2747 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002748 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002749 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002750 }
Andy Hung9a592762014-07-21 21:56:01 -07002751 if ((mType == MIXER || mType == DUPLICATING)
2752 && !isValidPcmSinkChannelMask(mChannelMask)) {
2753 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2754 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002755 }
Andy Hunge5412692014-05-16 11:25:07 -07002756 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002757 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002758
2759 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002760 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002761 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002762 // Get format from the shim, which will be different than the HAL format
2763 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002764 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002765 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002766 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002767 }
Andy Hung6146c082014-03-18 11:56:15 -07002768 if ((mType == MIXER || mType == DUPLICATING)
2769 && !isValidPcmSinkFormat(mFormat)) {
2770 LOG_FATAL("HAL format %#x not supported for mixed output",
2771 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002772 }
Phil Burk062e67a2015-02-11 13:40:50 -08002773 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002774 result = mOutput->stream->getBufferSize(&mBufferSize);
2775 LOG_ALWAYS_FATAL_IF(result != OK,
2776 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002777 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002778 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002779 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002780 mFrameCount);
2781 }
2782
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002783 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2784 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002785 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002786 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002787 }
2788 }
2789
Eric Laurentd1f69b02014-12-15 14:33:13 -08002790 mHwSupportsPause = false;
2791 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002792 bool supportsPause = false, supportsResume = false;
2793 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2794 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002795 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002796 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002797 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002798 } else if (supportsResume) {
2799 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002800 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002801 }
2802 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002803 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2804 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2805 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002806
Andy Hungfbfc3952015-01-15 13:33:51 -08002807 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2808 // For best precision, we use float instead of the associated output
2809 // device format (typically PCM 16 bit).
2810
2811 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2812 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2813 mBufferSize = mFrameSize * mFrameCount;
2814
2815 // TODO: We currently use the associated output device channel mask and sample rate.
2816 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2817 // (if a valid mask) to avoid premature downmix.
2818 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2819 // instead of the output device sample rate to avoid loss of high frequency information.
2820 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2821 }
2822
Andy Hung09a50072014-02-27 14:30:47 -08002823 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002824 double multiplier = 1.0;
2825 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2826 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002827 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2828 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002829
Eric Laurent81784c32012-11-19 14:55:58 -08002830 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2831 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2832 maxNormalFrameCount = maxNormalFrameCount & ~15;
2833 if (maxNormalFrameCount < minNormalFrameCount) {
2834 maxNormalFrameCount = minNormalFrameCount;
2835 }
2836 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2837 if (multiplier <= 1.0) {
2838 multiplier = 1.0;
2839 } else if (multiplier <= 2.0) {
2840 if (2 * mFrameCount <= maxNormalFrameCount) {
2841 multiplier = 2.0;
2842 } else {
2843 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2844 }
2845 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002846 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002847 }
2848 }
2849 mNormalFrameCount = multiplier * mFrameCount;
2850 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002851 if (mType == MIXER || mType == DUPLICATING) {
2852 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2853 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002854 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002855 mNormalFrameCount);
2856
Andy Hung08fb1742015-05-31 23:22:10 -07002857 // Check if we want to throttle the processing to no more than 2x normal rate
2858 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002859 mThreadThrottleTimeMs = 0;
2860 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002861 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2862
Andy Hung010a1a12014-03-13 13:57:33 -07002863 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2864 // Originally this was int16_t[] array, need to remove legacy implications.
2865 free(mSinkBuffer);
2866 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002867 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2868 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2869 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002870 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002871
Andy Hung69aed5f2014-02-25 17:24:40 -08002872 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2873 // drives the output.
2874 free(mMixerBuffer);
2875 mMixerBuffer = NULL;
2876 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002877 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002878 mMixerBufferSize = mNormalFrameCount * mChannelCount
2879 * audio_bytes_per_sample(mMixerBufferFormat);
2880 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2881 }
Andy Hung98ef9782014-03-04 14:46:50 -08002882 free(mEffectBuffer);
2883 mEffectBuffer = NULL;
2884 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002885 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002886 mEffectBufferSize = mNormalFrameCount * mChannelCount
2887 * audio_bytes_per_sample(mEffectBufferFormat);
2888 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2889 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002890
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07002891 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2892 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08002893 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2894 mChannelCount -= mHapticChannelCount;
2895
Eric Laurent81784c32012-11-19 14:55:58 -08002896 // force reconfiguration of effect chains and engines to take new buffer size and audio
2897 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002898 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002899 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2900 // matter.
2901 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2902 Vector< sp<EffectChain> > effectChains = mEffectChains;
2903 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002904 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2905 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002906 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002907
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002908 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002909 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002910 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2911 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2912 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2913 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2914 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2915 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2916 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2917 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2918 (int32_t)mHapticChannelMask)
2919 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2920 (int32_t)mHapticChannelCount)
2921 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2922 formatToString(mHALFormat).c_str())
2923 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2924 (int32_t)mFrameCount) // sic - added HAL
2925 ;
2926 uint32_t latencyMs;
2927 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2928 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2929 }
2930 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08002931}
2932
Kevin Rocard069c2712018-03-29 19:09:14 -07002933void AudioFlinger::PlaybackThread::updateMetadata_l()
2934{
Kevin Rocard12381092018-04-11 09:19:59 -07002935 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2936 return; // That should not happen
2937 }
2938 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2939 for (const sp<Track> &track : mActiveTracks) {
2940 // Do not short-circuit as all hasChanged states must be reset
2941 // as all the metadata are going to be sent
2942 hasChanged |= track->readAndClearHasChanged();
2943 }
2944 if (!hasChanged) {
2945 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002946 }
2947 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002948 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002949 for (const sp<Track> &track : mActiveTracks) {
2950 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002951 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002952 }
Kevin Rocard12381092018-04-11 09:19:59 -07002953 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002954}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002955
Kevin Rocard12381092018-04-11 09:19:59 -07002956void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2957 const StreamOutHalInterface::SourceMetadata& metadata)
2958{
2959 mOutput->stream->updateSourceMetadata(metadata);
2960};
2961
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002962status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002963{
2964 if (halFrames == NULL || dspFrames == NULL) {
2965 return BAD_VALUE;
2966 }
2967 Mutex::Autolock _l(mLock);
2968 if (initCheck() != NO_ERROR) {
2969 return INVALID_OPERATION;
2970 }
Andy Hung818e7a32016-02-16 18:08:07 -08002971 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002972 *halFrames = framesWritten;
2973
2974 if (isSuspended()) {
2975 // return an estimation of rendered frames when the output is suspended
2976 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002977 *dspFrames = (uint32_t)
2978 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002979 return NO_ERROR;
2980 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002981 status_t status;
2982 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002983 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002984 *dspFrames = (size_t)frames;
2985 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002986 }
2987}
2988
Glenn Kastend848eb42016-03-08 13:42:11 -08002989uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002990{
2991 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2992 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2993 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2994 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2995 }
2996 for (size_t i = 0; i < mTracks.size(); i++) {
2997 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002998 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002999 return AudioSystem::getStrategyForStream(track->streamType());
3000 }
3001 }
3002 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3003}
3004
3005
Phil Burk062e67a2015-02-11 13:40:50 -08003006AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003007{
3008 Mutex::Autolock _l(mLock);
3009 return mOutput;
3010}
3011
Phil Burk062e67a2015-02-11 13:40:50 -08003012AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003013{
3014 Mutex::Autolock _l(mLock);
3015 AudioStreamOut *output = mOutput;
3016 mOutput = NULL;
3017 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3018 // must push a NULL and wait for ack
3019 mOutputSink.clear();
3020 mPipeSink.clear();
3021 mNormalSink.clear();
3022 return output;
3023}
3024
3025// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003026sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003027{
3028 if (mOutput == NULL) {
3029 return NULL;
3030 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003031 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003032}
3033
3034uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3035{
3036 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3037}
3038
3039status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3040{
3041 if (!isValidSyncEvent(event)) {
3042 return BAD_VALUE;
3043 }
3044
3045 Mutex::Autolock _l(mLock);
3046
3047 for (size_t i = 0; i < mTracks.size(); ++i) {
3048 sp<Track> track = mTracks[i];
3049 if (event->triggerSession() == track->sessionId()) {
3050 (void) track->setSyncEvent(event);
3051 return NO_ERROR;
3052 }
3053 }
3054
3055 return NAME_NOT_FOUND;
3056}
3057
3058bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3059{
3060 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3061}
3062
3063void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3064 const Vector< sp<Track> >& tracksToRemove)
3065{
Andy Hungfe726a62018-09-27 15:17:25 -07003066 // Miscellaneous track cleanup when removed from the active list,
3067 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003068#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003069 for (const auto& track : tracksToRemove) {
3070 if (track->isExternalTrack()) {
3071 // to track the speaker usage
3072 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003073 }
3074 }
Andy Hungfe726a62018-09-27 15:17:25 -07003075#else
3076 (void)tracksToRemove; // suppress unused warning
3077#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003078}
3079
3080void AudioFlinger::PlaybackThread::checkSilentMode_l()
3081{
3082 if (!mMasterMute) {
3083 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003084 if (mOutDeviceTypeAddrs.empty()) {
3085 ALOGD("ro.audio.silent is ignored since no output device is set");
3086 return;
3087 }
jiabin10d86fd2019-10-31 17:20:42 -07003088 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003089 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3090 return;
3091 }
Eric Laurent81784c32012-11-19 14:55:58 -08003092 if (property_get("ro.audio.silent", value, "0") > 0) {
3093 char *endptr;
3094 unsigned long ul = strtoul(value, &endptr, 0);
3095 if (*endptr == '\0' && ul != 0) {
3096 ALOGD("Silence is golden");
3097 // The setprop command will not allow a property to be changed after
3098 // the first time it is set, so we don't have to worry about un-muting.
3099 setMasterMute_l(true);
3100 }
3101 }
3102 }
3103}
3104
3105// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003106ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003107{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003108 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003109 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003110 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003111 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003112
3113 // If an NBAIO sink is present, use it to write the normal mixer's submix
3114 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003115
Andy Hung010a1a12014-03-13 13:57:33 -07003116 const size_t count = mBytesRemaining / mFrameSize;
3117
Simon Wilson2d590962012-11-29 15:18:50 -08003118 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003119 // update the setpoint when AudioFlinger::mScreenState changes
3120 uint32_t screenState = AudioFlinger::mScreenState;
3121 if (screenState != mScreenState) {
3122 mScreenState = screenState;
3123 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3124 if (pipe != NULL) {
3125 pipe->setAvgFrames((mScreenState & 1) ?
3126 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3127 }
3128 }
Andy Hung010a1a12014-03-13 13:57:33 -07003129 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003130 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003131 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003132 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003133#ifdef TEE_SINK
3134 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3135#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003136 } else {
3137 bytesWritten = framesWritten;
3138 }
3139 // otherwise use the HAL / AudioStreamOut directly
3140 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003141 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003142
Eric Laurentbfb1b832013-01-07 09:53:42 -08003143 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003144 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3145 mWriteAckSequence += 2;
3146 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003147 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003148 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003149 }
Mikhail Naganov76e89c32019-08-15 20:18:47 -07003150 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003151 // FIXME We should have an implementation of timestamps for direct output threads.
3152 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003153 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganov76e89c32019-08-15 20:18:47 -07003154 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003155
Eric Laurentbfb1b832013-01-07 09:53:42 -08003156 if (mUseAsyncWrite &&
3157 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3158 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003159 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003160 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003161 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162 }
Eric Laurent81784c32012-11-19 14:55:58 -08003163 }
3164
Eric Laurent81784c32012-11-19 14:55:58 -08003165 mNumWrites++;
3166 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003167 if (mStandby) {
3168 mThreadMetrics.logBeginInterval();
3169 mStandby = false;
3170 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003171 return bytesWritten;
3172}
3173
3174void AudioFlinger::PlaybackThread::threadLoop_drain()
3175{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003176 bool supportsDrain = false;
3177 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003178 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3179 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003180 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3181 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003182 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003183 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003184 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003185 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003186 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003187 }
3188}
3189
3190void AudioFlinger::PlaybackThread::threadLoop_exit()
3191{
Eric Laurent275e8e92014-11-30 15:14:47 -08003192 {
3193 Mutex::Autolock _l(mLock);
3194 for (size_t i = 0; i < mTracks.size(); i++) {
3195 sp<Track> track = mTracks[i];
3196 track->invalidate();
3197 }
Andy Hungdae27702016-10-31 14:01:16 -07003198 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3199 // After we exit there are no more track changes sent to BatteryNotifier
3200 // because that requires an active threadLoop.
3201 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3202 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003203 }
Eric Laurent81784c32012-11-19 14:55:58 -08003204}
3205
3206/*
3207The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003208 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003209 - mActiveSleepTimeUs from activeSleepTimeUs()
3210 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003211 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3212 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003213 - maxPeriod from frame count and sample rate (MIXER only)
3214
3215The parameters that affect these derived values are:
3216 - frame count
3217 - frame size
3218 - sample rate
3219 - device type: A2DP or not
3220 - device latency
3221 - format: PCM or not
3222 - active sleep time
3223 - idle sleep time
3224*/
3225
3226void AudioFlinger::PlaybackThread::cacheParameters_l()
3227{
Andy Hung25c2dac2014-02-27 14:56:00 -08003228 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003229 mActiveSleepTimeUs = activeSleepTimeUs();
3230 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003231
3232 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3233 // truncating audio when going to standby.
3234 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabin10d86fd2019-10-31 17:20:42 -07003235 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003236 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3237 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3238 }
3239 }
Eric Laurent81784c32012-11-19 14:55:58 -08003240}
3241
Eric Laurent13084622016-05-17 10:51:49 -07003242bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003243{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003244 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003245 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003246 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003247 size_t size = mTracks.size();
3248 for (size_t i = 0; i < size; i++) {
3249 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003250 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003251 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003252 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003253 }
3254 }
Eric Laurent13084622016-05-17 10:51:49 -07003255 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003256}
3257
Haynes Mathew George05317d22016-05-03 16:34:26 -07003258void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3259{
3260 Mutex::Autolock _l(mLock);
3261 invalidateTracks_l(streamType);
3262}
3263
Eric Laurent81784c32012-11-19 14:55:58 -08003264status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3265{
Glenn Kastend848eb42016-03-08 13:42:11 -08003266 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003267 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003268 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003269 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3270 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3271 &halInBuffer);
3272 if (result != OK) return result;
3273 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003274 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003275 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurenta20c4e92019-11-12 15:55:51 -08003276 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003277 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003278 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003279 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003280 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003281 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003282 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003283 &halInBuffer);
3284 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003285#ifdef FLOAT_EFFECT_CHAIN
3286 buffer = halInBuffer->audioBuffer()->f32;
3287#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003288 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003289#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003290 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3291 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003292 }
3293
3294 // Attach all tracks with same session ID to this chain.
3295 for (size_t i = 0; i < mTracks.size(); ++i) {
3296 sp<Track> track = mTracks[i];
3297 if (session == track->sessionId()) {
3298 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3299 buffer);
3300 track->setMainBuffer(buffer);
3301 chain->incTrackCnt();
3302 }
3303 }
3304
3305 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003306 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003307 if (session == track->sessionId()) {
3308 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3309 chain->incActiveTrackCnt();
3310 }
3311 }
3312 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003313 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003314 chain->setInBuffer(halInBuffer);
3315 chain->setOutBuffer(halOutBuffer);
Eric Laurenta20c4e92019-11-12 15:55:51 -08003316 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3317 // chains list in order to be processed last as it contains output device effects.
3318 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3319 // processing effects specific to an output stream before effects applied to all streams
3320 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003321 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3322 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003323 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003324 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003325 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003326 // Effect chain for other sessions are inserted at beginning of effect
3327 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003328 // sessions is not important.
3329 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurenta20c4e92019-11-12 15:55:51 -08003330 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3331 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003332 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003333 size_t size = mEffectChains.size();
3334 size_t i = 0;
3335 for (i = 0; i < size; i++) {
3336 if (mEffectChains[i]->sessionId() < session) {
3337 break;
3338 }
3339 }
3340 mEffectChains.insertAt(chain, i);
3341 checkSuspendOnAddEffectChain_l(chain);
3342
3343 return NO_ERROR;
3344}
3345
3346size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3347{
Glenn Kastend848eb42016-03-08 13:42:11 -08003348 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003349
3350 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3351
3352 for (size_t i = 0; i < mEffectChains.size(); i++) {
3353 if (chain == mEffectChains[i]) {
3354 mEffectChains.removeAt(i);
3355 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003356 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003357 if (session == track->sessionId()) {
3358 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3359 chain.get(), session);
3360 chain->decActiveTrackCnt();
3361 }
3362 }
3363
3364 // detach all tracks with same session ID from this chain
3365 for (size_t i = 0; i < mTracks.size(); ++i) {
3366 sp<Track> track = mTracks[i];
3367 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003368 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003369 chain->decTrackCnt();
3370 }
3371 }
3372 break;
3373 }
3374 }
3375 return mEffectChains.size();
3376}
3377
3378status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003379 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003380{
3381 Mutex::Autolock _l(mLock);
3382 return attachAuxEffect_l(track, EffectId);
3383}
3384
3385status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003386 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003387{
3388 status_t status = NO_ERROR;
3389
3390 if (EffectId == 0) {
3391 track->setAuxBuffer(0, NULL);
3392 } else {
3393 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3394 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3395 if (effect != 0) {
3396 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3397 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3398 } else {
3399 status = INVALID_OPERATION;
3400 }
3401 } else {
3402 status = BAD_VALUE;
3403 }
3404 }
3405 return status;
3406}
3407
3408void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3409{
3410 for (size_t i = 0; i < mTracks.size(); ++i) {
3411 sp<Track> track = mTracks[i];
3412 if (track->auxEffectId() == effectId) {
3413 attachAuxEffect_l(track, 0);
3414 }
3415 }
3416}
3417
3418bool AudioFlinger::PlaybackThread::threadLoop()
3419{
Glenn Kasten388d5712017-04-07 14:38:41 -07003420 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003421
Eric Laurent81784c32012-11-19 14:55:58 -08003422 Vector< sp<Track> > tracksToRemove;
3423
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003424 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003425 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003426
3427 // MIXER
3428 nsecs_t lastWarning = 0;
3429
3430 // DUPLICATING
3431 // FIXME could this be made local to while loop?
3432 writeFrames = 0;
3433
3434 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003435 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003436
3437 if (mType == MIXER) {
3438 sleepTimeShift = 0;
3439 }
3440
3441 CpuStats cpuStats;
3442 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3443
3444 acquireWakeLock();
3445
Glenn Kasteneef598c2017-04-03 14:41:13 -07003446 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3447 // thread associated with this PlaybackThread.
3448 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3449 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003450 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3451 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003452 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003453 const char *logString = NULL;
3454
rago1bb90822017-05-02 18:31:48 -07003455 // Estimated time for next buffer to be written to hal. This is used only on
3456 // suspended mode (for now) to help schedule the wait time until next iteration.
3457 nsecs_t timeLoopNextNs = 0;
3458
Eric Laurent664539d2013-09-23 18:24:31 -07003459 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003460
Andy Hung2dbffc22018-08-08 18:50:41 -07003461 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003462
Andy Hung446f4df2019-02-21 12:26:41 -08003463 // loopCount is used for statistics and diagnostics.
3464 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003465 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003466 // Log merge requests are performed during AudioFlinger binder transactions, but
3467 // that does not cover audio playback. It's requested here for that reason.
3468 mAudioFlinger->requestLogMerge();
3469
Eric Laurent81784c32012-11-19 14:55:58 -08003470 cpuStats.sample(myName);
3471
3472 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003473 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003474 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003475
Andy Hung2dbffc22018-08-08 18:50:41 -07003476 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3477 //
jiabin10d86fd2019-10-31 17:20:42 -07003478 // Note: we access outDeviceTypes() outside of mLock.
3479 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003480 // Here, we try for the AF lock, but do not block on it as the latency
3481 // is more informational.
3482 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3483 std::vector<PatchPanel::SoftwarePatch> swPatches;
3484 double latencyMs;
3485 status_t status = INVALID_OPERATION;
3486 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3487 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3488 && swPatches.size() > 0) {
3489 status = swPatches[0].getLatencyMs_l(&latencyMs);
3490 downstreamPatchHandle = swPatches[0].getPatchHandle();
3491 }
3492 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003493 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003494 lastDownstreamPatchHandle = downstreamPatchHandle;
3495 }
3496 if (status == OK) {
3497 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003498 // latency of 5 seconds).
3499 const double minLatency = 0., maxLatency = 5000.;
3500 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003501 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003502 } else {
3503 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003504 if (latencyMs < minLatency) latencyMs = minLatency;
3505 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003506 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003507 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003508 }
3509 mAudioFlinger->mLock.unlock();
3510 }
3511 } else {
3512 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3513 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003514 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003515 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3516 }
3517 }
3518
Eric Laurent81784c32012-11-19 14:55:58 -08003519 { // scope for mLock
3520
3521 Mutex::Autolock _l(mLock);
3522
Eric Laurent021cf962014-05-13 10:18:14 -07003523 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003524
Glenn Kasteneef598c2017-04-03 14:41:13 -07003525 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003526 if (logString != NULL) {
3527 mNBLogWriter->logTimestamp();
3528 mNBLogWriter->log(logString);
3529 logString = NULL;
3530 }
3531
Dean Wheatley12473e92021-03-18 23:00:55 +11003532 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003533
Eric Laurent81784c32012-11-19 14:55:58 -08003534 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003535 if (mSignalPending) {
3536 // A signal was raised while we were unlocked
3537 mSignalPending = false;
3538 } else if (waitingAsyncCallback_l()) {
3539 if (exitPending()) {
3540 break;
3541 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003542 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003543 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003544 releaseWakeLock_l();
3545 released = true;
3546 }
Andy Hung10cbff12017-02-21 17:30:14 -08003547
3548 const int64_t waitNs = computeWaitTimeNs_l();
3549 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3550 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3551 if (status == TIMED_OUT) {
3552 mSignalPending = true; // if timeout recheck everything
3553 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003554 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003555 if (released) {
3556 acquireWakeLock_l();
3557 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003558 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3559 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003560
3561 continue;
3562 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003563 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003564 isSuspended()) {
3565 // put audio hardware into standby after short delay
3566 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003567
3568 threadLoop_standby();
3569
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003570 // This is where we go into standby
3571 if (!mStandby) {
3572 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003573 mThreadMetrics.logEndInterval();
3574 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003575 }
Andy Hungd0979812019-02-21 15:51:44 -08003576 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003577 }
3578
Eric Tan39ec8d62018-07-24 09:49:29 -07003579 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003580 // we're about to wait, flush the binder command buffer
3581 IPCThreadState::self()->flushCommands();
3582
3583 clearOutputTracks();
3584
3585 if (exitPending()) {
3586 break;
3587 }
3588
3589 releaseWakeLock_l();
3590 // wait until we have something to do...
3591 ALOGV("%s going to sleep", myName.string());
3592 mWaitWorkCV.wait(mLock);
3593 ALOGV("%s waking up", myName.string());
3594 acquireWakeLock_l();
3595
3596 mMixerStatus = MIXER_IDLE;
3597 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3598 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003599 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003600 checkSilentMode_l();
3601
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003602 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3603 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003604 if (mType == MIXER) {
3605 sleepTimeShift = 0;
3606 }
3607
3608 continue;
3609 }
3610 }
Eric Laurent81784c32012-11-19 14:55:58 -08003611 // mMixerStatusIgnoringFastTracks is also updated internally
3612 mMixerStatus = prepareTracks_l(&tracksToRemove);
3613
Andy Hungdae27702016-10-31 14:01:16 -07003614 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003615
Kevin Rocard069c2712018-03-29 19:09:14 -07003616 updateMetadata_l();
3617
Eric Laurent81784c32012-11-19 14:55:58 -08003618 // prevent any changes in effect chain list and in each effect chain
3619 // during mixing and effect process as the audio buffers could be deleted
3620 // or modified if an effect is created or deleted
3621 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003622
3623 // Determine which session to pick up haptic data.
3624 // This must be done under the same lock as prepareTracks_l().
3625 // TODO: Write haptic data directly to sink buffer when mixing.
3626 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3627 for (const auto& track : mActiveTracks) {
3628 if (track->getHapticPlaybackEnabled()) {
3629 activeHapticSessionId = track->sessionId();
3630 break;
3631 }
3632 }
3633 }
3634
Andy Hungc1646382019-04-30 16:12:10 -07003635 // Acquire a local copy of active tracks with lock (release w/o lock).
3636 //
3637 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3638 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3639 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3640 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003641 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003642
Eric Laurentbfb1b832013-01-07 09:53:42 -08003643 if (mBytesRemaining == 0) {
3644 mCurrentWriteLength = 0;
3645 if (mMixerStatus == MIXER_TRACKS_READY) {
3646 // threadLoop_mix() sets mCurrentWriteLength
3647 threadLoop_mix();
3648 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3649 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003650 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003651 // must be written to HAL
3652 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003653 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003654 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003655
3656 // Tally underrun frames as we are inserting 0s here.
3657 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003658 if (track->mFillingUpStatus == Track::FS_ACTIVE
3659 && !track->isStopped()
3660 && !track->isPaused()
3661 && !track->isTerminated()) {
3662 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3663 __func__, track->id(), track->getTrackStateAsString(),
3664 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003665 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3666 }
3667 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003668 }
3669 }
Andy Hung98ef9782014-03-04 14:46:50 -08003670 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003671 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003672 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3673 // or mSinkBuffer (if there are no effects).
3674 //
3675 // This is done pre-effects computation; if effects change to
3676 // support higher precision, this needs to move.
3677 //
3678 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003679 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003680 if (mMixerBufferValid) {
3681 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3682 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3683
Andy Hung2ddee192015-12-18 17:34:44 -08003684 // mono blend occurs for mixer threads only (not direct or offloaded)
3685 // and is handled here if we're going directly to the sink.
3686 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003687 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3688 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003689 }
3690
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003691 if (!hasFastMixer()) {
3692 // Balance must take effect after mono conversion.
3693 // We do it here if there is no FastMixer.
3694 // mBalance detects zero balance within the class for speed (not needed here).
3695 mBalance.setBalance(mMasterBalance.load());
3696 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3697 }
3698
Andy Hung98ef9782014-03-04 14:46:50 -08003699 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003700 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3701
3702 // If we're going directly to the sink and there are haptic channels,
3703 // we should adjust channels as the sample data is partially interleaved
3704 // in this case.
3705 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3706 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3707 mChannelCount + mHapticChannelCount,
3708 audio_bytes_per_sample(format),
3709 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3710 }
Andy Hung98ef9782014-03-04 14:46:50 -08003711 }
3712
Eric Laurentbfb1b832013-01-07 09:53:42 -08003713 mBytesRemaining = mCurrentWriteLength;
3714 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003715 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3716 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3717 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3718 mBytesWritten += mBytesRemaining;
3719 mFramesWritten += framesRemaining;
3720 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003721 mBytesRemaining = 0;
3722 }
Eric Laurent81784c32012-11-19 14:55:58 -08003723
Eric Laurentbfb1b832013-01-07 09:53:42 -08003724 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003725 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003726 for (size_t i = 0; i < effectChains.size(); i ++) {
3727 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003728 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003729 if (activeHapticSessionId != AUDIO_SESSION_NONE
3730 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003731 // Haptic data is active in this case, copy it directly from
3732 // in buffer to out buffer.
3733 const size_t audioBufferSize = mNormalFrameCount
3734 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3735 memcpy_by_audio_format(
3736 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3737 EFFECT_BUFFER_FORMAT,
3738 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3739 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3740 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003741 }
Eric Laurent81784c32012-11-19 14:55:58 -08003742 }
3743 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003744 // Process effect chains for offloaded thread even if no audio
3745 // was read from audio track: process only updates effect state
3746 // and thus does have to be synchronized with audio writes but may have
3747 // to be called while waiting for async write callback
3748 if (mType == OFFLOAD) {
3749 for (size_t i = 0; i < effectChains.size(); i ++) {
3750 effectChains[i]->process_l();
3751 }
3752 }
Eric Laurent81784c32012-11-19 14:55:58 -08003753
Andy Hung98ef9782014-03-04 14:46:50 -08003754 // Only if the Effects buffer is enabled and there is data in the
3755 // Effects buffer (buffer valid), we need to
3756 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003757 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003758 if (mEffectBufferValid) {
3759 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003760
3761 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003762 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3763 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003764 }
3765
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003766 if (!hasFastMixer()) {
3767 // Balance must take effect after mono conversion.
3768 // We do it here if there is no FastMixer.
3769 // mBalance detects zero balance within the class for speed (not needed here).
3770 mBalance.setBalance(mMasterBalance.load());
3771 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3772 }
3773
Andy Hung98ef9782014-03-04 14:46:50 -08003774 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003775 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3776 // The sample data is partially interleaved when haptic channels exist,
3777 // we need to adjust channels here.
3778 if (mHapticChannelCount > 0) {
3779 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3780 mChannelCount + mHapticChannelCount,
3781 audio_bytes_per_sample(mFormat),
3782 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3783 }
Andy Hung98ef9782014-03-04 14:46:50 -08003784 }
3785
Eric Laurent81784c32012-11-19 14:55:58 -08003786 // enable changes in effect chain
3787 unlockEffectChains(effectChains);
3788
Eric Laurentbfb1b832013-01-07 09:53:42 -08003789 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003790 // mSleepTimeUs == 0 means we must write to audio hardware
3791 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003792 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003793 // writePeriodNs is updated >= 0 when ret > 0.
3794 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003795 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003796 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003797 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003798 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003799 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003800 if (ret < 0) {
3801 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003802 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003803 mBytesWritten += ret;
3804 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003805 const int64_t frames = ret / mFrameSize;
3806 mFramesWritten += frames;
3807
3808 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3809 // process information relating to write time.
3810 if (audio_has_proportional_frames(mFormat)) {
3811 // we are in a continuous mixing cycle
3812 if (mMixerStatus == MIXER_TRACKS_READY &&
3813 loopCount == lastLoopCountWritten + 1) {
3814
3815 const double jitterMs =
3816 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3817 {frames, writePeriodNs},
3818 {0, 0} /* lastTimestamp */, mSampleRate);
3819 const double processMs =
3820 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3821
3822 Mutex::Autolock _l(mLock);
3823 mIoJitterMs.add(jitterMs);
3824 mProcessTimeMs.add(processMs);
3825 }
3826
3827 // write blocked detection
3828 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3829 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3830 mNumDelayedWrites++;
3831 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3832 ATRACE_NAME("underrun");
3833 ALOGW("write blocked for %lld msecs, "
3834 "%d delayed writes, thread %d",
3835 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3836 mNumDelayedWrites, mId);
3837 lastWarning = lastIoEndNs;
3838 }
3839 }
3840 }
3841 // update timing info.
3842 mLastIoBeginNs = lastIoBeginNs;
3843 mLastIoEndNs = lastIoEndNs;
3844 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003845 }
3846 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3847 (mMixerStatus == MIXER_DRAIN_ALL)) {
3848 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003849 }
Andy Hung08fb1742015-05-31 23:22:10 -07003850 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003851
3852 if (mThreadThrottle
3853 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003854 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003855 // Limit MixerThread data processing to no more than twice the
3856 // expected processing rate.
3857 //
3858 // This helps prevent underruns with NuPlayer and other applications
3859 // which may set up buffers that are close to the minimum size, or use
3860 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3861 //
3862 // The throttle smooths out sudden large data drains from the device,
3863 // e.g. when it comes out of standby, which often causes problems with
3864 // (1) mixer threads without a fast mixer (which has its own warm-up)
3865 // (2) minimum buffer sized tracks (even if the track is full,
3866 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003867 //
3868 // Total time spent in last processing cycle equals time spent in
3869 // 1. threadLoop_write, as well as time spent in
3870 // 2. threadLoop_mix (significant for heavy mixing, especially
3871 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003872
Andy Hung446f4df2019-02-21 12:26:41 -08003873 // it's OK if deltaMs is an overestimate.
3874
3875 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003876
Ivan Lozanoea04d392017-11-07 14:37:07 -08003877 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003878 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07003879 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08003880
Andy Hung08fb1742015-05-31 23:22:10 -07003881 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003882 // notify of throttle start on verbose log
3883 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3884 "mixer(%p) throttle begin:"
3885 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003886 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003887 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003888 // Throttle must be attributed to the previous mixer loop's write time
3889 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003890 // This also ensures proper timing statistics.
3891 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003892 } else {
3893 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3894 if (diff > 0) {
3895 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003896 // but prevent spamming for bluetooth
jiabin10d86fd2019-10-31 17:20:42 -07003897 ALOGD_IF(!isSingleDeviceType(
3898 outDeviceTypes(), audio_is_a2dp_out_device) &&
3899 !isSingleDeviceType(
3900 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003901 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003902 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3903 }
Andy Hung08fb1742015-05-31 23:22:10 -07003904 }
3905 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003906 }
Eric Laurent81784c32012-11-19 14:55:58 -08003907
Eric Laurentbfb1b832013-01-07 09:53:42 -08003908 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003909 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003910 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003911 // suspended requires accurate metering of sleep time.
3912 if (isSuspended()) {
3913 // advance by expected sleepTime
3914 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3915 const nsecs_t nowNs = systemTime();
3916
3917 // compute expected next time vs current time.
3918 // (negative deltas are treated as delays).
3919 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3920 if (deltaNs < -kMaxNextBufferDelayNs) {
3921 // Delays longer than the max allowed trigger a reset.
3922 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3923 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3924 timeLoopNextNs = nowNs + deltaNs;
3925 } else if (deltaNs < 0) {
3926 // Delays within the max delay allowed: zero the delta/sleepTime
3927 // to help the system catch up in the next iteration(s)
3928 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3929 deltaNs = 0;
3930 }
3931 // update sleep time (which is >= 0)
3932 mSleepTimeUs = deltaNs / 1000;
3933 }
Eric Laurente93cc032016-05-05 10:15:10 -07003934 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3935 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003936 }
Glenn Kastene7754022014-10-31 12:11:26 -07003937 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003938 }
Eric Laurent81784c32012-11-19 14:55:58 -08003939 }
3940
3941 // Finally let go of removed track(s), without the lock held
3942 // since we can't guarantee the destructors won't acquire that
3943 // same lock. This will also mutate and push a new fast mixer state.
3944 threadLoop_removeTracks(tracksToRemove);
3945 tracksToRemove.clear();
3946
3947 // FIXME I don't understand the need for this here;
3948 // it was in the original code but maybe the
3949 // assignment in saveOutputTracks() makes this unnecessary?
3950 clearOutputTracks();
3951
3952 // Effect chains will be actually deleted here if they were removed from
3953 // mEffectChains list during mixing or effects processing
3954 effectChains.clear();
3955
3956 // FIXME Note that the above .clear() is no longer necessary since effectChains
3957 // is now local to this block, but will keep it for now (at least until merge done).
3958 }
3959
Eric Laurentbfb1b832013-01-07 09:53:42 -08003960 threadLoop_exit();
3961
Eric Laurentcf817a22014-08-04 20:36:31 -07003962 if (!mStandby) {
3963 threadLoop_standby();
3964 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003965 }
3966
3967 releaseWakeLock();
3968
3969 ALOGV("Thread %p type %d exiting", this, mType);
3970 return false;
3971}
3972
Dean Wheatley12473e92021-03-18 23:00:55 +11003973void AudioFlinger::PlaybackThread::collectTimestamps_l()
3974{
3975 // Collect timestamp statistics for the Playback Thread types that support it.
3976 if (mType != MIXER
3977 && mType != DUPLICATING
3978 && mType != DIRECT
3979 && mType != OFFLOAD) {
3980 return;
3981 }
3982 if (mStandby) {
3983 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
3984 return;
3985 } else if (mHwPaused) {
3986 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
3987 return;
3988 }
3989
3990 // Gather the framesReleased counters for all active tracks,
3991 // and associate with the sink frames written out. We need
3992 // this to convert the sink timestamp to the track timestamp.
3993 bool kernelLocationUpdate = false;
3994 ExtendedTimestamp timestamp; // use private copy to fetch
3995
3996 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
3997 // HAL may be draining some small duration buffered data for fade out.
3998 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3999 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4000 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4001 mSampleRate);
4002
4003 if (isTimestampCorrectionEnabled()) {
4004 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4005 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4006 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4007 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4008 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4009 = correctedTimestamp.mFrames;
4010 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4011 = correctedTimestamp.mTimeNs;
4012 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4013 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4014 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4015
4016 // Note: Downstream latency only added if timestamp correction enabled.
4017 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4018 const int64_t newPosition =
4019 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4020 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4021 // prevent retrograde
4022 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4023 newPosition,
4024 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4025 - mSuspendedFrames));
4026 }
4027 }
4028
4029 // We always fetch the timestamp here because often the downstream
4030 // sink will block while writing.
4031
4032 // We keep track of the last valid kernel position in case we are in underrun
4033 // and the normal mixer period is the same as the fast mixer period, or there
4034 // is some error from the HAL.
4035 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4036 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4037 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4038 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4039 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4040
4041 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4042 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4043 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4044 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4045 }
4046
4047 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4048 kernelLocationUpdate = true;
4049 } else {
4050 ALOGVV("getTimestamp error - no valid kernel position");
4051 }
4052
4053 // copy over kernel info
4054 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4055 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4056 + mSuspendedFrames; // add frames discarded when suspended
4057 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4058 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4059 } else {
4060 mTimestampVerifier.error();
4061 }
4062
4063 // mFramesWritten for non-offloaded tracks are contiguous
4064 // even after standby() is called. This is useful for the track frame
4065 // to sink frame mapping.
4066 bool serverLocationUpdate = false;
4067 if (mFramesWritten != mLastFramesWritten) {
4068 serverLocationUpdate = true;
4069 mLastFramesWritten = mFramesWritten;
4070 }
4071 // Only update timestamps if there is a meaningful change.
4072 // Either the kernel timestamp must be valid or we have written something.
4073 if (kernelLocationUpdate || serverLocationUpdate) {
4074 if (serverLocationUpdate) {
4075 // use the time before we called the HAL write - it is a bit more accurate
4076 // to when the server last read data than the current time here.
4077 //
4078 // If we haven't written anything, mLastIoBeginNs will be -1
4079 // and we use systemTime().
4080 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4081 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4082 ? systemTime() : mLastIoBeginNs;
4083 }
4084
4085 for (const sp<Track> &t : mActiveTracks) {
4086 if (!t->isFastTrack()) {
4087 t->updateTrackFrameInfo(
4088 t->mAudioTrackServerProxy->framesReleased(),
4089 mFramesWritten,
4090 mSampleRate,
4091 mTimestamp);
4092 }
4093 }
4094 }
4095
4096 if (audio_has_proportional_frames(mFormat)) {
4097 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4098 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4099 mLatencyMs.add(latencyMs);
4100 }
4101 }
4102#if 0
4103 // logFormat example
4104 if (z % 100 == 0) {
4105 timespec ts;
4106 clock_gettime(CLOCK_MONOTONIC, &ts);
4107 LOGT("This is an integer %d, this is a float %f, this is my "
4108 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4109 LOGT("A deceptive null-terminated string %\0");
4110 }
4111 ++z;
4112#endif
4113}
4114
Eric Laurentbfb1b832013-01-07 09:53:42 -08004115// removeTracks_l() must be called with ThreadBase::mLock held
4116void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4117{
Andy Hungfe726a62018-09-27 15:17:25 -07004118 for (const auto& track : tracksToRemove) {
4119 mActiveTracks.remove(track);
4120 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4121 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4122 if (chain != 0) {
4123 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4124 __func__, track->id(), chain.get(), track->sessionId());
4125 chain->decActiveTrackCnt();
4126 }
4127 // If an external client track, inform APM we're no longer active, and remove if needed.
4128 // We do this under lock so that the state is consistent if the Track is destroyed.
4129 if (track->isExternalTrack()) {
4130 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004131 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004132 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004133 }
4134 }
Andy Hungfe726a62018-09-27 15:17:25 -07004135 if (track->isTerminated()) {
4136 // remove from our tracks vector
4137 removeTrack_l(track);
4138 }
jiabin57303cc2018-12-18 15:45:57 -08004139 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4140 && mHapticChannelCount > 0) {
4141 mLock.unlock();
4142 // Unlock due to VibratorService will lock for this call and will
4143 // call Tracks.mute/unmute which also require thread's lock.
4144 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4145 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08004146 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004147 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004148}
Eric Laurent81784c32012-11-19 14:55:58 -08004149
Eric Laurentaccc1472013-09-20 09:36:34 -07004150status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4151{
4152 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004153 ExtendedTimestamp ets;
4154 status_t status = mNormalSink->getTimestamp(ets);
4155 if (status == NO_ERROR) {
4156 status = ets.getBestTimestamp(&timestamp);
4157 }
4158 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004159 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004160 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004161 collectTimestamps_l();
4162 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4163 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004164 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004165 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4166 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4167 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4168 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4169 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004170 }
4171 return INVALID_OPERATION;
4172}
Eric Laurent1c333e22014-05-20 10:48:17 -07004173
Eric Laurenteab90452019-06-24 15:17:46 -07004174// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4175// still applied by the mixer.
4176// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4177// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4178// if more than one track are active
4179status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4180{
4181 status_t result = NO_ERROR;
4182 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4183 if (*volume != mLeftVolFloat) {
4184 result = mOutput->stream->setVolume(*volume, *volume);
4185 ALOGE_IF(result != OK,
4186 "Error when setting output stream volume: %d", result);
4187 if (result == NO_ERROR) {
4188 mLeftVolFloat = *volume;
4189 }
4190 }
4191 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4192 // remove stream volume contribution from software volume.
4193 if (mLeftVolFloat == *volume) {
4194 *volume = 1.0f;
4195 }
4196 }
4197 return result;
4198}
4199
Eric Laurent054d9d32015-04-24 08:48:48 -07004200status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4201 audio_patch_handle_t *handle)
4202{
Andy Hungf60abce2016-08-26 11:37:54 -07004203 status_t status;
4204 if (property_get_bool("af.patch_park", false /* default_value */)) {
4205 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4206 // or if HAL does not properly lock against access.
4207 AutoPark<FastMixer> park(mFastMixer);
4208 status = PlaybackThread::createAudioPatch_l(patch, handle);
4209 } else {
4210 status = PlaybackThread::createAudioPatch_l(patch, handle);
4211 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004212 return status;
4213}
4214
Eric Laurent1c333e22014-05-20 10:48:17 -07004215status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4216 audio_patch_handle_t *handle)
4217{
4218 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004219
4220 // store new device and send to effects
4221 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabin10d86fd2019-10-31 17:20:42 -07004222 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004223 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabin10d86fd2019-10-31 17:20:42 -07004224 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4225 && !mOutput->audioHwDev->supportsAudioPatches(),
4226 "Enumerated device type(%#x) must not be used "
4227 "as it does not support audio patches",
4228 patch->sinks[i].ext.device.type);
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07004229 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabin10d86fd2019-10-31 17:20:42 -07004230 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4231 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004232 }
4233
François Gaffie0c280aa2018-07-25 10:02:15 +02004234 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004235#ifdef ADD_BATTERY_DATA
4236 // when changing the audio output device, call addBatteryData to notify
4237 // the change
jiabin10d86fd2019-10-31 17:20:42 -07004238 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004239 uint32_t params = 0;
4240 // check whether speaker is on
jiabin10d86fd2019-10-31 17:20:42 -07004241 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004242 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004243 }
4244
Eric Laurent054d9d32015-04-24 08:48:48 -07004245 // check if any other device (except speaker) is on
jiabin10d86fd2019-10-31 17:20:42 -07004246 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004247 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4248 }
4249
4250 if (params != 0) {
4251 addBatteryData(params);
4252 }
4253 }
4254#endif
4255
4256 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08004257 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004258 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004259
jiabin10d86fd2019-10-31 17:20:42 -07004260 // mPatch.num_sinks is not set when the thread is created so that
4261 // the first patch creation triggers an ioConfigChanged callback
4262 bool configChanged = (mPatch.num_sinks == 0) ||
4263 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004264 mPatch = *patch;
jiabin10d86fd2019-10-31 17:20:42 -07004265 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004266 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004267
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004268 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004269 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4270 status = hwDevice->createAudioPatch(patch->num_sources,
4271 patch->sources,
4272 patch->num_sinks,
4273 patch->sinks,
4274 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004275 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004276 char *address;
4277 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4278 //FIXME: we only support address on first sink with HAL version < 3.0
4279 address = audio_device_address_to_parameter(
4280 patch->sinks[0].ext.device.type,
4281 patch->sinks[0].ext.device.address);
4282 } else {
4283 address = (char *)calloc(1, 1);
4284 }
4285 AudioParameter param = AudioParameter(String8(address));
4286 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004287 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004288 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004289 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004290 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004291 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004292
4293 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004294 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004295 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004296 // also dispatch to active AudioTracks for MediaMetrics
4297 for (const auto &track : mActiveTracks) {
4298 track->logEndInterval();
4299 track->logBeginInterval(patchSinksAsString);
4300 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004301
Eric Laurente8726fe2015-06-26 09:39:24 -07004302 if (configChanged) {
4303 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4304 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004305 return status;
4306}
4307
Eric Laurent054d9d32015-04-24 08:48:48 -07004308status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4309{
Andy Hungf60abce2016-08-26 11:37:54 -07004310 status_t status;
4311 if (property_get_bool("af.patch_park", false /* default_value */)) {
4312 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4313 // or if HAL does not properly lock against access.
4314 AutoPark<FastMixer> park(mFastMixer);
4315 status = PlaybackThread::releaseAudioPatch_l(handle);
4316 } else {
4317 status = PlaybackThread::releaseAudioPatch_l(handle);
4318 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004319 return status;
4320}
4321
Eric Laurent1c333e22014-05-20 10:48:17 -07004322status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4323{
4324 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004325
jiabin10d86fd2019-10-31 17:20:42 -07004326 mPatch = audio_patch{};
4327 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004328
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004329 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004330 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4331 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004332 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004333 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004334 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004335 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004336 }
4337 return status;
4338}
4339
Eric Laurent83b88082014-06-20 18:31:16 -07004340void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4341{
4342 Mutex::Autolock _l(mLock);
4343 mTracks.add(track);
4344}
4345
4346void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4347{
4348 Mutex::Autolock _l(mLock);
4349 destroyTrack_l(track);
4350}
4351
Mikhail Naganovdc769682018-05-04 15:34:08 -07004352void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004353{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004354 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004355 config->role = AUDIO_PORT_ROLE_SOURCE;
4356 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4357 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004358 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4359 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4360 config->flags.output = mOutput->flags;
4361 }
Eric Laurent83b88082014-06-20 18:31:16 -07004362}
4363
Eric Laurent81784c32012-11-19 14:55:58 -08004364// ----------------------------------------------------------------------------
4365
4366AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabin10d86fd2019-10-31 17:20:42 -07004367 audio_io_handle_t id, bool systemReady, type_t type)
4368 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004369 // mAudioMixer below
4370 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004371 mFastMixerFutex(0),
4372 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004373 // mOutputSink below
4374 // mPipeSink below
4375 // mNormalSink below
4376{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004377 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabin10d86fd2019-10-31 17:20:42 -07004378 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004379 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004380 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004381 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4382 mNormalFrameCount);
4383 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4384
Andy Hungfbfc3952015-01-15 13:33:51 -08004385 if (type == DUPLICATING) {
4386 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4387 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4388 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4389 return;
4390 }
Eric Laurent81784c32012-11-19 14:55:58 -08004391 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004392 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004393 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004394 const NBAIO_Format offers[1] = {Format_from_SR_C(
4395 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004396#if !LOG_NDEBUG
4397 ssize_t index =
4398#else
4399 (void)
4400#endif
4401 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004402 ALOG_ASSERT(index == 0);
4403
4404 // initialize fast mixer depending on configuration
4405 bool initFastMixer;
4406 switch (kUseFastMixer) {
4407 case FastMixer_Never:
4408 initFastMixer = false;
4409 break;
4410 case FastMixer_Always:
4411 initFastMixer = true;
4412 break;
4413 case FastMixer_Static:
4414 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004415 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4416 // where the period is less than an experimentally determined threshold that can be
4417 // scheduled reliably with CFS. However, the BT A2DP HAL is
4418 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4419 initFastMixer = mFrameCount < mNormalFrameCount
jiabin10d86fd2019-10-31 17:20:42 -07004420 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004421 break;
4422 }
Andy Hungfda69402017-02-15 14:33:12 -08004423 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4424 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4425 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004426 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004427 audio_format_t fastMixerFormat;
4428 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4429 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4430 } else {
4431 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4432 }
4433 if (mFormat != fastMixerFormat) {
4434 // change our Sink format to accept our intermediate precision
4435 mFormat = fastMixerFormat;
4436 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004437 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004438 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4439 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4440 }
Eric Laurent81784c32012-11-19 14:55:58 -08004441
4442 // create a MonoPipe to connect our submix to FastMixer
4443 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004444
Andy Hung1258c1a2014-05-23 21:22:17 -07004445 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004446 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004447 format.mFormat = fastMixerFormat;
4448 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4449
Eric Laurent81784c32012-11-19 14:55:58 -08004450 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4451 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4452 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4453 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4454 const NBAIO_Format offers[1] = {format};
4455 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004456#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004457 ssize_t index =
4458#else
4459 (void)
4460#endif
4461 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004462 ALOG_ASSERT(index == 0);
4463 monoPipe->setAvgFrames((mScreenState & 1) ?
4464 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4465 mPipeSink = monoPipe;
4466
Eric Laurent81784c32012-11-19 14:55:58 -08004467 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004468 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004469 FastMixerStateQueue *sq = mFastMixer->sq();
4470#ifdef STATE_QUEUE_DUMP
4471 sq->setObserverDump(&mStateQueueObserverDump);
4472 sq->setMutatorDump(&mStateQueueMutatorDump);
4473#endif
4474 FastMixerState *state = sq->begin();
4475 FastTrack *fastTrack = &state->mFastTracks[0];
4476 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4477 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4478 fastTrack->mVolumeProvider = NULL;
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07004479 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4480 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4481 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004482 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004483 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabin84114c32019-04-10 16:38:07 -07004484 fastTrack->mHapticIntensity = AudioMixer::HAPTIC_SCALE_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004485 fastTrack->mGeneration++;
4486 state->mFastTracksGen++;
4487 state->mTrackMask = 1;
4488 // fast mixer will use the HAL output sink
4489 state->mOutputSink = mOutputSink.get();
4490 state->mOutputSinkGen++;
4491 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004492 // specify sink channel mask when haptic channel mask present as it can not
4493 // be calculated directly from channel count
4494 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07004495 ? AUDIO_CHANNEL_NONE
4496 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004497 state->mCommand = FastMixerState::COLD_IDLE;
4498 // already done in constructor initialization list
4499 //mFastMixerFutex = 0;
4500 state->mColdFutexAddr = &mFastMixerFutex;
4501 state->mColdGen++;
4502 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004503 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4504 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004505 sq->end();
4506 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4507
Eric Tan0513b5d2018-09-17 10:32:48 -07004508 NBLog::thread_info_t info;
4509 info.id = mId;
4510 info.type = NBLog::FASTMIXER;
4511 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4512
Eric Laurent81784c32012-11-19 14:55:58 -08004513 // start the fast mixer
4514 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4515 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004516 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004517 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004518
4519#ifdef AUDIO_WATCHDOG
4520 // create and start the watchdog
4521 mAudioWatchdog = new AudioWatchdog();
4522 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4523 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4524 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004525 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004526#endif
Andy Hung8946a282018-04-19 20:04:56 -07004527 } else {
4528#ifdef TEE_SINK
4529 // Only use the MixerThread tee if there is no FastMixer.
4530 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4531 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4532#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004533 }
4534
4535 switch (kUseFastMixer) {
4536 case FastMixer_Never:
4537 case FastMixer_Dynamic:
4538 mNormalSink = mOutputSink;
4539 break;
4540 case FastMixer_Always:
4541 mNormalSink = mPipeSink;
4542 break;
4543 case FastMixer_Static:
4544 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4545 break;
4546 }
4547}
4548
4549AudioFlinger::MixerThread::~MixerThread()
4550{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004551 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004552 FastMixerStateQueue *sq = mFastMixer->sq();
4553 FastMixerState *state = sq->begin();
4554 if (state->mCommand == FastMixerState::COLD_IDLE) {
4555 int32_t old = android_atomic_inc(&mFastMixerFutex);
4556 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004557 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004558 }
4559 }
4560 state->mCommand = FastMixerState::EXIT;
4561 sq->end();
4562 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4563 mFastMixer->join();
4564 // Though the fast mixer thread has exited, it's state queue is still valid.
4565 // We'll use that extract the final state which contains one remaining fast track
4566 // corresponding to our sub-mix.
4567 state = sq->begin();
4568 ALOG_ASSERT(state->mTrackMask == 1);
4569 FastTrack *fastTrack = &state->mFastTracks[0];
4570 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4571 delete fastTrack->mBufferProvider;
4572 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004573 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004574#ifdef AUDIO_WATCHDOG
4575 if (mAudioWatchdog != 0) {
4576 mAudioWatchdog->requestExit();
4577 mAudioWatchdog->requestExitAndWait();
4578 mAudioWatchdog.clear();
4579 }
4580#endif
4581 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004582 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004583 delete mAudioMixer;
4584}
4585
4586
4587uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4588{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004589 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004590 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4591 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4592 }
4593 return latency;
4594}
4595
Eric Laurentbfb1b832013-01-07 09:53:42 -08004596ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004597{
4598 // FIXME we should only do one push per cycle; confirm this is true
4599 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004600 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004601 FastMixerStateQueue *sq = mFastMixer->sq();
4602 FastMixerState *state = sq->begin();
4603 if (state->mCommand != FastMixerState::MIX_WRITE &&
4604 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4605 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004606
4607 // FIXME workaround for first HAL write being CPU bound on some devices
4608 ATRACE_BEGIN("write");
4609 mOutput->write((char *)mSinkBuffer, 0);
4610 ATRACE_END();
4611
Eric Laurent81784c32012-11-19 14:55:58 -08004612 int32_t old = android_atomic_inc(&mFastMixerFutex);
4613 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004614 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004615 }
4616#ifdef AUDIO_WATCHDOG
4617 if (mAudioWatchdog != 0) {
4618 mAudioWatchdog->resume();
4619 }
4620#endif
4621 }
4622 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004623#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004624 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004625 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004626#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004627 sq->end();
4628 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4629 if (kUseFastMixer == FastMixer_Dynamic) {
4630 mNormalSink = mPipeSink;
4631 }
4632 } else {
4633 sq->end(false /*didModify*/);
4634 }
4635 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004636 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004637}
4638
4639void AudioFlinger::MixerThread::threadLoop_standby()
4640{
4641 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004642 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004643 FastMixerStateQueue *sq = mFastMixer->sq();
4644 FastMixerState *state = sq->begin();
4645 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004646 // Report any frames trapped in the Monopipe
4647 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4648 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4649 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4650 "monoPipeWritten:%lld monoPipeLeft:%lld",
4651 (long long)mFramesWritten, (long long)mSuspendedFrames,
4652 (long long)mPipeSink->framesWritten(), pipeFrames);
4653 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4654
Eric Laurent81784c32012-11-19 14:55:58 -08004655 state->mCommand = FastMixerState::COLD_IDLE;
4656 state->mColdFutexAddr = &mFastMixerFutex;
4657 state->mColdGen++;
4658 mFastMixerFutex = 0;
4659 sq->end();
4660 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4661 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4662 if (kUseFastMixer == FastMixer_Dynamic) {
4663 mNormalSink = mOutputSink;
4664 }
4665#ifdef AUDIO_WATCHDOG
4666 if (mAudioWatchdog != 0) {
4667 mAudioWatchdog->pause();
4668 }
4669#endif
4670 } else {
4671 sq->end(false /*didModify*/);
4672 }
4673 }
4674 PlaybackThread::threadLoop_standby();
4675}
4676
Eric Laurentbfb1b832013-01-07 09:53:42 -08004677bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4678{
4679 return false;
4680}
4681
4682bool AudioFlinger::PlaybackThread::shouldStandby_l()
4683{
4684 return !mStandby;
4685}
4686
4687bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4688{
4689 Mutex::Autolock _l(mLock);
4690 return waitingAsyncCallback_l();
4691}
4692
Eric Laurent81784c32012-11-19 14:55:58 -08004693// shared by MIXER and DIRECT, overridden by DUPLICATING
4694void AudioFlinger::PlaybackThread::threadLoop_standby()
4695{
4696 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004697 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004698 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004699 // discard any pending drain or write ack by incrementing sequence
4700 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4701 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004702 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004703 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4704 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004705 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004706 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004707}
4708
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004709void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4710{
4711 ALOGV("signal playback thread");
4712 broadcast_l();
4713}
4714
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004715void AudioFlinger::PlaybackThread::onAsyncError()
4716{
4717 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4718 invalidateTracks((audio_stream_type_t)i);
4719 }
4720}
4721
Eric Laurent81784c32012-11-19 14:55:58 -08004722void AudioFlinger::MixerThread::threadLoop_mix()
4723{
Eric Laurent81784c32012-11-19 14:55:58 -08004724 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004725 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004726 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004727 // increase sleep time progressively when application underrun condition clears.
4728 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4729 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4730 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004731 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004732 sleepTimeShift--;
4733 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004734 mSleepTimeUs = 0;
4735 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004736 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004737
Eric Laurent81784c32012-11-19 14:55:58 -08004738}
4739
4740void AudioFlinger::MixerThread::threadLoop_sleepTime()
4741{
4742 // If no tracks are ready, sleep once for the duration of an output
4743 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004744 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004745 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004746 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4747 // Using the Monopipe availableToWrite, we estimate the
4748 // sleep time to retry for more data (before we underrun).
4749 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4750 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4751 const size_t pipeFrames = monoPipe->maxFrames();
4752 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4753 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4754 const size_t framesDelay = std::min(
4755 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4756 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4757 pipeFrames, framesLeft, framesDelay);
4758 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4759 } else {
4760 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4761 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4762 mSleepTimeUs = kMinThreadSleepTimeUs;
4763 }
4764 // reduce sleep time in case of consecutive application underruns to avoid
4765 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4766 // duration we would end up writing less data than needed by the audio HAL if
4767 // the condition persists.
4768 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4769 sleepTimeShift++;
4770 }
Eric Laurent81784c32012-11-19 14:55:58 -08004771 }
4772 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004773 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004774 }
4775 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004776 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4777 // before effects processing or output.
4778 if (mMixerBufferValid) {
4779 memset(mMixerBuffer, 0, mMixerBufferSize);
4780 } else {
4781 memset(mSinkBuffer, 0, mSinkBufferSize);
4782 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004783 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004784 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4785 "anticipated start");
4786 }
4787 // TODO add standby time extension fct of effect tail
4788}
4789
4790// prepareTracks_l() must be called with ThreadBase::mLock held
4791AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4792 Vector< sp<Track> > *tracksToRemove)
4793{
Andy Hungc0691382018-09-12 18:01:57 -07004794 // clean up deleted track ids in AudioMixer before allocating new tracks
4795 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4796 // for each trackId, destroy it in the AudioMixer
4797 if (mAudioMixer->exists(trackId)) {
4798 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004799 }
4800 });
Andy Hungc0691382018-09-12 18:01:57 -07004801 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004802
4803 mixer_state mixerStatus = MIXER_IDLE;
4804 // find out which tracks need to be processed
4805 size_t count = mActiveTracks.size();
4806 size_t mixedTracks = 0;
4807 size_t tracksWithEffect = 0;
4808 // counts only _active_ fast tracks
4809 size_t fastTracks = 0;
4810 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4811
4812 float masterVolume = mMasterVolume;
4813 bool masterMute = mMasterMute;
4814
4815 if (masterMute) {
4816 masterVolume = 0;
4817 }
4818 // Delegate master volume control to effect in output mix effect chain if needed
4819 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4820 if (chain != 0) {
4821 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4822 chain->setVolume_l(&v, &v);
4823 masterVolume = (float)((v + (1 << 23)) >> 24);
4824 chain.clear();
4825 }
4826
4827 // prepare a new state to push
4828 FastMixerStateQueue *sq = NULL;
4829 FastMixerState *state = NULL;
4830 bool didModify = false;
4831 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004832 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004833 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004834 sq = mFastMixer->sq();
4835 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004836 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004837 }
4838
Andy Hung69aed5f2014-02-25 17:24:40 -08004839 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004840 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004841
Andy Hungbd3b2b02018-05-21 10:53:11 -07004842 // DeferredOperations handles statistics after setting mixerStatus.
4843 class DeferredOperations {
4844 public:
Andy Hungea840382020-05-05 21:50:17 -07004845 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4846 : mMixerStatus(mixerStatus)
4847 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004848
4849 // when leaving scope, tally frames properly.
4850 ~DeferredOperations() {
4851 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4852 // because that is when the underrun occurs.
4853 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004854 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004855 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004856 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004857 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004858 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004859 }
4860 }
Andy Hungea840382020-05-05 21:50:17 -07004861 // send the max underrun frames for this mixer period
4862 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004863 }
4864
4865 // tallyUnderrunFrames() is called to update the track counters
4866 // with the number of underrun frames for a particular mixer period.
4867 // We defer tallying until we know the final mixer status.
4868 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4869 mUnderrunFrames.emplace_back(track, underrunFrames);
4870 }
4871
4872 private:
4873 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004874 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004875 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004876 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004877 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004878
jiabin245cdd92018-12-07 17:55:15 -08004879 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004880 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004881 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004882
4883 // this const just means the local variable doesn't change
4884 Track* const track = t.get();
4885
4886 // process fast tracks
4887 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004888 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4889 "%s(%d): FastTrack(%d) present without FastMixer",
4890 __func__, id(), track->id());
4891
jiabin245cdd92018-12-07 17:55:15 -08004892 if (track->getHapticPlaybackEnabled()) {
4893 noFastHapticTrack = false;
4894 }
Eric Laurent81784c32012-11-19 14:55:58 -08004895
4896 // It's theoretically possible (though unlikely) for a fast track to be created
4897 // and then removed within the same normal mix cycle. This is not a problem, as
4898 // the track never becomes active so it's fast mixer slot is never touched.
4899 // The converse, of removing an (active) track and then creating a new track
4900 // at the identical fast mixer slot within the same normal mix cycle,
4901 // is impossible because the slot isn't marked available until the end of each cycle.
4902 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004903 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004904 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4905 FastTrack *fastTrack = &state->mFastTracks[j];
4906
4907 // Determine whether the track is currently in underrun condition,
4908 // and whether it had a recent underrun.
4909 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4910 FastTrackUnderruns underruns = ftDump->mUnderruns;
4911 uint32_t recentFull = (underruns.mBitFields.mFull -
4912 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4913 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4914 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4915 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4916 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4917 uint32_t recentUnderruns = recentPartial + recentEmpty;
4918 track->mObservedUnderruns = underruns;
4919 // don't count underruns that occur while stopping or pausing
4920 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004921 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004922 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4923 recentUnderruns > 0) {
4924 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004925 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004926 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004927 // Immediately account for FastTrack underruns.
4928 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004929
4930 // This is similar to the state machine for normal tracks,
4931 // with a few modifications for fast tracks.
4932 bool isActive = true;
4933 switch (track->mState) {
4934 case TrackBase::STOPPING_1:
4935 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004936 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004937 track->mState = TrackBase::STOPPING_2;
4938 }
4939 break;
4940 case TrackBase::PAUSING:
4941 // ramp down is not yet implemented
4942 track->setPaused();
4943 break;
4944 case TrackBase::RESUMING:
4945 // ramp up is not yet implemented
4946 track->mState = TrackBase::ACTIVE;
4947 break;
4948 case TrackBase::ACTIVE:
4949 if (recentFull > 0 || recentPartial > 0) {
4950 // track has provided at least some frames recently: reset retry count
4951 track->mRetryCount = kMaxTrackRetries;
4952 }
4953 if (recentUnderruns == 0) {
4954 // no recent underruns: stay active
4955 break;
4956 }
4957 // there has recently been an underrun of some kind
4958 if (track->sharedBuffer() == 0) {
4959 // were any of the recent underruns "empty" (no frames available)?
4960 if (recentEmpty == 0) {
4961 // no, then ignore the partial underruns as they are allowed indefinitely
4962 break;
4963 }
4964 // there has recently been an "empty" underrun: decrement the retry counter
4965 if (--(track->mRetryCount) > 0) {
4966 break;
4967 }
4968 // indicate to client process that the track was disabled because of underrun;
4969 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004970 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004971 // remove from active list, but state remains ACTIVE [confusing but true]
4972 isActive = false;
4973 break;
4974 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004975 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004976 case TrackBase::STOPPING_2:
4977 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004978 case TrackBase::STOPPED:
4979 case TrackBase::FLUSHED: // flush() while active
4980 // Check for presentation complete if track is inactive
4981 // We have consumed all the buffers of this track.
4982 // This would be incomplete if we auto-paused on underrun
4983 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004984 uint32_t latency = 0;
4985 status_t result = mOutput->stream->getLatency(&latency);
4986 ALOGE_IF(result != OK,
4987 "Error when retrieving output stream latency: %d", result);
4988 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004989 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004990 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4991 // track stays in active list until presentation is complete
4992 break;
4993 }
4994 }
4995 if (track->isStopping_2()) {
4996 track->mState = TrackBase::STOPPED;
4997 }
4998 if (track->isStopped()) {
4999 // Can't reset directly, as fast mixer is still polling this track
5000 // track->reset();
5001 // So instead mark this track as needing to be reset after push with ack
5002 resetMask |= 1 << i;
5003 }
5004 isActive = false;
5005 break;
5006 case TrackBase::IDLE:
5007 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005008 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005009 }
5010
5011 if (isActive) {
5012 // was it previously inactive?
5013 if (!(state->mTrackMask & (1 << j))) {
5014 ExtendedAudioBufferProvider *eabp = track;
5015 VolumeProvider *vp = track;
5016 fastTrack->mBufferProvider = eabp;
5017 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005018 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005019 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005020 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005021 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005022 fastTrack->mGeneration++;
5023 state->mTrackMask |= 1 << j;
5024 didModify = true;
5025 // no acknowledgement required for newly active tracks
5026 }
Kevin Rocard12381092018-04-11 09:19:59 -07005027 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005028 float volume;
5029 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5030 volume = 0.f;
5031 } else {
5032 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5033 }
5034
5035 handleVoipVolume_l(&volume);
5036
Eric Laurent81784c32012-11-19 14:55:58 -08005037 // cache the combined master volume and stream type volume for fast mixer; this
5038 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005039 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005040 proxy->framesReleased()).first;
5041 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005042 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005043 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5044 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5045 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005046
Kevin Rocard12381092018-04-11 09:19:59 -07005047 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005048 ++fastTracks;
5049 } else {
5050 // was it previously active?
5051 if (state->mTrackMask & (1 << j)) {
5052 fastTrack->mBufferProvider = NULL;
5053 fastTrack->mGeneration++;
5054 state->mTrackMask &= ~(1 << j);
5055 didModify = true;
5056 // If any fast tracks were removed, we must wait for acknowledgement
5057 // because we're about to decrement the last sp<> on those tracks.
5058 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5059 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005060 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5061 // AudioTrack may start (which may not be with a start() but with a write()
5062 // after underrun) and immediately paused or released. In that case the
5063 // FastTrack state hasn't had time to update.
5064 // TODO Remove the ALOGW when this theory is confirmed.
5065 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005066 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5067 j, track->mState, state->mTrackMask, recentUnderruns,
5068 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005069 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005070 }
5071 tracksToRemove->add(track);
5072 // Avoids a misleading display in dumpsys
5073 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5074 }
jiabin245cdd92018-12-07 17:55:15 -08005075 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5076 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5077 didModify = true;
5078 }
Eric Laurent81784c32012-11-19 14:55:58 -08005079 continue;
5080 }
5081
5082 { // local variable scope to avoid goto warning
5083
5084 audio_track_cblk_t* cblk = track->cblk();
5085
5086 // The first time a track is added we wait
5087 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005088 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005089
5090 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005091 // use the trackId as the AudioMixer name.
5092 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005093 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005094 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005095 track->mChannelMask,
5096 track->mFormat,
5097 track->mSessionId);
5098 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005099 ALOGW("%s(): AudioMixer cannot create track(%d)"
5100 " mask %#x, format %#x, sessionId %d",
5101 __func__, trackId,
5102 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005103 tracksToRemove->add(track);
5104 track->invalidate(); // consider it dead.
5105 continue;
5106 }
5107 }
5108
Eric Laurent81784c32012-11-19 14:55:58 -08005109 // make sure that we have enough frames to mix one full buffer.
5110 // enforce this condition only once to enable draining the buffer in case the client
5111 // app does not call stop() and relies on underrun to stop:
5112 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5113 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005114 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005115 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005116 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005117
5118 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005119 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005120 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5121 // add frames already consumed but not yet released by the resampler
5122 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005123 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005124
Eric Laurent81784c32012-11-19 14:55:58 -08005125 uint32_t minFrames = 1;
5126 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5127 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005128 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005129 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005130
5131 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005132 if (ATRACE_ENABLED()) {
5133 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005134 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005135 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005136 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005137 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005138 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005139 !track->isPaused() && !track->isTerminated())
5140 {
Andy Hungc0691382018-09-12 18:01:57 -07005141 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005142
5143 mixedTracks++;
5144
Andy Hung69aed5f2014-02-25 17:24:40 -08005145 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5146 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005147 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005148 if (track->mainBuffer() != mSinkBuffer &&
5149 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005150 if (mEffectBufferEnabled) {
5151 mEffectBufferValid = true; // Later can set directly.
5152 }
Eric Laurent81784c32012-11-19 14:55:58 -08005153 chain = getEffectChain_l(track->sessionId());
5154 // Delegate volume control to effect in track effect chain if needed
5155 if (chain != 0) {
5156 tracksWithEffect++;
5157 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005158 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005159 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005160 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005161 }
5162 }
5163
5164
5165 int param = AudioMixer::VOLUME;
5166 if (track->mFillingUpStatus == Track::FS_FILLED) {
5167 // no ramp for the first volume setting
5168 track->mFillingUpStatus = Track::FS_ACTIVE;
5169 if (track->mState == TrackBase::RESUMING) {
5170 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005171 // If a new track is paused immediately after start, do not ramp on resume.
5172 if (cblk->mServer != 0) {
5173 param = AudioMixer::RAMP_VOLUME;
5174 }
Eric Laurent81784c32012-11-19 14:55:58 -08005175 }
Andy Hungc0691382018-09-12 18:01:57 -07005176 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005177 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005178 // FIXME should not make a decision based on mServer
5179 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005180 // If the track is stopped before the first frame was mixed,
5181 // do not apply ramp
5182 param = AudioMixer::RAMP_VOLUME;
5183 }
5184
5185 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005186 uint32_t vl, vr; // in U8.24 integer format
5187 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005188 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005189 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005190 // Always fetch volumeshaper volume to ensure state is updated.
5191 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5192 const float vh = track->getVolumeHandler()->getVolume(
5193 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005194
Eric Laurenteab90452019-06-24 15:17:46 -07005195 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5196 v = 0;
5197 }
5198
5199 handleVoipVolume_l(&v);
5200
5201 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005202 vl = vr = 0;
5203 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005204 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005205 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005206 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005207 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5208 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005209 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005210 if (vlf > GAIN_FLOAT_UNITY) {
5211 ALOGV("Track left volume out of range: %.3g", vlf);
5212 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005213 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005214 if (vrf > GAIN_FLOAT_UNITY) {
5215 ALOGV("Track right volume out of range: %.3g", vrf);
5216 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005217 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005218 // now apply the master volume and stream type volume and shaper volume
5219 vlf *= v * vh;
5220 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005221 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005222 // then derive vl and vr as U8.24 versions for the effect chain
5223 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5224 vl = (uint32_t) (scaleto8_24 * vlf);
5225 vr = (uint32_t) (scaleto8_24 * vrf);
5226 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005227 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005228 // send level comes from shared memory and so may be corrupt
5229 if (sendLevel > MAX_GAIN_INT) {
5230 ALOGV("Track send level out of range: %04X", sendLevel);
5231 sendLevel = MAX_GAIN_INT;
5232 }
Andy Hung6be49402014-05-30 10:42:03 -07005233 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5234 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005235 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005236
Kevin Rocard12381092018-04-11 09:19:59 -07005237 track->setFinalVolume((vrf + vlf) / 2.f);
5238
Eric Laurent81784c32012-11-19 14:55:58 -08005239 // Delegate volume control to effect in track effect chain if needed
5240 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5241 // Do not ramp volume if volume is controlled by effect
5242 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005243 // Update remaining floating point volume levels
5244 vlf = (float)vl / (1 << 24);
5245 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005246 track->mHasVolumeController = true;
5247 } else {
5248 // force no volume ramp when volume controller was just disabled or removed
5249 // from effect chain to avoid volume spike
5250 if (track->mHasVolumeController) {
5251 param = AudioMixer::VOLUME;
5252 }
5253 track->mHasVolumeController = false;
5254 }
5255
Eric Laurent81784c32012-11-19 14:55:58 -08005256 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005257 mAudioMixer->setBufferProvider(trackId, track);
5258 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005259
Andy Hungc0691382018-09-12 18:01:57 -07005260 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5261 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5262 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005263 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005264 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005265 AudioMixer::TRACK,
5266 AudioMixer::FORMAT, (void *)track->format());
5267 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005268 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005269 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005270 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005271 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005272 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005273 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005274 AudioMixer::MIXER_CHANNEL_MASK,
5275 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005276 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005277 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005278 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005279 if (reqSampleRate == 0) {
5280 reqSampleRate = mSampleRate;
5281 } else if (reqSampleRate > maxSampleRate) {
5282 reqSampleRate = maxSampleRate;
5283 }
Eric Laurent81784c32012-11-19 14:55:58 -08005284 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005285 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005286 AudioMixer::RESAMPLE,
5287 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005288 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005289
Andy Hung333ab962019-05-28 20:23:35 -07005290 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005291 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005292 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005293 AudioMixer::TIMESTRETCH,
5294 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005295 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005296
Andy Hung69aed5f2014-02-25 17:24:40 -08005297 /*
5298 * Select the appropriate output buffer for the track.
5299 *
Andy Hung98ef9782014-03-04 14:46:50 -08005300 * Tracks with effects go into their own effects chain buffer
5301 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005302 *
5303 * Other tracks can use mMixerBuffer for higher precision
5304 * channel accumulation. If this buffer is enabled
5305 * (mMixerBufferEnabled true), then selected tracks will accumulate
5306 * into it.
5307 *
5308 */
5309 if (mMixerBufferEnabled
5310 && (track->mainBuffer() == mSinkBuffer
5311 || track->mainBuffer() == mMixerBuffer)) {
5312 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005313 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005314 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005315 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005316 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005317 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005318 AudioMixer::TRACK,
5319 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5320 // TODO: override track->mainBuffer()?
5321 mMixerBufferValid = true;
5322 } else {
5323 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005324 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005325 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005326 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005327 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005328 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005329 AudioMixer::TRACK,
5330 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5331 }
Eric Laurent81784c32012-11-19 14:55:58 -08005332 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005333 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005334 AudioMixer::TRACK,
5335 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005336 mAudioMixer->setParameter(
5337 trackId,
5338 AudioMixer::TRACK,
5339 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005340 mAudioMixer->setParameter(
5341 trackId,
5342 AudioMixer::TRACK,
5343 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005344
5345 // reset retry count
5346 track->mRetryCount = kMaxTrackRetries;
5347
5348 // If one track is ready, set the mixer ready if:
5349 // - the mixer was not ready during previous round OR
5350 // - no other track is not ready
5351 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5352 mixerStatus != MIXER_TRACKS_ENABLED) {
5353 mixerStatus = MIXER_TRACKS_READY;
5354 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005355
5356 // Enable the next few lines to instrument a test for underrun log handling.
5357 // TODO: Remove when we have a better way of testing the underrun log.
5358#if 0
5359 static int i;
5360 if ((++i & 0xf) == 0) {
5361 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5362 }
5363#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005364 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005365 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005366 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005367 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5368 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005369 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005370 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005371 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005372
Eric Laurent81784c32012-11-19 14:55:58 -08005373 // clear effect chain input buffer if an active track underruns to avoid sending
5374 // previous audio buffer again to effects
5375 chain = getEffectChain_l(track->sessionId());
5376 if (chain != 0) {
5377 chain->clearInputBuffer();
5378 }
5379
Andy Hungc0691382018-09-12 18:01:57 -07005380 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005381 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5382 track->isStopped() || track->isPaused()) {
5383 // We have consumed all the buffers of this track.
5384 // Remove it from the list of active tracks.
5385 // TODO: use actual buffer filling status instead of latency when available from
5386 // audio HAL
5387 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005388 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005389 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5390 if (track->isStopped()) {
5391 track->reset();
5392 }
5393 tracksToRemove->add(track);
5394 }
5395 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005396 // No buffers for this track. Give it a few chances to
5397 // fill a buffer, then remove it from active list.
5398 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005399 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5400 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005401 tracksToRemove->add(track);
5402 // indicate to client process that the track was disabled because of underrun;
5403 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005404 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005405 // If one track is not ready, mark the mixer also not ready if:
5406 // - the mixer was ready during previous round OR
5407 // - no other track is ready
5408 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5409 mixerStatus != MIXER_TRACKS_READY) {
5410 mixerStatus = MIXER_TRACKS_ENABLED;
5411 }
5412 }
Andy Hungc0691382018-09-12 18:01:57 -07005413 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005414 }
5415
5416 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005417
5418 }
5419
jiabin245cdd92018-12-07 17:55:15 -08005420 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5421 // When there is no fast track playing haptic and FastMixer exists,
5422 // enabling the first FastTrack, which provides mixed data from normal
5423 // tracks, to play haptic data.
5424 FastTrack *fastTrack = &state->mFastTracks[0];
5425 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5426 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5427 didModify = true;
5428 }
5429 }
5430
Eric Laurent81784c32012-11-19 14:55:58 -08005431 // Push the new FastMixer state if necessary
5432 bool pauseAudioWatchdog = false;
5433 if (didModify) {
5434 state->mFastTracksGen++;
5435 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5436 if (kUseFastMixer == FastMixer_Dynamic &&
5437 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5438 state->mCommand = FastMixerState::COLD_IDLE;
5439 state->mColdFutexAddr = &mFastMixerFutex;
5440 state->mColdGen++;
5441 mFastMixerFutex = 0;
5442 if (kUseFastMixer == FastMixer_Dynamic) {
5443 mNormalSink = mOutputSink;
5444 }
5445 // If we go into cold idle, need to wait for acknowledgement
5446 // so that fast mixer stops doing I/O.
5447 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5448 pauseAudioWatchdog = true;
5449 }
Eric Laurent81784c32012-11-19 14:55:58 -08005450 }
5451 if (sq != NULL) {
5452 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005453 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5454 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5455 // when bringing the output sink into standby.)
5456 //
5457 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5458 //
5459 // This occurs with BT suspend when we idle the FastMixer with
5460 // active tracks, which may be added or removed.
5461 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005462 }
5463#ifdef AUDIO_WATCHDOG
5464 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5465 mAudioWatchdog->pause();
5466 }
5467#endif
5468
5469 // Now perform the deferred reset on fast tracks that have stopped
5470 while (resetMask != 0) {
5471 size_t i = __builtin_ctz(resetMask);
5472 ALOG_ASSERT(i < count);
5473 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005474 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005475 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5476 track->reset();
5477 }
5478
Andy Hung80d03d22018-04-10 10:32:11 -07005479 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5480 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5481 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5482 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5483 // See also the implementation of destroyTrack_l().
5484 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005485 const int trackId = track->id();
5486 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5487 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005488 }
5489 }
5490
Eric Laurent81784c32012-11-19 14:55:58 -08005491 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005492 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005493
Eric Laurent97d547d2014-09-02 14:45:53 -07005494 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5495 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005496 }
5497
5498 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005499 // as long as there are effects we should clear the effects buffer, to avoid
5500 // passing a non-clean buffer to the effect chain
5501 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005502 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005503 // sink or mix buffer must be cleared if all tracks are connected to an
5504 // effect chain as in this case the mixer will not write to the sink or mix buffer
5505 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005506 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5507 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005508 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005509 if (mMixerBufferValid) {
5510 memset(mMixerBuffer, 0, mMixerBufferSize);
5511 // TODO: In testing, mSinkBuffer below need not be cleared because
5512 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5513 // after mixing.
5514 //
5515 // To enforce this guarantee:
5516 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5517 // (mixedTracks == 0 && fastTracks > 0))
5518 // must imply MIXER_TRACKS_READY.
5519 // Later, we may clear buffers regardless, and skip much of this logic.
5520 }
Andy Hung98ef9782014-03-04 14:46:50 -08005521 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005522 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005523 }
5524
5525 // if any fast tracks, then status is ready
5526 mMixerStatusIgnoringFastTracks = mixerStatus;
5527 if (fastTracks > 0) {
5528 mixerStatus = MIXER_TRACKS_READY;
5529 }
5530 return mixerStatus;
5531}
5532
Eric Laurentad7dd962016-09-22 12:38:37 -07005533// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005534uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005535{
5536 uint32_t trackCount = 0;
5537 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005538 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005539 trackCount++;
5540 }
5541 }
5542 return trackCount;
5543}
5544
Andy Hung1bc088a2018-02-09 15:57:31 -08005545// isTrackAllowed_l() must be called with ThreadBase::mLock held
5546bool AudioFlinger::MixerThread::isTrackAllowed_l(
5547 audio_channel_mask_t channelMask, audio_format_t format,
5548 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005549{
Andy Hung1bc088a2018-02-09 15:57:31 -08005550 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5551 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005552 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005553 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov32f0d162019-07-30 14:42:32 -07005554 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005555 ALOGW("%s: invalid format: %#x", __func__, format);
5556 return false;
5557 }
Mikhail Naganov32f0d162019-07-30 14:42:32 -07005558 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005559 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5560 return false;
5561 }
5562 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005563}
5564
Eric Laurent10351942014-05-08 18:49:52 -07005565// checkForNewParameter_l() must be called with ThreadBase::mLock held
5566bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5567 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005568{
Eric Laurent81784c32012-11-19 14:55:58 -08005569 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005570 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005571
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005572 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005573
Eric Laurent10351942014-05-08 18:49:52 -07005574 AudioParameter param = AudioParameter(keyValuePair);
5575 int value;
5576 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5577 reconfig = true;
5578 }
5579 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005580 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005581 status = BAD_VALUE;
5582 } else {
5583 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005584 reconfig = true;
5585 }
Eric Laurent10351942014-05-08 18:49:52 -07005586 }
5587 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005588 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005589 status = BAD_VALUE;
5590 } else {
5591 // no need to save value, since it's constant
5592 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005593 }
Eric Laurent10351942014-05-08 18:49:52 -07005594 }
5595 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5596 // do not accept frame count changes if tracks are open as the track buffer
5597 // size depends on frame count and correct behavior would not be guaranteed
5598 // if frame count is changed after track creation
5599 if (!mTracks.isEmpty()) {
5600 status = INVALID_OPERATION;
5601 } else {
5602 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005603 }
Eric Laurent10351942014-05-08 18:49:52 -07005604 }
5605 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07005606 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005607 }
Eric Laurent81784c32012-11-19 14:55:58 -08005608
Eric Laurent10351942014-05-08 18:49:52 -07005609 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005610 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005611 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005612 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005613 if (!mStandby) {
5614 mThreadMetrics.logEndInterval();
5615 mStandby = true;
5616 }
Eric Laurent10351942014-05-08 18:49:52 -07005617 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005618 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005619 }
Eric Laurent10351942014-05-08 18:49:52 -07005620 if (status == NO_ERROR && reconfig) {
5621 readOutputParameters_l();
5622 delete mAudioMixer;
5623 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005624 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005625 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005626 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005627 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005628 track->mChannelMask,
5629 track->mFormat,
5630 track->mSessionId);
5631 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005632 "%s(): AudioMixer cannot create track(%d)"
5633 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005634 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005635 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005636 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005637 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005638 }
Eric Laurent81784c32012-11-19 14:55:58 -08005639 }
5640
Dean Wheatley68918102021-03-19 22:09:19 +11005641 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005642}
5643
5644
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005645void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005646{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005647 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005648 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005649 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005650 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005651 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5652 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5653 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005654 if (hasFastMixer()) {
5655 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5656
5657 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5658 // while we are dumping it. It may be inconsistent, but it won't mutate!
5659 // This is a large object so we place it on the heap.
5660 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005661 const std::unique_ptr<FastMixerDumpState> copy =
5662 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005663 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005664
5665#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005666 // Similar for state queue
5667 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5668 observerCopy.dump(fd);
5669 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5670 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005671#endif
5672
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005673#ifdef AUDIO_WATCHDOG
5674 if (mAudioWatchdog != 0) {
5675 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5676 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5677 wdCopy.dump(fd);
5678 }
5679#endif
5680
5681 } else {
5682 dprintf(fd, " No FastMixer\n");
5683 }
Eric Laurent81784c32012-11-19 14:55:58 -08005684}
5685
5686uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5687{
5688 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5689}
5690
5691uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5692{
5693 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5694}
5695
5696void AudioFlinger::MixerThread::cacheParameters_l()
5697{
5698 PlaybackThread::cacheParameters_l();
5699
5700 // FIXME: Relaxed timing because of a certain device that can't meet latency
5701 // Should be reduced to 2x after the vendor fixes the driver issue
5702 // increase threshold again due to low power audio mode. The way this warning
5703 // threshold is calculated and its usefulness should be reconsidered anyway.
5704 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5705}
5706
5707// ----------------------------------------------------------------------------
5708
5709AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabin10d86fd2019-10-31 17:20:42 -07005710 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5711 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005712{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005713 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005714}
5715
Eric Laurent81784c32012-11-19 14:55:58 -08005716AudioFlinger::DirectOutputThread::~DirectOutputThread()
5717{
5718}
5719
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005720void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005721{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005722 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005723 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5724 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5725}
5726
5727void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5728{
5729 Mutex::Autolock _l(mLock);
5730 if (mMasterBalance != balance) {
5731 mMasterBalance.store(balance);
5732 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5733 broadcast_l();
5734 }
5735}
5736
Eric Laurent5850c4c2016-11-10 13:04:31 -08005737void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005738{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005739 float left, right;
5740
Andy Hung333ab962019-05-28 20:23:35 -07005741 // Ensure volumeshaper state always advances even when muted.
5742 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5743 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5744 proxy->framesReleased());
5745 mVolumeShaperActive = shaperActive;
5746
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005747 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005748 left = right = 0;
5749 } else {
5750 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005751 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005752
Glenn Kastenc56f3422014-03-21 17:53:17 -07005753 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5754 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5755 if (left > GAIN_FLOAT_UNITY) {
5756 left = GAIN_FLOAT_UNITY;
5757 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005758 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005759 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5760 if (right > GAIN_FLOAT_UNITY) {
5761 right = GAIN_FLOAT_UNITY;
5762 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005763 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005764 }
5765
5766 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005767 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005768 if (left != mLeftVolFloat || right != mRightVolFloat) {
5769 mLeftVolFloat = left;
5770 mRightVolFloat = right;
5771
Eric Laurentbfb1b832013-01-07 09:53:42 -08005772 // Delegate volume control to effect in track effect chain if needed
5773 // only one effect chain can be present on DirectOutputThread, so if
5774 // there is one, the track is connected to it
5775 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005776 // if effect chain exists, volume is handled by it.
5777 // Convert volumes from float to 8.24
5778 uint32_t vl = (uint32_t)(left * (1 << 24));
5779 uint32_t vr = (uint32_t)(right * (1 << 24));
5780 // Direct/Offload effect chains set output volume in setVolume_l().
5781 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5782 } else {
5783 // otherwise we directly set the volume.
5784 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005785 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005786 }
5787 }
5788}
5789
Phil Burk43b4dcc2015-06-09 16:53:44 -07005790void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5791{
5792 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005793 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005794
Eric Laurent0f0631e2015-07-06 18:01:25 -07005795 if (previousTrack != 0 && latestTrack != 0) {
5796 if (mType == DIRECT) {
5797 if (previousTrack.get() != latestTrack.get()) {
5798 mFlushPending = true;
5799 }
5800 } else /* mType == OFFLOAD */ {
5801 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5802 mFlushPending = true;
5803 }
5804 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005805 } else if (previousTrack == 0) {
5806 // there could be an old track added back during track transition for direct
5807 // output, so always issues flush to flush data of the previous track if it
5808 // was already destroyed with HAL paused, then flush can resume the playback
5809 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005810 }
5811 PlaybackThread::onAddNewTrack_l();
5812}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005813
Eric Laurent81784c32012-11-19 14:55:58 -08005814AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5815 Vector< sp<Track> > *tracksToRemove
5816)
5817{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005818 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005819 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005820 bool doHwPause = false;
5821 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005822
5823 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005824 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005825 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005826 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005827 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005828 continue;
5829 }
5830
Eric Laurent5850c4c2016-11-10 13:04:31 -08005831 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005832#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005833 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005834#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005835 // Only consider last track started for volume and mixer state control.
5836 // In theory an older track could underrun and restart after the new one starts
5837 // but as we only care about the transition phase between two tracks on a
5838 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005839 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005840 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005841
Kuowei Li23666472021-01-20 10:23:25 +08005842 if (track->isPausePending()) {
5843 track->pauseAck();
5844 // It is possible a track might have been flushed or stopped.
5845 // Other operations such as flush pending might occur on the next prepare.
5846 if (track->isPausing()) {
5847 track->setPaused();
5848 }
5849 // Always perform pause, as an immediate flush will change
5850 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005851 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005852 doHwPause = true;
5853 mHwPaused = true;
5854 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005855 } else if (track->isFlushPending()) {
5856 track->flushAck();
5857 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005858 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005859 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005860 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005861 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005862 if (last) {
5863 mLeftVolFloat = mRightVolFloat = -1.0;
5864 if (mHwPaused) {
5865 doHwResume = true;
5866 mHwPaused = false;
5867 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005868 }
5869 }
5870
Eric Laurent81784c32012-11-19 14:55:58 -08005871 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005872 // for all its buffers to be filled before processing it.
5873 // Allow draining the buffer in case the client
5874 // app does not call stop() and relies on underrun to stop:
5875 // hence the test on (track->mRetryCount > 1).
Andy Hung0765c9a2021-04-27 17:46:12 -07005876 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
5877 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
5878 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07005879 // Do not use a high threshold for compressed audio.
Andy Hung0765c9a2021-04-27 17:46:12 -07005880
5881 // target retry count that we will use is based on the time we wait for retries.
5882 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
5883 // the retry threshold is when we accept any size for PCM data. This is slightly
5884 // smaller than the retry count so we can push small bits of data without a glitch.
5885 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08005886 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005887 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung0765c9a2021-04-27 17:46:12 -07005888 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005889 minFrames = mNormalFrameCount;
5890 } else {
5891 minFrames = 1;
5892 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005893
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005894 const size_t framesReady = track->framesReady();
5895 const int trackId = track->id();
5896 if (ATRACE_ENABLED()) {
5897 std::string traceName("nRdy");
5898 traceName += std::to_string(trackId);
5899 ATRACE_INT(traceName.c_str(), framesReady);
5900 }
5901 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005902 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005903 {
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005904 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005905
5906 if (track->mFillingUpStatus == Track::FS_FILLED) {
5907 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005908 if (last) {
5909 // make sure processVolume_l() will apply new volume even if 0
5910 mLeftVolFloat = mRightVolFloat = -1.0;
5911 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005912 if (!mHwSupportsPause) {
5913 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005914 }
5915 }
5916
5917 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005918 processVolume_l(track, last);
5919 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005920 sp<Track> previousTrack = mPreviousTrack.promote();
5921 if (previousTrack != 0) {
5922 if (track != previousTrack.get()) {
5923 // Flush any data still being written from last track
5924 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005925 // Invalidate previous track to force a seek when resuming.
5926 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005927 }
5928 }
5929 mPreviousTrack = track;
5930
Eric Laurentd595b7c2013-04-03 17:27:56 -07005931 // reset retry count
Andy Hung0765c9a2021-04-27 17:46:12 -07005932 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005933 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005934 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005935 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005936 doHwResume = true;
5937 mHwPaused = false;
5938 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005939 }
Eric Laurent81784c32012-11-19 14:55:58 -08005940 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005941 // clear effect chain input buffer if the last active track started underruns
5942 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005943 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005944 mEffectChains[0]->clearInputBuffer();
5945 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005946 if (track->isStopping_1()) {
5947 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005948 if (last && mHwPaused) {
5949 doHwResume = true;
5950 mHwPaused = false;
5951 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005952 }
5953 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5954 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005955 // We have consumed all the buffers of this track.
5956 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005957 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005958 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005959 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5960 } else {
5961 audioHALFrames = 0;
5962 }
5963
Andy Hung818e7a32016-02-16 18:08:07 -08005964 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005965 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005966 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08005967 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005968 if (track->isStopping_2()) {
5969 track->mState = TrackBase::STOPPED;
5970 }
Eric Laurent81784c32012-11-19 14:55:58 -08005971 if (track->isStopped()) {
5972 track->reset();
5973 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005974 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005975 }
5976 } else {
5977 // No buffers for this track. Give it a few chances to
5978 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005979 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005980 if (--(track->mRetryCount) <= 0) {
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005981 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005982 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005983 // indicate to client process that the track was disabled because of underrun;
5984 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005985 track->disable();
Haynes Mathew George82fa4812017-01-24 20:06:05 -08005986 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
5987 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07005988 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5989 "minFrames = %u, mFormat = %#x",
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005990 framesReady, minFrames, mFormat);
Haynes Mathew George82fa4812017-01-24 20:06:05 -08005991 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005992 doHwPause = true;
5993 mHwPaused = true;
5994 }
Haynes Mathew George82fa4812017-01-24 20:06:05 -08005995 } else if (last) {
5996 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08005997 }
5998 }
5999 }
6000 }
6001
Eric Laurentd1f69b02014-12-15 14:33:13 -08006002 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006003 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006004 for (size_t i = 0; i < mTracks.size(); i++) {
6005 if (mTracks[i]->isFlushPending()) {
6006 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006007 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006008 }
6009 }
6010 }
6011
6012 // make sure the pause/flush/resume sequence is executed in the right order.
6013 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6014 // before flush and then resume HW. This can happen in case of pause/flush/resume
6015 // if resume is received before pause is executed.
6016 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006017 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006018 status_t result = mOutput->stream->pause();
6019 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006020 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006021 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006022 flushHw_l();
6023 }
6024 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006025 status_t result = mOutput->stream->resume();
6026 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006027 }
Eric Laurent81784c32012-11-19 14:55:58 -08006028 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006029 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006030
6031 return mixerStatus;
6032}
6033
6034void AudioFlinger::DirectOutputThread::threadLoop_mix()
6035{
Eric Laurent81784c32012-11-19 14:55:58 -08006036 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006037 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006038 // output audio to hardware
6039 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006040 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006041 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006042 status_t status = mActiveTrack->getNextBuffer(&buffer);
6043 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006044 // no need to pad with 0 for compressed audio
6045 if (audio_has_proportional_frames(mFormat)) {
6046 memset(curBuf, 0, frameCount * mFrameSize);
6047 }
Eric Laurent81784c32012-11-19 14:55:58 -08006048 break;
6049 }
6050 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6051 frameCount -= buffer.frameCount;
6052 curBuf += buffer.frameCount * mFrameSize;
6053 mActiveTrack->releaseBuffer(&buffer);
6054 }
Andy Hung2098f272014-02-27 14:00:06 -08006055 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006056 mSleepTimeUs = 0;
6057 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006058 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006059}
6060
6061void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6062{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006063 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006064 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006065 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006066 return;
6067 }
Andy Hung6b605f22021-04-27 17:40:26 -07006068 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6069 mSleepTimeUs = mActiveSleepTimeUs;
6070 } else {
6071 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006072 }
Andy Hung6b605f22021-04-27 17:40:26 -07006073 // Note: In S or later, we do not write zeroes for
6074 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006075}
6076
Eric Laurentd1f69b02014-12-15 14:33:13 -08006077void AudioFlinger::DirectOutputThread::threadLoop_exit()
6078{
6079 {
6080 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006081 for (size_t i = 0; i < mTracks.size(); i++) {
6082 if (mTracks[i]->isFlushPending()) {
6083 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006084 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006085 }
6086 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006087 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006088 flushHw_l();
6089 }
6090 }
6091 PlaybackThread::threadLoop_exit();
6092}
6093
6094// must be called with thread mutex locked
6095bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6096{
6097 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006098 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006099
6100 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6101 // after a timeout and we will enter standby then.
6102 if (mTracks.size() > 0) {
6103 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006104 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6105 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006106 }
6107
Eric Laurent5cff4032015-05-26 13:49:58 -07006108 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006109}
6110
Eric Laurent10351942014-05-08 18:49:52 -07006111// checkForNewParameter_l() must be called with ThreadBase::mLock held
6112bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6113 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006114{
6115 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006116 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006117
Eric Laurent10351942014-05-08 18:49:52 -07006118 AudioParameter param = AudioParameter(keyValuePair);
6119 int value;
6120 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07006121 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006122 }
Eric Laurent10351942014-05-08 18:49:52 -07006123 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6124 // do not accept frame count changes if tracks are open as the track buffer
6125 // size depends on frame count and correct behavior would not be garantied
6126 // if frame count is changed after track creation
6127 if (!mTracks.isEmpty()) {
6128 status = INVALID_OPERATION;
6129 } else {
6130 reconfig = true;
6131 }
6132 }
6133 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006134 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006135 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006136 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006137 if (!mStandby) {
6138 mThreadMetrics.logEndInterval();
6139 mStandby = true;
6140 }
Eric Laurent10351942014-05-08 18:49:52 -07006141 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006142 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006143 }
6144 if (status == NO_ERROR && reconfig) {
6145 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006146 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006147 }
6148 }
6149
Dean Wheatley68918102021-03-19 22:09:19 +11006150 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006151}
6152
6153uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6154{
6155 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006156 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006157 time = PlaybackThread::activeSleepTimeUs();
6158 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006159 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006160 }
6161 return time;
6162}
6163
6164uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6165{
6166 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006167 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006168 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6169 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006170 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006171 }
6172 return time;
6173}
6174
6175uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6176{
6177 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006178 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006179 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6180 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006181 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006182 }
6183 return time;
6184}
6185
6186void AudioFlinger::DirectOutputThread::cacheParameters_l()
6187{
6188 PlaybackThread::cacheParameters_l();
6189
6190 // use shorter standby delay as on normal output to release
6191 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006192 // no delay on outputs with HW A/V sync
6193 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006194 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006195 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006196 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006197 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006198 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006199 }
Eric Laurent81784c32012-11-19 14:55:58 -08006200}
6201
Eric Laurente659ef42014-09-29 13:06:46 -07006202void AudioFlinger::DirectOutputThread::flushHw_l()
6203{
Phil Burk062e67a2015-02-11 13:40:50 -08006204 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006205 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006206 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006207 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006208 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006209}
6210
Andy Hung10cbff12017-02-21 17:30:14 -08006211int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6212 // If a VolumeShaper is active, we must wake up periodically to update volume.
6213 const int64_t NS_PER_MS = 1000000;
6214 return mVolumeShaperActive ?
6215 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6216}
6217
Eric Laurent81784c32012-11-19 14:55:58 -08006218// ----------------------------------------------------------------------------
6219
Eric Laurentbfb1b832013-01-07 09:53:42 -08006220AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006221 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006222 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006223 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006224 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006225 mDrainSequence(0),
6226 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006227{
6228}
6229
6230AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6231{
6232}
6233
6234void AudioFlinger::AsyncCallbackThread::onFirstRef()
6235{
6236 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6237}
6238
6239bool AudioFlinger::AsyncCallbackThread::threadLoop()
6240{
6241 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006242 uint32_t writeAckSequence;
6243 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006244 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006245
6246 {
6247 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006248 while (!((mWriteAckSequence & 1) ||
6249 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006250 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006251 exitPending())) {
6252 mWaitWorkCV.wait(mLock);
6253 }
6254
Eric Laurentbfb1b832013-01-07 09:53:42 -08006255 if (exitPending()) {
6256 break;
6257 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006258 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6259 mWriteAckSequence, mDrainSequence);
6260 writeAckSequence = mWriteAckSequence;
6261 mWriteAckSequence &= ~1;
6262 drainSequence = mDrainSequence;
6263 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006264 asyncError = mAsyncError;
6265 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006266 }
6267 {
Eric Laurent4de95592013-09-26 15:28:21 -07006268 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6269 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006270 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006271 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006272 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006273 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006274 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006275 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006276 if (asyncError) {
6277 playbackThread->onAsyncError();
6278 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006279 }
6280 }
6281 }
6282 return false;
6283}
6284
6285void AudioFlinger::AsyncCallbackThread::exit()
6286{
6287 ALOGV("AsyncCallbackThread::exit");
6288 Mutex::Autolock _l(mLock);
6289 requestExit();
6290 mWaitWorkCV.broadcast();
6291}
6292
Eric Laurent3b4529e2013-09-05 18:09:19 -07006293void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006294{
6295 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006296 // bit 0 is cleared
6297 mWriteAckSequence = sequence << 1;
6298}
6299
6300void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6301{
6302 Mutex::Autolock _l(mLock);
6303 // ignore unexpected callbacks
6304 if (mWriteAckSequence & 2) {
6305 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006306 mWaitWorkCV.signal();
6307 }
6308}
6309
Eric Laurent3b4529e2013-09-05 18:09:19 -07006310void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006311{
6312 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006313 // bit 0 is cleared
6314 mDrainSequence = sequence << 1;
6315}
6316
6317void AudioFlinger::AsyncCallbackThread::resetDraining()
6318{
6319 Mutex::Autolock _l(mLock);
6320 // ignore unexpected callbacks
6321 if (mDrainSequence & 2) {
6322 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006323 mWaitWorkCV.signal();
6324 }
6325}
6326
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006327void AudioFlinger::AsyncCallbackThread::setAsyncError()
6328{
6329 Mutex::Autolock _l(mLock);
6330 mAsyncError = true;
6331 mWaitWorkCV.signal();
6332}
6333
Eric Laurentbfb1b832013-01-07 09:53:42 -08006334
6335// ----------------------------------------------------------------------------
6336AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabin10d86fd2019-10-31 17:20:42 -07006337 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6338 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006339 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6340 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006341{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006342 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006343 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006344 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006345}
6346
Eric Laurentbfb1b832013-01-07 09:53:42 -08006347void AudioFlinger::OffloadThread::threadLoop_exit()
6348{
6349 if (mFlushPending || mHwPaused) {
6350 // If a flush is pending or track was paused, just discard buffered data
6351 flushHw_l();
6352 } else {
6353 mMixerStatus = MIXER_DRAIN_ALL;
6354 threadLoop_drain();
6355 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006356 if (mUseAsyncWrite) {
6357 ALOG_ASSERT(mCallbackThread != 0);
6358 mCallbackThread->exit();
6359 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006360 PlaybackThread::threadLoop_exit();
6361}
6362
6363AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6364 Vector< sp<Track> > *tracksToRemove
6365)
6366{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006367 size_t count = mActiveTracks.size();
6368
6369 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006370 bool doHwPause = false;
6371 bool doHwResume = false;
6372
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006373 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006374
Eric Laurentbfb1b832013-01-07 09:53:42 -08006375 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006376 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006377 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006378#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006379 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006380#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006381 // Only consider last track started for volume and mixer state control.
6382 // In theory an older track could underrun and restart after the new one starts
6383 // but as we only care about the transition phase between two tracks on a
6384 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006385 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006386 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006387
Haynes Mathew George7844f672014-01-15 12:32:55 -08006388 if (track->isInvalid()) {
6389 ALOGW("An invalidated track shouldn't be in active list");
6390 tracksToRemove->add(track);
6391 continue;
6392 }
6393
6394 if (track->mState == TrackBase::IDLE) {
6395 ALOGW("An idle track shouldn't be in active list");
6396 continue;
6397 }
6398
Kuowei Li23666472021-01-20 10:23:25 +08006399 if (track->isPausePending()) {
6400 track->pauseAck();
6401 // It is possible a track might have been flushed or stopped.
6402 // Other operations such as flush pending might occur on the next prepare.
6403 if (track->isPausing()) {
6404 track->setPaused();
6405 }
6406 // Always perform pause if last, as an immediate flush will change
6407 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006408 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006409 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006410 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006411 mHwPaused = true;
6412 }
6413 // If we were part way through writing the mixbuffer to
6414 // the HAL we must save this until we resume
6415 // BUG - this will be wrong if a different track is made active,
6416 // in that case we want to discard the pending data in the
6417 // mixbuffer and tell the client to present it again when the
6418 // track is resumed
6419 mPausedWriteLength = mCurrentWriteLength;
6420 mPausedBytesRemaining = mBytesRemaining;
6421 mBytesRemaining = 0; // stop writing
6422 }
6423 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006424 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006425 if (track->isStopping_1()) {
6426 track->mRetryCount = kMaxTrackStopRetriesOffload;
6427 } else {
6428 track->mRetryCount = kMaxTrackRetriesOffload;
6429 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006430 track->flushAck();
6431 if (last) {
6432 mFlushPending = true;
6433 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006434 } else if (track->isResumePending()){
6435 track->resumeAck();
6436 if (last) {
6437 if (mPausedBytesRemaining) {
6438 // Need to continue write that was interrupted
6439 mCurrentWriteLength = mPausedWriteLength;
6440 mBytesRemaining = mPausedBytesRemaining;
6441 mPausedBytesRemaining = 0;
6442 }
6443 if (mHwPaused) {
6444 doHwResume = true;
6445 mHwPaused = false;
6446 // threadLoop_mix() will handle the case that we need to
6447 // resume an interrupted write
6448 }
6449 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006450 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006451
Eric Laurent3df841a2016-07-15 15:15:40 -07006452 mLeftVolFloat = mRightVolFloat = -1.0;
6453
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006454 // Do not handle new data in this iteration even if track->framesReady()
6455 mixerStatus = MIXER_TRACKS_ENABLED;
6456 }
6457 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006458 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006459 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006460 if (track->mFillingUpStatus == Track::FS_FILLED) {
6461 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006462 if (last) {
6463 // make sure processVolume_l() will apply new volume even if 0
6464 mLeftVolFloat = mRightVolFloat = -1.0;
6465 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006466 }
6467
6468 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006469 sp<Track> previousTrack = mPreviousTrack.promote();
6470 if (previousTrack != 0) {
6471 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006472 // Flush any data still being written from last track
6473 mBytesRemaining = 0;
6474 if (mPausedBytesRemaining) {
6475 // Last track was paused so we also need to flush saved
6476 // mixbuffer state and invalidate track so that it will
6477 // re-submit that unwritten data when it is next resumed
6478 mPausedBytesRemaining = 0;
6479 // Invalidate is a bit drastic - would be more efficient
6480 // to have a flag to tell client that some of the
6481 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006482 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006483 }
6484 // flush data already sent to the DSP if changing audio session as audio
6485 // comes from a different source. Also invalidate previous track to force a
6486 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006487 if (previousTrack->sessionId() != track->sessionId()) {
6488 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006489 }
6490 }
6491 }
6492 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006493 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006494 if (track->isStopping_1()) {
6495 track->mRetryCount = kMaxTrackStopRetriesOffload;
6496 } else {
6497 track->mRetryCount = kMaxTrackRetriesOffload;
6498 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006499 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006500 mixerStatus = MIXER_TRACKS_READY;
6501 }
6502 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006503 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006504 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006505 if (--(track->mRetryCount) <= 0) {
6506 // Hardware buffer can hold a large amount of audio so we must
6507 // wait for all current track's data to drain before we say
6508 // that the track is stopped.
6509 if (mBytesRemaining == 0) {
6510 // Only start draining when all data in mixbuffer
6511 // has been written
6512 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6513 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6514 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6515 if (last && !mStandby) {
6516 // do not modify drain sequence if we are already draining. This happens
6517 // when resuming from pause after drain.
6518 if ((mDrainSequence & 1) == 0) {
6519 mSleepTimeUs = 0;
6520 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6521 mixerStatus = MIXER_DRAIN_TRACK;
6522 mDrainSequence += 2;
6523 }
6524 if (mHwPaused) {
6525 // It is possible to move from PAUSED to STOPPING_1 without
6526 // a resume so we must ensure hardware is running
6527 doHwResume = true;
6528 mHwPaused = false;
6529 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006530 }
6531 }
Eric Laurente93cc032016-05-05 10:15:10 -07006532 } else if (last) {
6533 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6534 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006535 }
6536 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006537 // Drain has completed or we are in standby, signal presentation complete
6538 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006539 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006540 uint32_t latency = 0;
6541 status_t result = mOutput->stream->getLatency(&latency);
6542 ALOGE_IF(result != OK,
6543 "Error when retrieving output stream latency: %d", result);
6544 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006545 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006546 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006547 track->presentationComplete(framesWritten, audioHALFrames);
6548 track->reset();
6549 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006550 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006551 if (!mUseAsyncWrite) {
6552 // If we don't get explicit drain notification we must
6553 // register discontinuity regardless of whether this is
6554 // the previous (!last) or the upcoming (last) track
6555 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006556 mTimestampVerifier.discontinuity(
6557 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006558 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006559 }
6560 } else {
6561 // No buffers for this track. Give it a few chances to
6562 // fill a buffer, then remove it from active list.
6563 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006564 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006565 uint64_t position = 0;
6566 struct timespec unused;
6567 // The running check restarts the retry counter at least once.
6568 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6569 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6570 running = true;
6571 mOffloadUnderrunPosition = position;
6572 }
6573 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006574 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6575 (long long)position, (long long)mOffloadUnderrunPosition);
6576 }
6577 if (running) { // still running, give us more time.
6578 track->mRetryCount = kMaxTrackRetriesOffload;
6579 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006580 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6581 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006582 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006583 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006584 // it will then automatically call start() when data is available
6585 track->disable();
6586 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006587 } else if (last){
6588 mixerStatus = MIXER_TRACKS_ENABLED;
6589 }
6590 }
6591 }
6592 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006593 if (track->isReady()) { // check ready to prevent premature start.
6594 processVolume_l(track, last);
6595 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006596 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006597
Eric Laurentea0fade2013-10-04 16:23:48 -07006598 // make sure the pause/flush/resume sequence is executed in the right order.
6599 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6600 // before flush and then resume HW. This can happen in case of pause/flush/resume
6601 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006602 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006603 status_t result = mOutput->stream->pause();
6604 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006605 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006606 if (mFlushPending) {
6607 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006608 }
Eric Laurentfd477972013-10-25 18:10:40 -07006609 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006610 status_t result = mOutput->stream->resume();
6611 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006612 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006613
Eric Laurentbfb1b832013-01-07 09:53:42 -08006614 // remove all the tracks that need to be...
6615 removeTracks_l(*tracksToRemove);
6616
6617 return mixerStatus;
6618}
6619
Eric Laurentbfb1b832013-01-07 09:53:42 -08006620// must be called with thread mutex locked
6621bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6622{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006623 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6624 mWriteAckSequence, mDrainSequence);
6625 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006626 return true;
6627 }
6628 return false;
6629}
6630
Eric Laurentbfb1b832013-01-07 09:53:42 -08006631bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6632{
6633 Mutex::Autolock _l(mLock);
6634 return waitingAsyncCallback_l();
6635}
6636
6637void AudioFlinger::OffloadThread::flushHw_l()
6638{
Eric Laurente659ef42014-09-29 13:06:46 -07006639 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006640 // Flush anything still waiting in the mixbuffer
6641 mCurrentWriteLength = 0;
6642 mBytesRemaining = 0;
6643 mPausedWriteLength = 0;
6644 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006645 // reset bytes written count to reflect that DSP buffers are empty after flush.
6646 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006647 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006648
Eric Laurentbfb1b832013-01-07 09:53:42 -08006649 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006650 // discard any pending drain or write ack by incrementing sequence
6651 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6652 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006653 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006654 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6655 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006656 }
6657}
6658
Haynes Mathew George05317d22016-05-03 16:34:26 -07006659void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6660{
6661 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006662 if (PlaybackThread::invalidateTracks_l(streamType)) {
6663 mFlushPending = true;
6664 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006665}
6666
Eric Laurentbfb1b832013-01-07 09:53:42 -08006667// ----------------------------------------------------------------------------
6668
Eric Laurent81784c32012-11-19 14:55:58 -08006669AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006670 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabin10d86fd2019-10-31 17:20:42 -07006671 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006672 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006673 mWaitTimeMs(UINT_MAX)
6674{
6675 addOutputTrack(mainThread);
6676}
6677
6678AudioFlinger::DuplicatingThread::~DuplicatingThread()
6679{
6680 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6681 mOutputTracks[i]->destroy();
6682 }
6683}
6684
6685void AudioFlinger::DuplicatingThread::threadLoop_mix()
6686{
6687 // mix buffers...
6688 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006689 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006690 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006691 if (mMixerBufferValid) {
6692 memset(mMixerBuffer, 0, mMixerBufferSize);
6693 } else {
6694 memset(mSinkBuffer, 0, mSinkBufferSize);
6695 }
Eric Laurent81784c32012-11-19 14:55:58 -08006696 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006697 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006698 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006699 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006700 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006701}
6702
6703void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6704{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006705 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006706 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006707 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006708 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006709 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006710 }
6711 } else if (mBytesWritten != 0) {
6712 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6713 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006714 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006715 } else {
6716 // flush remaining overflow buffers in output tracks
6717 writeFrames = 0;
6718 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006719 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006720 }
6721}
6722
Eric Laurentbfb1b832013-01-07 09:53:42 -08006723ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006724{
6725 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006726 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6727
6728 // Consider the first OutputTrack for timestamp and frame counting.
6729
6730 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6731 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6732 // we always claim success.
6733 if (i == 0) {
6734 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6735 ALOGD_IF(correction != 0 && writeFrames != 0,
6736 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6737 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6738 mFramesWritten -= correction;
6739 }
6740
6741 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006742 }
Andy Hungcf10d742020-04-28 15:38:24 -07006743 if (mStandby) {
6744 mThreadMetrics.logBeginInterval();
6745 mStandby = false;
6746 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006747 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006748}
6749
6750void AudioFlinger::DuplicatingThread::threadLoop_standby()
6751{
6752 // DuplicatingThread implements standby by stopping all tracks
6753 for (size_t i = 0; i < outputTracks.size(); i++) {
6754 outputTracks[i]->stop();
6755 }
6756}
6757
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006758void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006759{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006760 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006761
6762 std::stringstream ss;
6763 const size_t numTracks = mOutputTracks.size();
6764 ss << " " << numTracks << " OutputTracks";
6765 if (numTracks > 0) {
6766 ss << ":";
6767 for (const auto &track : mOutputTracks) {
6768 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006769 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006770 if (thread.get() != nullptr) {
6771 ss << thread.get() << ", " << thread->id();
6772 } else {
6773 ss << "null";
6774 }
6775 ss << ")";
6776 }
6777 }
6778 ss << "\n";
6779 std::string result = ss.str();
6780 write(fd, result.c_str(), result.size());
6781}
6782
Eric Laurent81784c32012-11-19 14:55:58 -08006783void AudioFlinger::DuplicatingThread::saveOutputTracks()
6784{
6785 outputTracks = mOutputTracks;
6786}
6787
6788void AudioFlinger::DuplicatingThread::clearOutputTracks()
6789{
6790 outputTracks.clear();
6791}
6792
6793void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6794{
6795 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006796 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6797 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6798 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6799 const size_t frameCount =
6800 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6801 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6802 // from different OutputTracks and their associated MixerThreads (e.g. one may
6803 // nearly empty and the other may be dropping data).
6804
6805 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006806 this,
6807 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006808 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006809 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006810 frameCount,
6811 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006812 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6813 if (status != NO_ERROR) {
6814 ALOGE("addOutputTrack() initCheck failed %d", status);
6815 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006816 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006817 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6818 mOutputTracks.add(outputTrack);
6819 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6820 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006821}
6822
6823void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6824{
6825 Mutex::Autolock _l(mLock);
6826 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6827 if (mOutputTracks[i]->thread() == thread) {
6828 mOutputTracks[i]->destroy();
6829 mOutputTracks.removeAt(i);
6830 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006831 if (thread->getOutput() == mOutput) {
6832 mOutput = NULL;
6833 }
Eric Laurent81784c32012-11-19 14:55:58 -08006834 return;
6835 }
6836 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006837 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006838}
6839
6840// caller must hold mLock
6841void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6842{
6843 mWaitTimeMs = UINT_MAX;
6844 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6845 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6846 if (strong != 0) {
6847 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6848 if (waitTimeMs < mWaitTimeMs) {
6849 mWaitTimeMs = waitTimeMs;
6850 }
6851 }
6852 }
6853}
6854
6855
6856bool AudioFlinger::DuplicatingThread::outputsReady(
6857 const SortedVector< sp<OutputTrack> > &outputTracks)
6858{
6859 for (size_t i = 0; i < outputTracks.size(); i++) {
6860 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6861 if (thread == 0) {
6862 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6863 outputTracks[i].get());
6864 return false;
6865 }
6866 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6867 // see note at standby() declaration
6868 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6869 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6870 thread.get());
6871 return false;
6872 }
6873 }
6874 return true;
6875}
6876
Kevin Rocard12381092018-04-11 09:19:59 -07006877void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6878 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006879{
Kevin Rocard12381092018-04-11 09:19:59 -07006880 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6881 outputTrack->setMetadatas(metadata.tracks);
6882 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006883}
6884
Eric Laurent81784c32012-11-19 14:55:58 -08006885uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6886{
6887 return (mWaitTimeMs * 1000) / 2;
6888}
6889
6890void AudioFlinger::DuplicatingThread::cacheParameters_l()
6891{
6892 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6893 updateWaitTime_l();
6894
6895 MixerThread::cacheParameters_l();
6896}
6897
Eric Laurent6acd1d42017-01-04 14:23:29 -08006898
Eric Laurent81784c32012-11-19 14:55:58 -08006899// ----------------------------------------------------------------------------
6900// Record
6901// ----------------------------------------------------------------------------
6902
6903AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6904 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006905 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006906 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006907 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006908 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006909 mInput(input),
Mikhail Naganovaf288872019-09-25 13:05:02 -07006910 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006911 mActiveTracks(&this->mLocalLog),
6912 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006913 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006914 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006915 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6916 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006917 // mFastCapture below
6918 , mFastCaptureFutex(0)
6919 // mInputSource
6920 // mPipeSink
6921 // mPipeSource
6922 , mPipeFramesP2(0)
6923 // mPipeMemory
6924 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006925 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006926 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006927{
Glenn Kastend7dca052015-03-05 16:05:54 -08006928 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6929 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006930
George Burgess IVa8f90c12020-05-14 11:27:19 -07006931 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07006932 mIsMsdDevice = strcmp(
6933 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6934 }
6935
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006936 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006937
Andy Hungc8fddf32018-08-08 18:32:37 -07006938 // TODO: We may also match on address as well as device type for
6939 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabin10d86fd2019-10-31 17:20:42 -07006940 // TODO: This property should be ensure that only contains one single device type.
6941 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6942 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006943 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6944 : AUDIO_DEVICE_NONE));
6945
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006946 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006947 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006948 size_t numCounterOffers = 0;
6949 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006950#if !LOG_NDEBUG
6951 ssize_t index =
6952#else
6953 (void)
6954#endif
6955 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006956 ALOG_ASSERT(index == 0);
6957
6958 // initialize fast capture depending on configuration
6959 bool initFastCapture;
6960 switch (kUseFastCapture) {
6961 case FastCapture_Never:
6962 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006963 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006964 break;
6965 case FastCapture_Always:
6966 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006967 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006968 break;
6969 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006970 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006971 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6972 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6973 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006974 break;
6975 // case FastCapture_Dynamic:
6976 }
6977
6978 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006979 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006980 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006981 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6982 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006983 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006984 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006985 const sp<MemoryDealer> roHeap(readOnlyHeap());
6986 sp<IMemory> pipeMemory;
6987 if ((roHeap == 0) ||
6988 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07006989 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006990 ALOGE("not enough memory for pipe buffer size=%zu; "
6991 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6992 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6993 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006994 goto failed;
6995 }
6996 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6997 memset(pipeBuffer, 0, pipeSize);
6998 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6999 const NBAIO_Format offers[1] = {format};
7000 size_t numCounterOffers = 0;
7001 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7002 ALOG_ASSERT(index == 0);
7003 mPipeSink = pipe;
7004 PipeReader *pipeReader = new PipeReader(*pipe);
7005 numCounterOffers = 0;
7006 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7007 ALOG_ASSERT(index == 0);
7008 mPipeSource = pipeReader;
7009 mPipeFramesP2 = pipeFramesP2;
7010 mPipeMemory = pipeMemory;
7011
7012 // create fast capture
7013 mFastCapture = new FastCapture();
7014 FastCaptureStateQueue *sq = mFastCapture->sq();
7015#ifdef STATE_QUEUE_DUMP
7016 // FIXME
7017#endif
7018 FastCaptureState *state = sq->begin();
7019 state->mCblk = NULL;
7020 state->mInputSource = mInputSource.get();
7021 state->mInputSourceGen++;
7022 state->mPipeSink = pipe;
7023 state->mPipeSinkGen++;
7024 state->mFrameCount = mFrameCount;
7025 state->mCommand = FastCaptureState::COLD_IDLE;
7026 // already done in constructor initialization list
7027 //mFastCaptureFutex = 0;
7028 state->mColdFutexAddr = &mFastCaptureFutex;
7029 state->mColdGen++;
7030 state->mDumpState = &mFastCaptureDumpState;
7031#ifdef TEE_SINK
7032 // FIXME
7033#endif
7034 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7035 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7036 sq->end();
7037 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7038
7039 // start the fast capture
7040 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7041 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007042 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007043 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007044#ifdef AUDIO_WATCHDOG
7045 // FIXME
7046#endif
7047
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007048 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007049 }
Andy Hung8946a282018-04-19 20:04:56 -07007050#ifdef TEE_SINK
7051 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7052 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7053#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007054failed: ;
7055
7056 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007057}
7058
Eric Laurent81784c32012-11-19 14:55:58 -08007059AudioFlinger::RecordThread::~RecordThread()
7060{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007061 if (mFastCapture != 0) {
7062 FastCaptureStateQueue *sq = mFastCapture->sq();
7063 FastCaptureState *state = sq->begin();
7064 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7065 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7066 if (old == -1) {
7067 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7068 }
7069 }
7070 state->mCommand = FastCaptureState::EXIT;
7071 sq->end();
7072 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7073 mFastCapture->join();
7074 mFastCapture.clear();
7075 }
7076 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007077 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007078 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007079}
7080
7081void AudioFlinger::RecordThread::onFirstRef()
7082{
Glenn Kastend7dca052015-03-05 16:05:54 -08007083 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007084}
7085
Eric Laurent555530a2017-02-07 18:17:24 -08007086void AudioFlinger::RecordThread::preExit()
7087{
7088 ALOGV(" preExit()");
7089 Mutex::Autolock _l(mLock);
7090 for (size_t i = 0; i < mTracks.size(); i++) {
7091 sp<RecordTrack> track = mTracks[i];
7092 track->invalidate();
7093 }
7094 mActiveTracks.clear();
7095 mStartStopCond.broadcast();
7096}
7097
Eric Laurent81784c32012-11-19 14:55:58 -08007098bool AudioFlinger::RecordThread::threadLoop()
7099{
Eric Laurent81784c32012-11-19 14:55:58 -08007100 nsecs_t lastWarning = 0;
7101
7102 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007103
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007104reacquire_wakelock:
7105 sp<RecordTrack> activeTrack;
7106 {
7107 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007108 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007109 }
7110
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007111 // used to request a deferred sleep, to be executed later while mutex is unlocked
7112 uint32_t sleepUs = 0;
7113
Andy Hung446f4df2019-02-21 12:26:41 -08007114 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7115
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007116 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007117 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007118 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007119
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007120 // activeTracks accumulates a copy of a subset of mActiveTracks
7121 Vector< sp<RecordTrack> > activeTracks;
7122
Glenn Kasten735f45f2014-08-18 15:51:59 -07007123 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007124 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007125
Glenn Kasten735f45f2014-08-18 15:51:59 -07007126 // reference to a fast track which is about to be removed
7127 sp<RecordTrack> fastTrackToRemove;
7128
Eric Laurent33403f02020-05-29 18:35:06 -07007129 bool silenceFastCapture = false;
7130
Eric Laurent81784c32012-11-19 14:55:58 -08007131 { // scope for mLock
7132 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007133
Eric Laurent021cf962014-05-13 10:18:14 -07007134 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007135
Eric Laurent000a4192014-01-29 15:17:32 -08007136 // check exitPending here because checkForNewParameters_l() and
7137 // checkForNewParameters_l() can temporarily release mLock
7138 if (exitPending()) {
7139 break;
7140 }
7141
Eric Laurent5c25d562016-07-13 17:17:45 -07007142 // sleep with mutex unlocked
7143 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007144 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007145 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7146 ATRACE_END();
7147 sleepUs = 0;
7148 continue;
7149 }
7150
Glenn Kasten2b806402013-11-20 16:37:38 -08007151 // if no active track(s), then standby and release wakelock
7152 size_t size = mActiveTracks.size();
7153 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007154 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007155 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007156 releaseWakeLock_l();
7157 ALOGV("RecordThread: loop stopping");
7158 // go to sleep
7159 mWaitWorkCV.wait(mLock);
7160 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007161 goto reacquire_wakelock;
7162 }
7163
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007164 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007165 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007166 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007167
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007168 activeTrack = mActiveTracks[i];
7169 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007170 if (activeTrack->isFastTrack()) {
7171 ALOG_ASSERT(fastTrackToRemove == 0);
7172 fastTrackToRemove = activeTrack;
7173 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007174 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007175 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007176 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007177 continue;
7178 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007179
7180 TrackBase::track_state activeTrackState = activeTrack->mState;
7181 switch (activeTrackState) {
7182
7183 case TrackBase::PAUSING:
7184 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007185 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007186 doBroadcast = true;
7187 size--;
7188 continue;
7189
7190 case TrackBase::STARTING_1:
7191 sleepUs = 10000;
7192 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007193 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007194 continue;
7195
7196 case TrackBase::STARTING_2:
7197 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007198 if (mStandby) {
7199 mThreadMetrics.logBeginInterval();
7200 mStandby = false;
7201 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007202 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007203 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007204 break;
7205
7206 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007207 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007208 break;
7209
Andy Hungce685402018-10-05 17:23:27 -07007210 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7211 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7212 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007213 default:
Andy Hungce685402018-10-05 17:23:27 -07007214 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7215 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007216 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007217
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007218 if (activeTrack->isFastTrack()) {
7219 ALOG_ASSERT(!mFastTrackAvail);
7220 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007221 // if the active fast track is silenced either:
7222 // 1) silence the whole capture from fast capture buffer if this is
7223 // the only active track
7224 // 2) invalidate this track: this will cause the client to reconnect and possibly
7225 // be invalidated again until unsilenced
7226 if (activeTrack->isSilenced()) {
7227 if (size > 1) {
7228 activeTrack->invalidate();
7229 ALOG_ASSERT(fastTrackToRemove == 0);
7230 fastTrackToRemove = activeTrack;
7231 removeTrack_l(activeTrack);
7232 mActiveTracks.remove(activeTrack);
7233 size--;
7234 continue;
7235 } else {
7236 silenceFastCapture = true;
7237 }
7238 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007239 fastTrack = activeTrack;
7240 }
Eric Laurent33403f02020-05-29 18:35:06 -07007241
7242 activeTracks.add(activeTrack);
7243 i++;
7244
Glenn Kasten9e982352013-08-14 14:39:50 -07007245 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007246
Andy Hungdae27702016-10-31 14:01:16 -07007247 mActiveTracks.updatePowerState(this);
7248
Kevin Rocard069c2712018-03-29 19:09:14 -07007249 updateMetadata_l();
7250
Eric Laurent5c25d562016-07-13 17:17:45 -07007251 if (allStopped) {
7252 standbyIfNotAlreadyInStandby();
7253 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007254 if (doBroadcast) {
7255 mStartStopCond.broadcast();
7256 }
7257
7258 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007259 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007260 if (sleepUs == 0) {
7261 sleepUs = kRecordThreadSleepUs;
7262 }
7263 continue;
7264 }
7265 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007266
Eric Laurent81784c32012-11-19 14:55:58 -08007267 lockEffectChains_l(effectChains);
7268 }
7269
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007270 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007271
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007272 size_t size = effectChains.size();
7273 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007274 // thread mutex is not locked, but effect chain is locked
7275 effectChains[i]->process_l();
7276 }
7277
Glenn Kasten735f45f2014-08-18 15:51:59 -07007278 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007279 if (mFastCapture != 0) {
7280 FastCaptureStateQueue *sq = mFastCapture->sq();
7281 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007282 bool didModify = false;
7283 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007284 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7285 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7286 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7287 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7288 if (old == -1) {
7289 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7290 }
7291 }
7292 state->mCommand = FastCaptureState::READ_WRITE;
7293#if 0 // FIXME
7294 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007295 FastThreadDumpState::kSamplingNforLowRamDevice :
7296 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007297#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007298 didModify = true;
7299 }
7300 audio_track_cblk_t *cblkOld = state->mCblk;
7301 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7302 if (cblkNew != cblkOld) {
7303 state->mCblk = cblkNew;
7304 // block until acked if removing a fast track
7305 if (cblkOld != NULL) {
7306 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7307 }
7308 didModify = true;
7309 }
jiabin01c8f562018-07-19 17:47:28 -07007310 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7311 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7312 if (state->mFastPatchRecordBufferProvider != abp) {
7313 state->mFastPatchRecordBufferProvider = abp;
7314 state->mFastPatchRecordFormat = fastTrack == 0 ?
7315 AUDIO_FORMAT_INVALID : fastTrack->format();
7316 didModify = true;
7317 }
Eric Laurent33403f02020-05-29 18:35:06 -07007318 if (state->mSilenceCapture != silenceFastCapture) {
7319 state->mSilenceCapture = silenceFastCapture;
7320 didModify = true;
7321 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007322 sq->end(didModify);
7323 if (didModify) {
7324 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007325#if 0
7326 if (kUseFastCapture == FastCapture_Dynamic) {
7327 mNormalSource = mPipeSource;
7328 }
7329#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007330 }
7331 }
7332
Glenn Kasten735f45f2014-08-18 15:51:59 -07007333 // now run the fast track destructor with thread mutex unlocked
7334 fastTrackToRemove.clear();
7335
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007336 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7337 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7338 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7339 // If destination is non-contiguous, first read past the nominal end of buffer, then
7340 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007341
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007342 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007343 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007344 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007345
7346 // If an NBAIO source is present, use it to read the normal capture's data
7347 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007348 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007349
7350 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7351 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7352 // we immediately retry the read() to get data and prevent another overflow.
7353 for (int retries = 0; retries <= 2; ++retries) {
7354 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7355 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7356 framesToRead);
7357 if (framesRead != OVERRUN) break;
7358 }
7359
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007360 const ssize_t availableToRead = mPipeSource->availableToRead();
7361 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007362 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007363 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7364 "more frames to read than fifo size, %zd > %zu",
7365 availableToRead, mPipeFramesP2);
7366 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7367 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7368 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7369 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007370 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7371 }
7372 if (framesRead < 0) {
7373 status_t status = (status_t) framesRead;
7374 switch (status) {
7375 case OVERRUN:
7376 ALOGW("overrun on read from pipe");
7377 framesRead = 0;
7378 break;
7379 case NEGOTIATE:
7380 ALOGE("re-negotiation is needed");
7381 framesRead = -1; // Will cause an attempt to recover.
7382 break;
7383 default:
7384 ALOGE("unknown error %d on read from pipe", status);
7385 break;
7386 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007387 }
7388 // otherwise use the HAL / AudioStreamIn directly
7389 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007390 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007391 size_t bytesRead;
Mikhail Naganovaf288872019-09-25 13:05:02 -07007392 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007393 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007394 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007395 if (result < 0) {
7396 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007397 } else {
7398 framesRead = bytesRead / mFrameSize;
7399 }
7400 }
7401
Andy Hung446f4df2019-02-21 12:26:41 -08007402 const int64_t lastIoEndNs = systemTime(); // end IO timing
7403
Andy Hung3f0c9022016-01-15 17:49:46 -08007404 // Update server timestamp with server stats
7405 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007406 if (framesRead >= 0) {
7407 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7408 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7409 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007410
7411 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007412 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007413 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007414 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007415 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7416 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7417 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganovaf288872019-09-25 13:05:02 -07007418 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007419 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7420
7421 mTimestampVerifier.add(position, time, mSampleRate);
7422
7423 // Correct timestamps
7424 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007425 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007426 id(), (long long)time, (long long)position);
7427 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7428 position = correctedTimestamp.mFrames;
7429 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007430 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007431 id(), (long long)time, (long long)position);
7432 }
7433
Andy Hung3f0c9022016-01-15 17:49:46 -08007434 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7435 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7436 // Note: In general record buffers should tend to be empty in
7437 // a properly running pipeline.
7438 //
7439 // Also, it is not advantageous to call get_presentation_position during the read
7440 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007441 } else {
7442 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007443 }
7444 }
Andy Hunge6c37112019-02-26 17:38:10 -08007445
7446 // From the timestamp, input read latency is negative output write latency.
7447 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7448 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7449 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7450 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7451 mLatencyMs.add(latencyMs);
7452 }
7453
Andy Hung3f0c9022016-01-15 17:49:46 -08007454 // Use this to track timestamp information
7455 // ALOGD("%s", mTimestamp.toString().c_str());
7456
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007457 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007458 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007459 // Force input into standby so that it tries to recover at next read attempt
7460 inputStandBy();
7461 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007462 }
7463 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007464 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007465 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007466 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007467 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007468
Andy Hung8946a282018-04-19 20:04:56 -07007469#ifdef TEE_SINK
7470 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7471#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007472 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007473 {
7474 size_t part1 = mRsmpInFramesP2 - rear;
7475 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007476 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007477 (framesRead - part1) * mFrameSize);
7478 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007479 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007480 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007481
7482 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007483
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007484 // loop over each active track
7485 for (size_t i = 0; i < size; i++) {
7486 activeTrack = activeTracks[i];
7487
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007488 // skip fast tracks, as those are handled directly by FastCapture
7489 if (activeTrack->isFastTrack()) {
7490 continue;
7491 }
7492
Andy Hung73c02e42015-03-29 01:13:58 -07007493 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007494 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7495
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007496 enum {
7497 OVERRUN_UNKNOWN,
7498 OVERRUN_TRUE,
7499 OVERRUN_FALSE
7500 } overrun = OVERRUN_UNKNOWN;
7501
7502 // loop over getNextBuffer to handle circular sink
7503 for (;;) {
7504
7505 activeTrack->mSink.frameCount = ~0;
7506 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7507 size_t framesOut = activeTrack->mSink.frameCount;
7508 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7509
Andy Hung73c02e42015-03-29 01:13:58 -07007510 // check available frames and handle overrun conditions
7511 // if the record track isn't draining fast enough.
7512 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007513 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007514 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7515 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007516 overrun = OVERRUN_TRUE;
7517 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007518 if (framesOut == 0 || framesIn == 0) {
7519 break;
7520 }
7521
Andy Hung6770c6f2015-04-07 13:43:36 -07007522 // Don't allow framesOut to be larger than what is possible with resampling
7523 // from framesIn.
7524 // This isn't strictly necessary but helps limit buffer resizing in
7525 // RecordBufferConverter. TODO: remove when no longer needed.
7526 framesOut = min(framesOut,
7527 destinationFramesPossible(
7528 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007529
7530 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007531 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007532 // straight from RecordThread buffer to RecordTrack buffer.
7533 AudioBufferProvider::Buffer buffer;
7534 buffer.frameCount = framesOut;
7535 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7536 if (status == OK && buffer.frameCount != 0) {
7537 ALOGV_IF(buffer.frameCount != framesOut,
7538 "%s() read less than expected (%zu vs %zu)",
7539 __func__, buffer.frameCount, framesOut);
7540 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007541 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007542 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7543 } else {
7544 framesOut = 0;
7545 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7546 __func__, status, buffer.frameCount);
7547 }
7548 } else {
7549 // process frames from the RecordThread buffer provider to the RecordTrack
7550 // buffer
7551 framesOut = activeTrack->mRecordBufferConverter->convert(
7552 activeTrack->mSink.raw,
7553 activeTrack->mResamplerBufferProvider,
7554 framesOut);
7555 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007556
7557 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7558 overrun = OVERRUN_FALSE;
7559 }
7560
7561 if (activeTrack->mFramesToDrop == 0) {
7562 if (framesOut > 0) {
7563 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007564 // Sanitize before releasing if the track has no access to the source data
7565 // An idle UID receives silence from non virtual devices until active
7566 if (activeTrack->isSilenced()) {
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007567 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007568 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007569 activeTrack->releaseBuffer(&activeTrack->mSink);
7570 }
7571 } else {
7572 // FIXME could do a partial drop of framesOut
7573 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007574 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007575 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007576 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007577 }
7578 } else {
7579 activeTrack->mFramesToDrop += framesOut;
7580 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7581 activeTrack->mSyncStartEvent->isCancelled()) {
7582 ALOGW("Synced record %s, session %d, trigger session %d",
7583 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7584 activeTrack->sessionId(),
7585 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007586 activeTrack->mSyncStartEvent->triggerSession() :
7587 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007588 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007589 }
7590 }
7591 }
7592
7593 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007594 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007595 }
7596 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007597
7598 switch (overrun) {
7599 case OVERRUN_TRUE:
7600 // client isn't retrieving buffers fast enough
7601 if (!activeTrack->setOverflow()) {
7602 nsecs_t now = systemTime();
7603 // FIXME should lastWarning per track?
7604 if ((now - lastWarning) > kWarningThrottleNs) {
7605 ALOGW("RecordThread: buffer overflow");
7606 lastWarning = now;
7607 }
7608 }
7609 break;
7610 case OVERRUN_FALSE:
7611 activeTrack->clearOverflow();
7612 break;
7613 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007614 break;
7615 }
7616
Andy Hung3f0c9022016-01-15 17:49:46 -08007617 // update frame information and push timestamp out
7618 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007619 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007620 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7621 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007622 }
7623
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007624unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007625 // enable changes in effect chain
7626 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007627 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007628 if (audio_has_proportional_frames(mFormat)
7629 && loopCount == lastLoopCountRead + 1) {
7630 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7631 const double jitterMs =
7632 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7633 {framesRead, readPeriodNs},
7634 {0, 0} /* lastTimestamp */, mSampleRate);
7635 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7636
7637 Mutex::Autolock _l(mLock);
7638 mIoJitterMs.add(jitterMs);
7639 mProcessTimeMs.add(processMs);
7640 }
7641 // update timing info.
7642 mLastIoBeginNs = lastIoBeginNs;
7643 mLastIoEndNs = lastIoEndNs;
7644 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007645 }
7646
Glenn Kasten93e471f2013-08-19 08:40:07 -07007647 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007648
7649 {
7650 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007651 for (size_t i = 0; i < mTracks.size(); i++) {
7652 sp<RecordTrack> track = mTracks[i];
7653 track->invalidate();
7654 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007655 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007656 mStartStopCond.broadcast();
7657 }
7658
7659 releaseWakeLock();
7660
7661 ALOGV("RecordThread %p exiting", this);
7662 return false;
7663}
7664
Glenn Kasten93e471f2013-08-19 08:40:07 -07007665void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007666{
7667 if (!mStandby) {
7668 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007669 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007670 mStandby = true;
7671 }
7672}
7673
7674void AudioFlinger::RecordThread::inputStandBy()
7675{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007676 // Idle the fast capture if it's currently running
7677 if (mFastCapture != 0) {
7678 FastCaptureStateQueue *sq = mFastCapture->sq();
7679 FastCaptureState *state = sq->begin();
7680 if (!(state->mCommand & FastCaptureState::IDLE)) {
7681 state->mCommand = FastCaptureState::COLD_IDLE;
7682 state->mColdFutexAddr = &mFastCaptureFutex;
7683 state->mColdGen++;
7684 mFastCaptureFutex = 0;
7685 sq->end();
7686 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7687 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7688#if 0
7689 if (kUseFastCapture == FastCapture_Dynamic) {
7690 // FIXME
7691 }
7692#endif
7693#ifdef AUDIO_WATCHDOG
7694 // FIXME
7695#endif
7696 } else {
7697 sq->end(false /*didModify*/);
7698 }
7699 }
Mikhail Naganovaf288872019-09-25 13:05:02 -07007700 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007701 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007702
7703 // If going into standby, flush the pipe source.
7704 if (mPipeSource.get() != nullptr) {
7705 const ssize_t flushed = mPipeSource->flush();
7706 if (flushed > 0) {
7707 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7708 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7709 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7710 }
7711 }
Eric Laurent81784c32012-11-19 14:55:58 -08007712}
7713
Glenn Kasten05997e22014-03-13 15:08:33 -07007714// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007715sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007716 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007717 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007718 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007719 audio_format_t format,
7720 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007721 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007722 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007723 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007724 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007725 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007726 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007727 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007728 status_t *status,
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007729 audio_port_handle_t portId,
7730 const String16& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08007731{
Glenn Kasten74935e42013-12-19 08:56:45 -08007732 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007733 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007734 sp<RecordTrack> track;
7735 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007736 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007737 audio_input_flags_t requestedFlags = *flags;
7738 uint32_t sampleRate;
7739
7740 lStatus = initCheck();
7741 if (lStatus != NO_ERROR) {
7742 ALOGE("createRecordTrack_l() audio driver not initialized");
7743 goto Exit;
7744 }
7745
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007746 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7747 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7748 lStatus = BAD_VALUE;
7749 goto Exit;
7750 }
7751
Eric Laurentf14db3c2017-12-08 14:20:36 -08007752 if (*pSampleRate == 0) {
7753 *pSampleRate = mSampleRate;
7754 }
7755 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007756
7757 // special case for FAST flag considered OK if fast capture is present
7758 if (hasFastCapture()) {
7759 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7760 }
7761
Eric Laurentf14db3c2017-12-08 14:20:36 -08007762 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007763 if ((*flags & inputFlags) != *flags) {
7764 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7765 " input flags (%08x)",
7766 *flags, inputFlags);
7767 *flags = (audio_input_flags_t)(*flags & inputFlags);
7768 }
Eric Laurent81784c32012-11-19 14:55:58 -08007769
Glenn Kasten90e58b12013-07-31 16:16:02 -07007770 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007771 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007772 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007773 // we formerly checked for a callback handler (non-0 tid),
7774 // but that is no longer required for TRANSFER_OBTAIN mode
7775 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007776 // Frame count is not specified (0), or is less than or equal the pipe depth.
7777 // It is OK to provide a higher capacity than requested.
7778 // We will force it to mPipeFramesP2 below.
7779 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007780 // PCM data
7781 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007782 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007783 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007784 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007785 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007786 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007787 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007788 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007789 hasFastCapture() &&
7790 // there are sufficient fast track slots available
7791 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007792 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007793 // check compatibility with audio effects.
7794 Mutex::Autolock _l(mLock);
7795 // Do not accept FAST flag if the session has software effects
7796 sp<EffectChain> chain = getEffectChain_l(sessionId);
7797 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007798 audio_input_flags_t old = *flags;
7799 chain->checkInputFlagCompatibility(flags);
7800 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007801 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7802 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007803 }
7804 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007805 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007806 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7807 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007808 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007809 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7810 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007811 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007812 this, frameCount, mFrameCount, mPipeFramesP2,
7813 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007814 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007815 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007816 }
7817 }
7818
Eric Laurentf14db3c2017-12-08 14:20:36 -08007819 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7820 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7821 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7822 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7823 lStatus = BAD_TYPE;
7824 goto Exit;
7825 }
7826
Glenn Kasten74105912014-07-03 12:28:53 -07007827 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007828 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007829 // fast track: frame count is exactly the pipe depth
7830 frameCount = mPipeFramesP2;
7831 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007832 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007833 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007834 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7835 // or 20 ms if there is a fast capture
7836 // TODO This could be a roundupRatio inline, and const
7837 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7838 * sampleRate + mSampleRate - 1) / mSampleRate;
7839 // minimum number of notification periods is at least kMinNotifications,
7840 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7841 static const size_t kMinNotifications = 3;
7842 static const uint32_t kMinMs = 30;
7843 // TODO This could be a roundupRatio inline
7844 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7845 // TODO This could be a roundupRatio inline
7846 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7847 maxNotificationFrames;
7848 const size_t minFrameCount = maxNotificationFrames *
7849 max(kMinNotifications, minNotificationsByMs);
7850 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007851 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7852 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007853 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007854 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007855 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007856 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007857
7858 { // scope for mLock
7859 Mutex::Autolock _l(mLock);
7860
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007861 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007862 format, channelMask, frameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007863 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, uid,
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007864 *flags, TrackBase::TYPE_DEFAULT, opPackageName, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007865
Glenn Kasten03003332013-08-06 15:40:54 -07007866 lStatus = track->initCheck();
7867 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007868 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007869 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007870 goto Exit;
7871 }
7872 mTracks.add(track);
7873
Eric Laurent05067782016-06-01 18:27:28 -07007874 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007875 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7876 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7877 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007878 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007879 }
Eric Laurent81784c32012-11-19 14:55:58 -08007880 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007881
Eric Laurent81784c32012-11-19 14:55:58 -08007882 lStatus = NO_ERROR;
7883
7884Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007885 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007886 return track;
7887}
7888
7889status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7890 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007891 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007892{
7893 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7894 sp<ThreadBase> strongMe = this;
7895 status_t status = NO_ERROR;
7896
7897 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007898 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007899 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007900 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007901 triggerSession,
7902 recordTrack->sessionId(),
7903 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007904 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007905 // Sync event can be cancelled by the trigger session if the track is not in a
7906 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007907 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007908 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007909 } else {
7910 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007911 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007912 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007913 }
7914 }
7915
7916 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007917 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007918 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007919 if (recordTrack->isInvalid()) {
7920 recordTrack->clearSyncStartEvent();
Eric Laurent717bc282020-08-21 17:10:39 -07007921 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
7922 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07007923 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007924 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7925 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007926 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7927 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007928 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007929 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007930 } else {
7931 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007932 }
7933 return status;
7934 }
7935
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007936 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7937 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7938 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007939 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007940 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007941 status_t status = NO_ERROR;
7942 if (recordTrack->isExternalTrack()) {
7943 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007944 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007945 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007946 if (recordTrack->isInvalid()) {
7947 recordTrack->clearSyncStartEvent();
7948 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7949 recordTrack->mState = TrackBase::STARTING_2;
7950 // STARTING_2 forces destroy to call stopInput.
7951 }
Eric Laurent717bc282020-08-21 17:10:39 -07007952 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
7953 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07007954 }
7955 if (recordTrack->mState != TrackBase::STARTING_1) {
7956 ALOGW("%s(%d): unsynchronized mState:%d change",
7957 __func__, recordTrack->id(), recordTrack->mState);
7958 // Someone else has changed state, let them take over,
7959 // leave mState in the new state.
7960 recordTrack->clearSyncStartEvent();
7961 return INVALID_OPERATION;
7962 }
7963 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007964 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007965 ALOGW("%s(%d): startInput failed, status %d",
7966 __func__, recordTrack->id(), status);
7967 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7968 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007969 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007970 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007971 return status;
7972 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07007973 sendIoConfigEvent_l(
7974 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08007975 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07007976
7977 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
7978
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007979 // Catch up with current buffer indices if thread is already running.
7980 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7981 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7982 // see previously buffered data before it called start(), but with greater risk of overrun.
7983
Andy Hung73c02e42015-03-29 01:13:58 -07007984 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007985 if (!recordTrack->isDirect()) {
7986 // clear any converter state as new data will be discontinuous
7987 recordTrack->mRecordBufferConverter->reset();
7988 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007989 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007990 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007991 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007992 return status;
7993 }
Eric Laurent81784c32012-11-19 14:55:58 -08007994}
7995
Eric Laurent81784c32012-11-19 14:55:58 -08007996void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7997{
7998 sp<SyncEvent> strongEvent = event.promote();
7999
8000 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008001 sp<RefBase> ptr = strongEvent->cookie().promote();
8002 if (ptr != 0) {
8003 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8004 recordTrack->handleSyncStartEvent(strongEvent);
8005 }
Eric Laurent81784c32012-11-19 14:55:58 -08008006 }
8007}
8008
Glenn Kastena8356f62013-07-25 14:37:52 -07008009bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008010 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008011 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008012 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008013 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008014 return false;
8015 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008016 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008017 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008018
Andy Hungabfab202019-03-07 19:45:54 -08008019 // NOTE: Waiting here is important to keep stop synchronous.
8020 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008021 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8022 mWaitWorkCV.broadcast(); // signal thread to stop
8023 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008024 }
Andy Hungce685402018-10-05 17:23:27 -07008025
8026 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008027 ALOGV("Record stopped OK");
8028 return true;
8029 }
Andy Hungce685402018-10-05 17:23:27 -07008030
8031 // don't handle anything - we've been invalidated or restarted and in a different state
8032 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8033 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008034 return false;
8035}
8036
Glenn Kasten0f11b512014-01-31 16:18:54 -08008037bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008038{
8039 return false;
8040}
8041
Glenn Kasten0f11b512014-01-31 16:18:54 -08008042status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008043{
8044#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8045 if (!isValidSyncEvent(event)) {
8046 return BAD_VALUE;
8047 }
8048
Glenn Kastend848eb42016-03-08 13:42:11 -08008049 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008050 status_t ret = NAME_NOT_FOUND;
8051
8052 Mutex::Autolock _l(mLock);
8053
8054 for (size_t i = 0; i < mTracks.size(); i++) {
8055 sp<RecordTrack> track = mTracks[i];
8056 if (eventSession == track->sessionId()) {
8057 (void) track->setSyncEvent(event);
8058 ret = NO_ERROR;
8059 }
8060 }
8061 return ret;
8062#else
8063 return BAD_VALUE;
8064#endif
8065}
8066
jiabin653cc0a2018-01-17 17:54:10 -08008067status_t AudioFlinger::RecordThread::getActiveMicrophones(
8068 std::vector<media::MicrophoneInfo>* activeMicrophones)
8069{
8070 ALOGV("RecordThread::getActiveMicrophones");
8071 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07008072 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8073 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008074}
8075
Paul McLean12340082019-03-19 09:35:05 -06008076status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8077 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008078{
Paul McLean12340082019-03-19 09:35:05 -06008079 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008080 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008081 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008082}
8083
Paul McLean12340082019-03-19 09:35:05 -06008084status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008085{
Paul McLean12340082019-03-19 09:35:05 -06008086 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008087 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008088 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008089}
8090
Kevin Rocard069c2712018-03-29 19:09:14 -07008091void AudioFlinger::RecordThread::updateMetadata_l()
8092{
8093 if (mInput == nullptr || mInput->stream == nullptr ||
8094 !mActiveTracks.readAndClearHasChanged()) {
8095 return;
8096 }
8097 StreamInHalInterface::SinkMetadata metadata;
8098 for (const sp<RecordTrack> &track : mActiveTracks) {
8099 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent6109cdb2020-11-20 18:41:04 +01008100 record_track_metadata_v7_t trackMetadata;
8101 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008102 .source = track->attributes().source,
8103 .gain = 1, // capture tracks do not have volumes
Eric Laurent6109cdb2020-11-20 18:41:04 +01008104 };
8105 trackMetadata.channel_mask = track->channelMask(),
8106 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8107
8108 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008109 }
8110 mInput->stream->updateSinkMetadata(metadata);
8111}
8112
Eric Laurent81784c32012-11-19 14:55:58 -08008113// destroyTrack_l() must be called with ThreadBase::mLock held
8114void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8115{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008116 track->terminate();
8117 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08008118 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008119 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008120 removeTrack_l(track);
8121 }
8122}
8123
8124void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8125{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008126 String8 result;
8127 track->appendDump(result, false /* active */);
8128 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8129
Eric Laurent81784c32012-11-19 14:55:58 -08008130 mTracks.remove(track);
8131 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008132 if (track->isFastTrack()) {
8133 ALOG_ASSERT(!mFastTrackAvail);
8134 mFastTrackAvail = true;
8135 }
Eric Laurent81784c32012-11-19 14:55:58 -08008136}
8137
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008138void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008139{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008140 AudioStreamIn *input = mInput;
8141 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8142 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008143 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008144 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008145 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008146 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008147 }
Andy Hungbfa64962017-06-12 14:43:19 -07008148
8149 if (input != nullptr) {
8150 dprintf(fd, " Hal stream dump:\n");
8151 (void)input->stream->dump(fd);
8152 }
8153
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008154 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008155 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008156
Glenn Kasten2f90c512015-12-02 11:40:09 -08008157 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8158 // while we are dumping it. It may be inconsistent, but it won't mutate!
8159 // This is a large object so we place it on the heap.
8160 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008161 const std::unique_ptr<FastCaptureDumpState> copy =
8162 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008163 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008164}
8165
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008166void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008167{
Eric Laurent81784c32012-11-19 14:55:58 -08008168 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008169 size_t numtracks = mTracks.size();
8170 size_t numactive = mActiveTracks.size();
8171 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008172 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008173 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008174 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008175 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008176 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008177 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008178 for (size_t i = 0; i < numtracks ; ++i) {
8179 sp<RecordTrack> track = mTracks[i];
8180 if (track != 0) {
8181 bool active = mActiveTracks.indexOf(track) >= 0;
8182 if (active) {
8183 numactiveseen++;
8184 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008185 result.append(prefix);
8186 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008187 }
Eric Laurent81784c32012-11-19 14:55:58 -08008188 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008189 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008190 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008191 }
8192
Marco Nelissenb2208842014-02-07 14:00:50 -08008193 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008194 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008195 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008196 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008197 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008198 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008199 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008200 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008201 result.append(prefix);
8202 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008203 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008204 }
Eric Laurent81784c32012-11-19 14:55:58 -08008205
8206 }
8207 write(fd, result.string(), result.size());
8208}
8209
Eric Laurent5ada82e2019-08-29 17:53:54 -07008210void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008211{
8212 Mutex::Autolock _l(mLock);
8213 for (size_t i = 0; i < mTracks.size() ; i++) {
8214 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008215 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008216 track->setSilenced(silenced);
8217 }
8218 }
8219}
Andy Hung73c02e42015-03-29 01:13:58 -07008220
8221void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8222{
8223 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8224 RecordThread *recordThread = (RecordThread *) threadBase.get();
8225 mRsmpInFront = recordThread->mRsmpInRear;
8226 mRsmpInUnrel = 0;
8227}
8228
8229void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8230 size_t *framesAvailable, bool *hasOverrun)
8231{
8232 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8233 RecordThread *recordThread = (RecordThread *) threadBase.get();
8234 const int32_t rear = recordThread->mRsmpInRear;
8235 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008236 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008237
8238 size_t framesIn;
8239 bool overrun = false;
8240 if (filled < 0) {
8241 // should not happen, but treat like a massive overrun and re-sync
8242 framesIn = 0;
8243 mRsmpInFront = rear;
8244 overrun = true;
8245 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8246 framesIn = (size_t) filled;
8247 } else {
8248 // client is not keeping up with server, but give it latest data
8249 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008250 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8251 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008252 overrun = true;
8253 }
8254 if (framesAvailable != NULL) {
8255 *framesAvailable = framesIn;
8256 }
8257 if (hasOverrun != NULL) {
8258 *hasOverrun = overrun;
8259 }
8260}
8261
Eric Laurent81784c32012-11-19 14:55:58 -08008262// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008263status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008264 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008265{
Andy Hung73c02e42015-03-29 01:13:58 -07008266 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008267 if (threadBase == 0) {
8268 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008269 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008270 return NOT_ENOUGH_DATA;
8271 }
8272 RecordThread *recordThread = (RecordThread *) threadBase.get();
8273 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008274 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008275 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008276 // FIXME should not be P2 (don't want to increase latency)
8277 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008278 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008279 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008280 front &= recordThread->mRsmpInFramesP2 - 1;
8281 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008282 if (part1 > (size_t) filled) {
8283 part1 = filled;
8284 }
8285 size_t ask = buffer->frameCount;
8286 ALOG_ASSERT(ask > 0);
8287 if (part1 > ask) {
8288 part1 = ask;
8289 }
8290 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008291 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008292 buffer->raw = NULL;
8293 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008294 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008295 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008296 }
8297
Andy Hung57446612015-04-19 23:56:46 -07008298 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008299 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008300 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008301 return NO_ERROR;
8302}
8303
8304// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008305void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8306 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008307{
Hongwei Wang95e37682019-04-12 11:13:36 -07008308 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008309 if (stepCount == 0) {
8310 return;
8311 }
Andy Hung73c02e42015-03-29 01:13:58 -07008312 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8313 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008314 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008315 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008316 buffer->frameCount = 0;
8317}
8318
Eric Laurentd8365c52017-07-16 15:27:05 -07008319void AudioFlinger::RecordThread::checkBtNrec()
8320{
8321 Mutex::Autolock _l(mLock);
8322 checkBtNrec_l();
8323}
8324
8325void AudioFlinger::RecordThread::checkBtNrec_l()
8326{
8327 // disable AEC and NS if the device is a BT SCO headset supporting those
8328 // pre processings
jiabin10d86fd2019-10-31 17:20:42 -07008329 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008330 mAudioFlinger->btNrecIsOff();
8331 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8332 for (size_t i = 0; i < mEffectChains.size(); i++) {
8333 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8334 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8335 }
8336 }
8337}
8338
Andy Hung97a893e2015-03-29 01:03:07 -07008339
Eric Laurent10351942014-05-08 18:49:52 -07008340bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8341 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008342{
8343 bool reconfig = false;
8344
Eric Laurent10351942014-05-08 18:49:52 -07008345 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008346
Eric Laurent10351942014-05-08 18:49:52 -07008347 audio_format_t reqFormat = mFormat;
8348 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008349 // 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 -07008350 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8351
8352 AudioParameter param = AudioParameter(keyValuePair);
8353 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008354
8355 // scope for AutoPark extends to end of method
8356 AutoPark<FastCapture> park(mFastCapture);
8357
Eric Laurent10351942014-05-08 18:49:52 -07008358 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8359 // channel count change can be requested. Do we mandate the first client defines the
8360 // HAL sampling rate and channel count or do we allow changes on the fly?
8361 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8362 samplingRate = value;
8363 reconfig = true;
8364 }
8365 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008366 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008367 status = BAD_VALUE;
8368 } else {
8369 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008370 reconfig = true;
8371 }
Eric Laurent10351942014-05-08 18:49:52 -07008372 }
8373 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8374 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008375 if (!audio_is_input_channel(mask) ||
8376 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008377 status = BAD_VALUE;
8378 } else {
8379 channelMask = mask;
8380 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008381 }
Eric Laurent10351942014-05-08 18:49:52 -07008382 }
8383 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8384 // do not accept frame count changes if tracks are open as the track buffer
8385 // size depends on frame count and correct behavior would not be guaranteed
8386 // if frame count is changed after track creation
8387 if (mActiveTracks.size() > 0) {
8388 status = INVALID_OPERATION;
8389 } else {
8390 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008391 }
Eric Laurent10351942014-05-08 18:49:52 -07008392 }
8393 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07008394 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008395 }
8396 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8397 mAudioSource != (audio_source_t)value) {
jiabin10d86fd2019-10-31 17:20:42 -07008398 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008399 }
Glenn Kastene198c362013-08-13 09:13:36 -07008400
Eric Laurent10351942014-05-08 18:49:52 -07008401 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008402 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008403 if (status == INVALID_OPERATION) {
8404 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008405 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008406 }
8407 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008408 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008409 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8410 if (mInput->stream->getAudioProperties(&config) == OK &&
8411 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8412 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8413 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_8) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008414 status = NO_ERROR;
8415 }
Eric Laurent81784c32012-11-19 14:55:58 -08008416 }
Eric Laurent10351942014-05-08 18:49:52 -07008417 if (status == NO_ERROR) {
8418 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008419 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008420 }
8421 }
Eric Laurent81784c32012-11-19 14:55:58 -08008422 }
Eric Laurent10351942014-05-08 18:49:52 -07008423
Eric Laurent81784c32012-11-19 14:55:58 -08008424 return reconfig;
8425}
8426
8427String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8428{
Eric Laurent81784c32012-11-19 14:55:58 -08008429 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008430 if (initCheck() == NO_ERROR) {
8431 String8 out_s8;
8432 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8433 return out_s8;
8434 }
Eric Laurent81784c32012-11-19 14:55:58 -08008435 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008436 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008437}
8438
Eric Laurent09f1ed22019-04-24 17:45:17 -07008439void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8440 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008441 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8442
8443 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008444
8445 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008446 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008447 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008448 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008449 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008450 desc->mChannelMask = mChannelMask;
8451 desc->mSamplingRate = mSampleRate;
8452 desc->mFormat = mFormat;
8453 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008454 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008455 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008456 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008457 case AUDIO_CLIENT_STARTED:
8458 desc->mPatch = mPatch;
8459 desc->mPortId = portId;
8460 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008461 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008462 default:
8463 break;
8464 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008465 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008466}
8467
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008468void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008469{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008470 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8471 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008472 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008473 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8474 if (audio_is_linear_pcm(mFormat)) {
8475 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8476 mChannelCount, FCC_8);
8477 } else {
8478 // Can have more that FCC_8 channels in encoded streams.
8479 ALOGI("HAL format %#x is not linear pcm", mFormat);
8480 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008481 result = mInput->stream->getFrameSize(&mFrameSize);
8482 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008483 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8484 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008485 result = mInput->stream->getBufferSize(&mBufferSize);
8486 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008487 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008488 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8489 "mBufferSize=%zu, mFrameCount=%zu",
8490 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008491 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008492 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
Glenn Kasten85948432013-08-19 12:09:05 -07008493 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008494 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008495 // A larger value should allow more old data to be read after a track calls start(),
8496 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008497 //
8498 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008499 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008500 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008501 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008502 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008503
8504 // TODO optimize audio capture buffer sizes ...
8505 // Here we calculate the size of the sliding buffer used as a source
8506 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8507 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8508 // be better to have it derived from the pipe depth in the long term.
8509 // The current value is higher than necessary. However it should not add to latency.
8510
Glenn Kasten85948432013-08-19 12:09:05 -07008511 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008512 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8513 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008514 // if posix_memalign fails, will segv here.
8515 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008516
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008517 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8518 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008519
8520 audio_input_flags_t flags = mInput->flags;
8521 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8522 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8523 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8524 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8525 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8526 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8527 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8528 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8529 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008530}
8531
Glenn Kasten5f972c02014-01-13 09:59:31 -08008532uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008533{
8534 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008535 uint32_t result;
8536 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8537 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008538 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008539 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008540}
8541
Glenn Kastend848eb42016-03-08 13:42:11 -08008542KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008543{
Glenn Kastend848eb42016-03-08 13:42:11 -08008544 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008545 Mutex::Autolock _l(mLock);
8546 for (size_t j = 0; j < mTracks.size(); ++j) {
8547 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008548 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008549 if (ids.indexOfKey(sessionId) < 0) {
8550 ids.add(sessionId, true);
8551 }
8552 }
8553 return ids;
8554}
8555
8556AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8557{
8558 Mutex::Autolock _l(mLock);
8559 AudioStreamIn *input = mInput;
8560 mInput = NULL;
8561 return input;
8562}
8563
8564// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008565sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008566{
8567 if (mInput == NULL) {
8568 return NULL;
8569 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008570 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008571}
8572
8573status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8574{
Eric Laurent81784c32012-11-19 14:55:58 -08008575 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008576 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008577 chain->setInBuffer(NULL);
8578 chain->setOutBuffer(NULL);
8579
8580 checkSuspendOnAddEffectChain_l(chain);
8581
Eric Laurent1b928682014-10-02 19:41:47 -07008582 // make sure enabled pre processing effects state is communicated to the HAL as we
8583 // just moved them to a new input stream.
8584 chain->syncHalEffectsState();
8585
Eric Laurent81784c32012-11-19 14:55:58 -08008586 mEffectChains.add(chain);
8587
8588 return NO_ERROR;
8589}
8590
8591size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8592{
8593 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008594
8595 for (size_t i = 0; i < mEffectChains.size(); i++) {
8596 if (chain == mEffectChains[i]) {
8597 mEffectChains.removeAt(i);
8598 break;
8599 }
Eric Laurent81784c32012-11-19 14:55:58 -08008600 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008601 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008602}
8603
Eric Laurent1c333e22014-05-20 10:48:17 -07008604status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8605 audio_patch_handle_t *handle)
8606{
8607 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008608
8609 // store new device and send to effects
jiabin10d86fd2019-10-31 17:20:42 -07008610 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin4e826212020-08-07 17:32:40 -07008611 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008612 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008613 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08008614 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008615 }
8616
Eric Laurentd8365c52017-07-16 15:27:05 -07008617 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008618
8619 // store new source and send to effects
8620 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8621 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008622 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008623 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008624 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008625 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008626
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008627 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008628 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8629 status = hwDevice->createAudioPatch(patch->num_sources,
8630 patch->sources,
8631 patch->num_sinks,
8632 patch->sinks,
8633 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008634 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008635 char *address;
8636 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8637 address = audio_device_address_to_parameter(
8638 patch->sources[0].ext.device.type,
8639 patch->sources[0].ext.device.address);
8640 } else {
8641 address = (char *)calloc(1, 1);
8642 }
8643 AudioParameter param = AudioParameter(String8(address));
8644 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008645 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008646 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008647 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008648 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008649 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008650 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008651 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008652
jiabin10d86fd2019-10-31 17:20:42 -07008653 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008654 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabin10d86fd2019-10-31 17:20:42 -07008655 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008656 }
Eric Laurent296fb132015-05-01 11:38:42 -07008657
Andy Hungc2b11cb2020-04-22 09:04:01 -07008658 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008659 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008660 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008661 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008662 // also dispatch to active AudioRecords
8663 for (const auto &track : mActiveTracks) {
8664 track->logEndInterval();
8665 track->logBeginInterval(pathSourcesAsString);
8666 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008667 return status;
8668}
8669
8670status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8671{
8672 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008673
jiabin10d86fd2019-10-31 17:20:42 -07008674 mPatch = audio_patch{};
8675 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008676
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008677 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008678 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8679 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008680 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008681 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008682 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008683 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008684 }
8685 return status;
8686}
8687
jiabin10d86fd2019-10-31 17:20:42 -07008688void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8689{
wendy lin56aa82b2020-12-02 15:19:55 +08008690 Mutex::Autolock _l(mLock);
jiabin10d86fd2019-10-31 17:20:42 -07008691 mOutDevices = outDevices;
8692 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8693 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08008694 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabin10d86fd2019-10-31 17:20:42 -07008695 }
8696}
8697
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008698void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008699{
8700 Mutex::Autolock _l(mLock);
8701 mTracks.add(record);
Mikhail Naganovaf288872019-09-25 13:05:02 -07008702 if (record->getSource()) {
8703 mSource = record->getSource();
8704 }
Eric Laurent83b88082014-06-20 18:31:16 -07008705}
8706
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008707void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008708{
8709 Mutex::Autolock _l(mLock);
Mikhail Naganovaf288872019-09-25 13:05:02 -07008710 if (mSource == record->getSource()) {
8711 mSource = mInput;
8712 }
Eric Laurent83b88082014-06-20 18:31:16 -07008713 destroyTrack_l(record);
8714}
8715
Mikhail Naganovdc769682018-05-04 15:34:08 -07008716void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008717{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008718 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008719 config->role = AUDIO_PORT_ROLE_SINK;
8720 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8721 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008722 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8723 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8724 config->flags.input = mInput->flags;
8725 }
Eric Laurent83b88082014-06-20 18:31:16 -07008726}
Eric Laurent1c333e22014-05-20 10:48:17 -07008727
Eric Laurent6acd1d42017-01-04 14:23:29 -08008728// ----------------------------------------------------------------------------
8729// Mmap
8730// ----------------------------------------------------------------------------
8731
8732AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8733 : mThread(thread)
8734{
Phil Burk9fabbf82017-08-03 12:02:00 -07008735 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008736}
8737
8738AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8739{
Phil Burk9fabbf82017-08-03 12:02:00 -07008740 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008741}
8742
8743status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8744 struct audio_mmap_buffer_info *info)
8745{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008746 return mThread->createMmapBuffer(minSizeFrames, info);
8747}
8748
8749status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8750{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008751 return mThread->getMmapPosition(position);
8752}
8753
Eric Laurenta54f1282017-07-01 19:39:32 -07008754status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008755 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008756
8757{
jiabind1f1cb62020-03-24 11:57:57 -07008758 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008759}
8760
8761status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8762{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008763 return mThread->stop(handle);
8764}
8765
Eric Laurent18b57012017-02-13 16:23:52 -08008766status_t AudioFlinger::MmapThreadHandle::standby()
8767{
Eric Laurent18b57012017-02-13 16:23:52 -08008768 return mThread->standby();
8769}
8770
Eric Laurent6acd1d42017-01-04 14:23:29 -08008771
8772AudioFlinger::MmapThread::MmapThread(
8773 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07008774 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07008775 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008776 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008777 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008778 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008779 mActiveTracks(&this->mLocalLog),
8780 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8781 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008782{
Eric Laurent18b57012017-02-13 16:23:52 -08008783 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008784 readHalParameters_l();
8785}
8786
8787AudioFlinger::MmapThread::~MmapThread()
8788{
Eric Laurent18b57012017-02-13 16:23:52 -08008789 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008790}
8791
8792void AudioFlinger::MmapThread::onFirstRef()
8793{
8794 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8795}
8796
8797void AudioFlinger::MmapThread::disconnect()
8798{
Eric Laurent331679c2018-04-16 17:03:16 -07008799 ActiveTracks<MmapTrack> activeTracks;
8800 {
8801 Mutex::Autolock _l(mLock);
8802 for (const sp<MmapTrack> &t : mActiveTracks) {
8803 activeTracks.add(t);
8804 }
8805 }
8806 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008807 stop(t->portId());
8808 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008809 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008810 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008811 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008812 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008813 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008814 }
8815}
8816
8817
8818void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8819 audio_stream_type_t streamType __unused,
8820 audio_session_t sessionId,
8821 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008822 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008823 audio_port_handle_t portId)
8824{
8825 mAttr = *attr;
8826 mSessionId = sessionId;
8827 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008828 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008829 mPortId = portId;
8830}
8831
8832status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8833 struct audio_mmap_buffer_info *info)
8834{
8835 if (mHalStream == 0) {
8836 return NO_INIT;
8837 }
Eric Laurent18b57012017-02-13 16:23:52 -08008838 mStandby = true;
8839 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008840 return mHalStream->createMmapBuffer(minSizeFrames, info);
8841}
8842
8843status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8844{
8845 if (mHalStream == 0) {
8846 return NO_INIT;
8847 }
8848 return mHalStream->getMmapPosition(position);
8849}
8850
Eric Laurent331679c2018-04-16 17:03:16 -07008851status_t AudioFlinger::MmapThread::exitStandby()
8852{
8853 status_t ret = mHalStream->start();
8854 if (ret != NO_ERROR) {
8855 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8856 return ret;
8857 }
Andy Hungcf10d742020-04-28 15:38:24 -07008858 if (mStandby) {
8859 mThreadMetrics.logBeginInterval();
8860 mStandby = false;
8861 }
Eric Laurent331679c2018-04-16 17:03:16 -07008862 return NO_ERROR;
8863}
8864
Eric Laurenta54f1282017-07-01 19:39:32 -07008865status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008866 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008867 audio_port_handle_t *handle)
8868{
Eric Laurenta54f1282017-07-01 19:39:32 -07008869 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8870 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008871 if (mHalStream == 0) {
8872 return NO_INIT;
8873 }
8874
8875 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008876
Eric Laurenta54f1282017-07-01 19:39:32 -07008877 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008878 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008879 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008880 }
8881
8882 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8883
8884 audio_io_handle_t io = mId;
8885 if (isOutput()) {
8886 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8887 config.sample_rate = mSampleRate;
8888 config.channel_mask = mChannelMask;
8889 config.format = mFormat;
8890 audio_stream_type_t stream = streamType();
8891 audio_output_flags_t flags =
8892 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008893 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008894 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008895 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8896 mSessionId,
8897 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008898 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008899 client.clientUid,
8900 &config,
8901 flags,
8902 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008903 &portId,
8904 &secondaryOutputs);
8905 ALOGD_IF(!secondaryOutputs.empty(),
8906 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008907 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008908 audio_config_base_t config;
8909 config.sample_rate = mSampleRate;
8910 config.channel_mask = mChannelMask;
8911 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008912 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008913 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07008914 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07008915 mSessionId,
8916 client.clientPid,
8917 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008918 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008919 &config,
8920 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8921 &deviceId,
8922 &portId);
8923 }
8924 // APM should not chose a different input or output stream for the same set of attributes
8925 // and audo configuration
8926 if (ret != NO_ERROR || io != mId) {
8927 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8928 __FUNCTION__, ret, io, mId);
8929 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008930 }
8931
8932 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008933 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008934 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008935 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008936 }
8937
Eric Laurent331679c2018-04-16 17:03:16 -07008938 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008939 // abort if start is rejected by audio policy manager
8940 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008941 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008942 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008943 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008944 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008945 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008946 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008947 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008948 }
Eric Laurent331679c2018-04-16 17:03:16 -07008949 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008950 } else {
8951 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008952 }
8953 return PERMISSION_DENIED;
8954 }
8955
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008956 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07008957 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
8958 mChannelMask, mSessionId, isOutput(), client.clientUid,
8959 client.clientPid, IPCThreadState::self()->getCallingPid(),
8960 portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008961
Eric Laurent4eb58f12018-12-07 16:41:02 -08008962 if (isOutput()) {
8963 // force volume update when a new track is added
8964 mHalVolFloat = -1.0f;
8965 } else if (!track->isSilenced_l()) {
8966 for (const sp<MmapTrack> &t : mActiveTracks) {
8967 if (t->isSilenced_l() && t->uid() != client.clientUid)
8968 t->invalidate();
8969 }
8970 }
8971
8972
Eric Laurent6acd1d42017-01-04 14:23:29 -08008973 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008974 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008975 if (chain != 0) {
8976 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8977 chain->incTrackCnt();
8978 chain->incActiveTrackCnt();
8979 }
8980
Andy Hungc2b11cb2020-04-22 09:04:01 -07008981 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08008982 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008983 broadcast_l();
8984
Eric Laurenta54f1282017-07-01 19:39:32 -07008985 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008986
8987 return NO_ERROR;
8988}
8989
8990status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8991{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008992 ALOGV("%s handle %d", __FUNCTION__, handle);
8993
8994 if (mHalStream == 0) {
8995 return NO_INIT;
8996 }
8997
Eric Laurenta54f1282017-07-01 19:39:32 -07008998 if (handle == mPortId) {
8999 mHalStream->stop();
9000 return NO_ERROR;
9001 }
9002
Eric Laurent331679c2018-04-16 17:03:16 -07009003 Mutex::Autolock _l(mLock);
9004
Eric Laurent6acd1d42017-01-04 14:23:29 -08009005 sp<MmapTrack> track;
9006 for (const sp<MmapTrack> &t : mActiveTracks) {
9007 if (handle == t->portId()) {
9008 track = t;
9009 break;
9010 }
9011 }
9012 if (track == 0) {
9013 return BAD_VALUE;
9014 }
9015
9016 mActiveTracks.remove(track);
9017
Eric Laurent331679c2018-04-16 17:03:16 -07009018 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009019 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009020 AudioSystem::stopOutput(track->portId());
9021 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009022 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009023 AudioSystem::stopInput(track->portId());
9024 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009025 }
Eric Laurent331679c2018-04-16 17:03:16 -07009026 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009027
9028 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9029 if (chain != 0) {
9030 chain->decActiveTrackCnt();
9031 chain->decTrackCnt();
9032 }
9033
9034 broadcast_l();
9035
Eric Laurent6acd1d42017-01-04 14:23:29 -08009036 return NO_ERROR;
9037}
9038
Eric Laurent18b57012017-02-13 16:23:52 -08009039status_t AudioFlinger::MmapThread::standby()
9040{
9041 ALOGV("%s", __FUNCTION__);
9042
9043 if (mHalStream == 0) {
9044 return NO_INIT;
9045 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009046 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009047 return INVALID_OPERATION;
9048 }
9049 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009050 if (!mStandby) {
9051 mThreadMetrics.logEndInterval();
9052 mStandby = true;
9053 }
Eric Laurent18b57012017-02-13 16:23:52 -08009054 releaseWakeLock();
9055 return NO_ERROR;
9056}
9057
Eric Laurent6acd1d42017-01-04 14:23:29 -08009058
9059void AudioFlinger::MmapThread::readHalParameters_l()
9060{
9061 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9062 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9063 mFormat = mHALFormat;
9064 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9065 result = mHalStream->getFrameSize(&mFrameSize);
9066 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009067 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9068 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009069 result = mHalStream->getBufferSize(&mBufferSize);
9070 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9071 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009072
Andy Hungcf10d742020-04-28 15:38:24 -07009073 // TODO: make a readHalParameters call?
9074 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009075 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9076 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9077 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9078 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9079 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9080 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9081 /*
9082 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9083 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9084 (int32_t)mHapticChannelMask)
9085 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9086 (int32_t)mHapticChannelCount)
9087 */
9088 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9089 formatToString(mHALFormat).c_str())
9090 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9091 (int32_t)mFrameCount) // sic - added HAL
9092 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009093}
9094
9095bool AudioFlinger::MmapThread::threadLoop()
9096{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009097 checkSilentMode_l();
9098
9099 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9100
9101 while (!exitPending())
9102 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009103 Vector< sp<EffectChain> > effectChains;
9104
Andy Hung13850be2019-03-14 11:33:09 -07009105 { // under Thread lock
9106 Mutex::Autolock _l(mLock);
9107
Eric Laurent6acd1d42017-01-04 14:23:29 -08009108 if (mSignalPending) {
9109 // A signal was raised while we were unlocked
9110 mSignalPending = false;
9111 } else {
9112 if (mConfigEvents.isEmpty()) {
9113 // we're about to wait, flush the binder command buffer
9114 IPCThreadState::self()->flushCommands();
9115
9116 if (exitPending()) {
9117 break;
9118 }
9119
Eric Laurent6acd1d42017-01-04 14:23:29 -08009120 // wait until we have something to do...
9121 ALOGV("%s going to sleep", myName.string());
9122 mWaitWorkCV.wait(mLock);
9123 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009124
9125 checkSilentMode_l();
9126
9127 continue;
9128 }
9129 }
9130
9131 processConfigEvents_l();
9132
9133 processVolume_l();
9134
9135 checkInvalidTracks_l();
9136
9137 mActiveTracks.updatePowerState(this);
9138
Kevin Rocard069c2712018-03-29 19:09:14 -07009139 updateMetadata_l();
9140
Eric Laurent6acd1d42017-01-04 14:23:29 -08009141 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009142 } // release Thread lock
9143
Eric Laurent6acd1d42017-01-04 14:23:29 -08009144 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009145 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009146 }
Andy Hung13850be2019-03-14 11:33:09 -07009147
9148 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009149 unlockEffectChains(effectChains);
9150 // Effect chains will be actually deleted here if they were removed from
9151 // mEffectChains list during mixing or effects processing
9152 }
9153
9154 threadLoop_exit();
9155
9156 if (!mStandby) {
9157 threadLoop_standby();
9158 mStandby = true;
9159 }
9160
Eric Laurent6acd1d42017-01-04 14:23:29 -08009161 ALOGV("Thread %p type %d exiting", this, mType);
9162 return false;
9163}
9164
9165// checkForNewParameter_l() must be called with ThreadBase::mLock held
9166bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9167 status_t& status)
9168{
9169 AudioParameter param = AudioParameter(keyValuePair);
9170 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009171 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009172 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07009173 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009174 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009175 if (sendToHal) {
9176 status = mHalStream->setParameters(keyValuePair);
9177 } else {
9178 status = NO_ERROR;
9179 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009180
9181 return false;
9182}
9183
9184String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9185{
9186 Mutex::Autolock _l(mLock);
9187 String8 out_s8;
9188 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9189 return out_s8;
9190 }
9191 return String8();
9192}
9193
Eric Laurent09f1ed22019-04-24 17:45:17 -07009194void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9195 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009196 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9197
9198 desc->mIoHandle = mId;
9199
9200 switch (event) {
9201 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009202 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009203 case AUDIO_INPUT_CONFIG_CHANGED:
9204 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009205 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009206 case AUDIO_OUTPUT_CONFIG_CHANGED:
9207 desc->mPatch = mPatch;
9208 desc->mChannelMask = mChannelMask;
9209 desc->mSamplingRate = mSampleRate;
9210 desc->mFormat = mFormat;
9211 desc->mFrameCount = mFrameCount;
9212 desc->mFrameCountHAL = mFrameCount;
9213 desc->mLatency = 0;
9214 break;
9215
9216 case AUDIO_INPUT_CLOSED:
9217 case AUDIO_OUTPUT_CLOSED:
9218 default:
9219 break;
9220 }
9221 mAudioFlinger->ioConfigChanged(event, desc, pid);
9222}
9223
9224status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9225 audio_patch_handle_t *handle)
9226{
9227 status_t status = NO_ERROR;
9228
9229 // store new device and send to effects
9230 audio_devices_t type = AUDIO_DEVICE_NONE;
9231 audio_port_handle_t deviceId;
jiabin10d86fd2019-10-31 17:20:42 -07009232 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9233 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9234 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009235 if (isOutput()) {
9236 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabin10d86fd2019-10-31 17:20:42 -07009237 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9238 && !mAudioHwDev->supportsAudioPatches(),
9239 "Enumerated device type(%#x) must not be used "
9240 "as it does not support audio patches",
9241 patch->sinks[i].ext.device.type);
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07009242 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabin10d86fd2019-10-31 17:20:42 -07009243 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9244 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009245 }
9246 deviceId = patch->sinks[0].id;
jiabin10d86fd2019-10-31 17:20:42 -07009247 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009248 } else {
9249 type = patch->sources[0].ext.device.type;
9250 deviceId = patch->sources[0].id;
jiabin10d86fd2019-10-31 17:20:42 -07009251 numDevices = mPatch.num_sources;
9252 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin4e826212020-08-07 17:32:40 -07009253 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009254 }
9255
9256 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08009257 if (isOutput()) {
9258 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9259 } else {
9260 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9261 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009262 }
9263
jiabin10d86fd2019-10-31 17:20:42 -07009264 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009265 // store new source and send to effects
9266 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9267 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9268 for (size_t i = 0; i < mEffectChains.size(); i++) {
9269 mEffectChains[i]->setAudioSource_l(mAudioSource);
9270 }
9271 }
9272 }
9273
9274 if (mAudioHwDev->supportsAudioPatches()) {
9275 status = mHalDevice->createAudioPatch(patch->num_sources,
9276 patch->sources,
9277 patch->num_sinks,
9278 patch->sinks,
9279 handle);
9280 } else {
9281 char *address;
9282 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9283 //FIXME: we only support address on first sink with HAL version < 3.0
9284 address = audio_device_address_to_parameter(
9285 patch->sinks[0].ext.device.type,
9286 patch->sinks[0].ext.device.address);
9287 } else {
9288 address = (char *)calloc(1, 1);
9289 }
9290 AudioParameter param = AudioParameter(String8(address));
9291 free(address);
9292 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9293 if (!isOutput()) {
9294 param.addInt(String8(AudioParameter::keyInputSource),
9295 (int)patch->sinks[0].ext.mix.usecase.source);
9296 }
9297 status = mHalStream->setParameters(param.toString());
9298 *handle = AUDIO_PATCH_HANDLE_NONE;
9299 }
9300
jiabin10d86fd2019-10-31 17:20:42 -07009301 if (numDevices == 0 || mDeviceId != deviceId) {
9302 if (isOutput()) {
9303 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9304 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009305 checkSilentMode_l();
jiabin10d86fd2019-10-31 17:20:42 -07009306 } else {
9307 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9308 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9309 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009310 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009311 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009312 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009313 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009314 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009315 }
jiabin10d86fd2019-10-31 17:20:42 -07009316 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009317 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009318 }
9319 return status;
9320}
9321
9322status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9323{
9324 status_t status = NO_ERROR;
9325
jiabin10d86fd2019-10-31 17:20:42 -07009326 mPatch = audio_patch{};
9327 mOutDeviceTypeAddrs.clear();
9328 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009329
9330 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9331 supportsAudioPatches : false;
9332
9333 if (supportsAudioPatches) {
9334 status = mHalDevice->releaseAudioPatch(handle);
9335 } else {
9336 AudioParameter param;
9337 param.addInt(String8(AudioParameter::keyRouting), 0);
9338 status = mHalStream->setParameters(param.toString());
9339 }
9340 return status;
9341}
9342
Mikhail Naganovdc769682018-05-04 15:34:08 -07009343void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009344{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009345 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009346 if (isOutput()) {
9347 config->role = AUDIO_PORT_ROLE_SOURCE;
9348 config->ext.mix.hw_module = mAudioHwDev->handle();
9349 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9350 } else {
9351 config->role = AUDIO_PORT_ROLE_SINK;
9352 config->ext.mix.hw_module = mAudioHwDev->handle();
9353 config->ext.mix.usecase.source = mAudioSource;
9354 }
9355}
9356
9357status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9358{
9359 audio_session_t session = chain->sessionId();
9360
9361 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9362 // Attach all tracks with same session ID to this chain.
9363 // indicate all active tracks in the chain
9364 for (const sp<MmapTrack> &track : mActiveTracks) {
9365 if (session == track->sessionId()) {
9366 chain->incTrackCnt();
9367 chain->incActiveTrackCnt();
9368 }
9369 }
9370
9371 chain->setThread(this);
9372 chain->setInBuffer(nullptr);
9373 chain->setOutBuffer(nullptr);
9374 chain->syncHalEffectsState();
9375
9376 mEffectChains.add(chain);
9377 checkSuspendOnAddEffectChain_l(chain);
9378 return NO_ERROR;
9379}
9380
9381size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9382{
9383 audio_session_t session = chain->sessionId();
9384
9385 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9386
9387 for (size_t i = 0; i < mEffectChains.size(); i++) {
9388 if (chain == mEffectChains[i]) {
9389 mEffectChains.removeAt(i);
9390 // detach all active tracks from the chain
9391 // detach all tracks with same session ID from this chain
9392 for (const sp<MmapTrack> &track : mActiveTracks) {
9393 if (session == track->sessionId()) {
9394 chain->decActiveTrackCnt();
9395 chain->decTrackCnt();
9396 }
9397 }
9398 break;
9399 }
9400 }
9401 return mEffectChains.size();
9402}
9403
Eric Laurent6acd1d42017-01-04 14:23:29 -08009404void AudioFlinger::MmapThread::threadLoop_standby()
9405{
9406 mHalStream->standby();
9407}
9408
9409void AudioFlinger::MmapThread::threadLoop_exit()
9410{
Phil Burk7dce7282017-09-27 13:51:41 -07009411 // Do not call callback->onTearDown() because it is redundant for thread exit
9412 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009413}
9414
9415status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9416{
9417 return BAD_VALUE;
9418}
9419
9420bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9421{
9422 return false;
9423}
9424
9425status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9426 const effect_descriptor_t *desc, audio_session_t sessionId)
9427{
9428 // No global effect sessions on mmap threads
Eric Laurenta20c4e92019-11-12 15:55:51 -08009429 if (audio_is_global_session(sessionId)) {
9430 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009431 desc->name, mThreadName);
9432 return BAD_VALUE;
9433 }
9434
9435 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9436 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9437 desc->name);
9438 return BAD_VALUE;
9439 }
9440 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009441 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9442 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009443 return BAD_VALUE;
9444 }
9445
9446 // Only allow effects without processing load or latency
9447 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9448 return BAD_VALUE;
9449 }
9450
9451 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009452}
9453
9454void AudioFlinger::MmapThread::checkInvalidTracks_l()
9455{
9456 for (const sp<MmapTrack> &track : mActiveTracks) {
9457 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009458 sp<MmapStreamCallback> callback = mCallback.promote();
9459 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009460 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009461 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009462 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009463 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9464 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9465 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009466 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009467 }
9468 }
9469}
9470
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009471void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009472{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009473 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9474 mAttr.content_type, mAttr.usage, mAttr.source);
9475 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009476 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009477 dprintf(fd, " No active clients\n");
9478 }
9479}
9480
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009481void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009482{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009483 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009484 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009485 dprintf(fd, " %zu Tracks\n", numtracks);
9486 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009487 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009488 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009489 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009490 for (size_t i = 0; i < numtracks ; ++i) {
9491 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009492 result.append(prefix);
9493 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009494 }
9495 } else {
9496 dprintf(fd, "\n");
9497 }
9498 write(fd, result.string(), result.size());
9499}
9500
9501AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9502 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -07009503 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009504 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009505 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009506 mStreamVolume(1.0),
9507 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009508 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009509{
9510 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9511 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9512 mMasterVolume = audioFlinger->masterVolume_l();
9513 mMasterMute = audioFlinger->masterMute_l();
9514 if (mAudioHwDev) {
9515 if (mAudioHwDev->canSetMasterVolume()) {
9516 mMasterVolume = 1.0;
9517 }
9518
9519 if (mAudioHwDev->canSetMasterMute()) {
9520 mMasterMute = false;
9521 }
9522 }
9523}
9524
9525void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9526 audio_stream_type_t streamType,
9527 audio_session_t sessionId,
9528 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009529 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009530 audio_port_handle_t portId)
9531{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009532 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009533 mStreamType = streamType;
9534}
9535
9536AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9537{
9538 Mutex::Autolock _l(mLock);
9539 AudioStreamOut *output = mOutput;
9540 mOutput = NULL;
9541 return output;
9542}
9543
9544void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9545{
9546 Mutex::Autolock _l(mLock);
9547 // Don't apply master volume in SW if our HAL can do it for us.
9548 if (mAudioHwDev &&
9549 mAudioHwDev->canSetMasterVolume()) {
9550 mMasterVolume = 1.0;
9551 } else {
9552 mMasterVolume = value;
9553 }
9554}
9555
9556void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9557{
9558 Mutex::Autolock _l(mLock);
9559 // Don't apply master mute in SW if our HAL can do it for us.
9560 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9561 mMasterMute = false;
9562 } else {
9563 mMasterMute = muted;
9564 }
9565}
9566
9567void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9568{
9569 Mutex::Autolock _l(mLock);
9570 if (stream == mStreamType) {
9571 mStreamVolume = value;
9572 broadcast_l();
9573 }
9574}
9575
9576float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9577{
9578 Mutex::Autolock _l(mLock);
9579 if (stream == mStreamType) {
9580 return mStreamVolume;
9581 }
9582 return 0.0f;
9583}
9584
9585void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9586{
9587 Mutex::Autolock _l(mLock);
9588 if (stream == mStreamType) {
9589 mStreamMute= muted;
9590 broadcast_l();
9591 }
9592}
9593
9594void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9595{
9596 Mutex::Autolock _l(mLock);
9597 if (streamType == mStreamType) {
9598 for (const sp<MmapTrack> &track : mActiveTracks) {
9599 track->invalidate();
9600 }
9601 broadcast_l();
9602 }
9603}
9604
9605void AudioFlinger::MmapPlaybackThread::processVolume_l()
9606{
9607 float volume;
9608
9609 if (mMasterMute || mStreamMute) {
9610 volume = 0;
9611 } else {
9612 volume = mMasterVolume * mStreamVolume;
9613 }
9614
9615 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009616
9617 // Convert volumes from float to 8.24
9618 uint32_t vol = (uint32_t)(volume * (1 << 24));
9619
9620 // Delegate volume control to effect in track effect chain if needed
9621 // only one effect chain can be present on DirectOutputThread, so if
9622 // there is one, the track is connected to it
9623 if (!mEffectChains.isEmpty()) {
9624 mEffectChains[0]->setVolume_l(&vol, &vol);
9625 volume = (float)vol / (1 << 24);
9626 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009627 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009628 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9629 mHalVolFloat = volume; // HW volume control worked, so update value.
9630 mNoCallbackWarningCount = 0;
9631 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009632 sp<MmapStreamCallback> callback = mCallback.promote();
9633 if (callback != 0) {
9634 int channelCount;
9635 if (isOutput()) {
9636 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9637 } else {
9638 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9639 }
9640 Vector<float> values;
9641 for (int i = 0; i < channelCount; i++) {
9642 values.add(volume);
9643 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009644 mHalVolFloat = volume; // SW volume control worked, so update value.
9645 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009646 mLock.unlock();
9647 callback->onVolumeChanged(mChannelMask, values);
9648 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009649 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009650 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9651 ALOGW("Could not set MMAP stream volume: no volume callback!");
9652 mNoCallbackWarningCount++;
9653 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009654 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009655 }
9656 }
9657}
9658
Kevin Rocard069c2712018-03-29 19:09:14 -07009659void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9660{
9661 if (mOutput == nullptr || mOutput->stream == nullptr ||
9662 !mActiveTracks.readAndClearHasChanged()) {
9663 return;
9664 }
9665 StreamOutHalInterface::SourceMetadata metadata;
9666 for (const sp<MmapTrack> &track : mActiveTracks) {
9667 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent6109cdb2020-11-20 18:41:04 +01009668 playback_track_metadata_v7_t trackMetadata;
9669 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009670 .usage = track->attributes().usage,
9671 .content_type = track->attributes().content_type,
9672 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent6109cdb2020-11-20 18:41:04 +01009673 };
9674 trackMetadata.channel_mask = track->channelMask(),
9675 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9676 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009677 }
9678 mOutput->stream->updateSourceMetadata(metadata);
9679}
9680
Eric Laurent6acd1d42017-01-04 14:23:29 -08009681void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9682{
9683 if (!mMasterMute) {
9684 char value[PROPERTY_VALUE_MAX];
9685 if (property_get("ro.audio.silent", value, "0") > 0) {
9686 char *endptr;
9687 unsigned long ul = strtoul(value, &endptr, 0);
9688 if (*endptr == '\0' && ul != 0) {
9689 ALOGD("Silence is golden");
9690 // The setprop command will not allow a property to be changed after
9691 // the first time it is set, so we don't have to worry about un-muting.
9692 setMasterMute_l(true);
9693 }
9694 }
9695 }
9696}
9697
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009698void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9699{
9700 MmapThread::toAudioPortConfig(config);
9701 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9702 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9703 config->flags.output = mOutput->flags;
9704 }
9705}
9706
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009707void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009708{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009709 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009710
Glenn Kastend3bb6452016-12-05 18:14:37 -08009711 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9712 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009713 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9714}
9715
9716AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9717 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -07009718 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009719 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009720 mInput(input)
9721{
9722 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9723 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9724}
9725
Eric Laurent331679c2018-04-16 17:03:16 -07009726status_t AudioFlinger::MmapCaptureThread::exitStandby()
9727{
Phil Burkf054fc32018-12-06 09:45:59 -08009728 {
9729 // mInput might have been cleared by clearInput()
9730 Mutex::Autolock _l(mLock);
9731 if (mInput != nullptr && mInput->stream != nullptr) {
9732 mInput->stream->setGain(1.0f);
9733 }
9734 }
Eric Laurent331679c2018-04-16 17:03:16 -07009735 return MmapThread::exitStandby();
9736}
9737
Eric Laurent6acd1d42017-01-04 14:23:29 -08009738AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9739{
9740 Mutex::Autolock _l(mLock);
9741 AudioStreamIn *input = mInput;
9742 mInput = NULL;
9743 return input;
9744}
Kevin Rocard069c2712018-03-29 19:09:14 -07009745
Eric Laurent331679c2018-04-16 17:03:16 -07009746
9747void AudioFlinger::MmapCaptureThread::processVolume_l()
9748{
9749 bool changed = false;
9750 bool silenced = false;
9751
9752 sp<MmapStreamCallback> callback = mCallback.promote();
9753 if (callback == 0) {
9754 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9755 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9756 mNoCallbackWarningCount++;
9757 }
9758 }
9759
9760 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9761 // track is silenced and unmute otherwise
9762 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9763 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9764 changed = true;
9765 silenced = mActiveTracks[i]->isSilenced_l();
9766 }
9767 }
9768
9769 if (changed) {
9770 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9771 }
9772}
9773
Kevin Rocard069c2712018-03-29 19:09:14 -07009774void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9775{
9776 if (mInput == nullptr || mInput->stream == nullptr ||
9777 !mActiveTracks.readAndClearHasChanged()) {
9778 return;
9779 }
9780 StreamInHalInterface::SinkMetadata metadata;
9781 for (const sp<MmapTrack> &track : mActiveTracks) {
9782 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent6109cdb2020-11-20 18:41:04 +01009783 record_track_metadata_v7_t trackMetadata;
9784 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07009785 .source = track->attributes().source,
9786 .gain = 1, // capture tracks do not have volumes
Eric Laurent6109cdb2020-11-20 18:41:04 +01009787 };
9788 trackMetadata.channel_mask = track->channelMask(),
9789 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9790 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07009791 }
9792 mInput->stream->updateSinkMetadata(metadata);
9793}
9794
Eric Laurent5ada82e2019-08-29 17:53:54 -07009795void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -07009796{
9797 Mutex::Autolock _l(mLock);
9798 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07009799 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -07009800 mActiveTracks[i]->setSilenced_l(silenced);
9801 broadcast_l();
9802 }
9803 }
9804}
9805
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009806void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9807{
9808 MmapThread::toAudioPortConfig(config);
9809 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9810 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9811 config->flags.input = mInput->flags;
9812 }
9813}
9814
Glenn Kasten63238ef2015-03-02 15:50:29 -08009815} // namespace android