blob: 69bf8318c28cf72dc91a1461871e86def9ce9e5a [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>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <cutils/properties.h>
jiabinc52b1ff2019-10-31 17:20:42 -070033#include <media/AudioContainers.h>
34#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070035#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070036#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080037#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070038#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080039#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080040#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080041
42#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070043#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010044#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080045#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080046#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080047#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080048#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080049#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070050#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070051#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070052#include <system/audio_effects/effect_ns.h>
53#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070054#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080055
56// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070057#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080058#include <media/nbaio/AudioStreamOutSink.h>
59#include <media/nbaio/MonoPipe.h>
60#include <media/nbaio/MonoPipeReader.h>
61#include <media/nbaio/Pipe.h>
62#include <media/nbaio/PipeReader.h>
63#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080064#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080065
Mikhail Naganov2996f672019-04-18 12:29:59 -070066#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080067#include <powermanager/PowerManager.h>
68
Kevin Rocard7588ff42018-01-08 11:11:30 -080069#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070070#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080071
Eric Laurent81784c32012-11-19 14:55:58 -080072#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080073#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070074#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070075#include <mediautils/SchedulingPolicyService.h>
76#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080077
Eric Laurent81784c32012-11-19 14:55:58 -080078#ifdef ADD_BATTERY_DATA
79#include <media/IMediaPlayerService.h>
80#include <media/IMediaDeathNotifier.h>
81#endif
82
Eric Laurent81784c32012-11-19 14:55:58 -080083#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070084#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080085#include <cpustats/ThreadCpuUsage.h>
86#endif
87
Glenn Kastenc05b8d72016-03-24 09:48:17 -070088#include "AutoPark.h"
89
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080090#include <pthread.h>
91#include "TypedLogger.h"
92
Eric Laurent81784c32012-11-19 14:55:58 -080093// ----------------------------------------------------------------------------
94
95// Note: the following macro is used for extremely verbose logging message. In
96// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
97// 0; but one side effect of this is to turn all LOGV's as well. Some messages
98// are so verbose that we want to suppress them even when we have ALOG_ASSERT
99// turned on. Do not uncomment the #def below unless you really know what you
100// are doing and want to see all of the extremely verbose messages.
101//#define VERY_VERY_VERBOSE_LOGGING
102#ifdef VERY_VERY_VERBOSE_LOGGING
103#define ALOGVV ALOGV
104#else
105#define ALOGVV(a...) do { } while(0)
106#endif
107
Andy Hung6770c6f2015-04-07 13:43:36 -0700108// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700109#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700110template <typename T>
111static inline T min(const T& a, const T& b)
112{
113 return a < b ? a : b;
114}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700115
Eric Laurent81784c32012-11-19 14:55:58 -0800116namespace android {
117
118// retry counts for buffer fill timeout
119// 50 * ~20msecs = 1 second
120static const int8_t kMaxTrackRetries = 50;
121static const int8_t kMaxTrackStartupRetries = 50;
122// allow less retry attempts on direct output thread.
123// direct outputs can be a scarce resource in audio hardware and should
124// be released as quickly as possible.
125static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700126
Eric Laurent51716182016-02-29 18:00:56 -0800127
Eric Laurent81784c32012-11-19 14:55:58 -0800128
129// don't warn about blocked writes or record buffer overflows more often than this
130static const nsecs_t kWarningThrottleNs = seconds(5);
131
132// RecordThread loop sleep time upon application overrun or audio HAL read error
133static const int kRecordThreadSleepUs = 5000;
134
Eric Laurent10351942014-05-08 18:49:52 -0700135// maximum time to wait in sendConfigEvent_l() for a status to be received
136static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800137
138// minimum sleep time for the mixer thread loop when tracks are active but in underrun
139static const uint32_t kMinThreadSleepTimeUs = 5000;
140// maximum divider applied to the active sleep time in the mixer thread loop
141static const uint32_t kMaxThreadSleepTimeShift = 2;
142
Andy Hung09a50072014-02-27 14:30:47 -0800143// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700144// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800145static const uint32_t kMinNormalSinkBufferSizeMs = 20;
146// maximum normal sink buffer size
147static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800148
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700149// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
150// FIXME This should be based on experimentally observed scheduling jitter
151static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
152
Eric Laurent972a1732013-09-04 09:42:59 -0700153// Offloaded output thread standby delay: allows track transition without going to standby
154static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
155
Eric Laurent51716182016-02-29 18:00:56 -0800156// Direct output thread minimum sleep time in idle or active(underrun) state
157static const nsecs_t kDirectMinSleepTimeUs = 10000;
158
Glenn Kasten1b291842016-07-18 14:55:21 -0700159// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
160// balance between power consumption and latency, and allows threads to be scheduled reliably
161// by the CFS scheduler.
162// FIXME Express other hardcoded references to 20ms with references to this constant and move
163// it appropriately.
164#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800165
Eric Laurent81784c32012-11-19 14:55:58 -0800166// Whether to use fast mixer
167static const enum {
168 FastMixer_Never, // never initialize or use: for debugging only
169 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
170 // normal mixer multiplier is 1
171 FastMixer_Static, // initialize if needed, then use all the time if initialized,
172 // multiplier is calculated based on min & max normal mixer buffer size
173 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
174 // multiplier is calculated based on min & max normal mixer buffer size
175 // FIXME for FastMixer_Dynamic:
176 // Supporting this option will require fixing HALs that can't handle large writes.
177 // For example, one HAL implementation returns an error from a large write,
178 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
179 // We could either fix the HAL implementations, or provide a wrapper that breaks
180 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
181} kUseFastMixer = FastMixer_Static;
182
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700183// Whether to use fast capture
184static const enum {
185 FastCapture_Never, // never initialize or use: for debugging only
186 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
187 FastCapture_Static, // initialize if needed, then use all the time if initialized
188} kUseFastCapture = FastCapture_Static;
189
Eric Laurent81784c32012-11-19 14:55:58 -0800190// Priorities for requestPriority
191static const int kPriorityAudioApp = 2;
192static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700193static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800194
Glenn Kastenea38ee72016-04-18 11:08:01 -0700195// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
196// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
197// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700198
199// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800200static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800201
Glenn Kasten03490092014-05-27 12:30:54 -0700202// The minimum and maximum allowed values
203static const int kFastTrackMultiplierMin = 1;
204static const int kFastTrackMultiplierMax = 2;
205
206// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
207static int sFastTrackMultiplier = kFastTrackMultiplier;
208
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700209// See Thread::readOnlyHeap().
210// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
211// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
212// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700213static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700214
Eric Laurent81784c32012-11-19 14:55:58 -0800215// ----------------------------------------------------------------------------
216
Andy Hungb68f5eb2019-12-03 16:49:17 -0800217// TODO: move all toString helpers to audio.h
218// under #ifdef __cplusplus #endif
219static std::string patchSinksToString(const struct audio_patch *patch)
220{
221 std::stringstream ss;
222 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700223 if (i > 0) {
224 ss << "|";
225 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800226 ss << "(" << toString(patch->sinks[i].ext.device.type)
227 << ", " << patch->sinks[i].ext.device.address << ")";
228 }
229 return ss.str();
230}
231
232static std::string patchSourcesToString(const struct audio_patch *patch)
233{
234 std::stringstream ss;
235 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700236 if (i > 0) {
237 ss << "|";
238 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800239 ss << "(" << toString(patch->sources[i].ext.device.type)
240 << ", " << patch->sources[i].ext.device.address << ")";
241 }
242 return ss.str();
243}
244
Glenn Kasten03490092014-05-27 12:30:54 -0700245static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
246
247static void sFastTrackMultiplierInit()
248{
249 char value[PROPERTY_VALUE_MAX];
250 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
251 char *endptr;
252 unsigned long ul = strtoul(value, &endptr, 0);
253 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
254 sFastTrackMultiplier = (int) ul;
255 }
256 }
257}
258
259// ----------------------------------------------------------------------------
260
Eric Laurent81784c32012-11-19 14:55:58 -0800261#ifdef ADD_BATTERY_DATA
262// To collect the amplifier usage
263static void addBatteryData(uint32_t params) {
264 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
265 if (service == NULL) {
266 // it already logged
267 return;
268 }
269
270 service->addBatteryData(params);
271}
272#endif
273
Andy Hung3f0c9022016-01-15 17:49:46 -0800274// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
275struct {
276 // call when you acquire a partial wakelock
277 void acquire(const sp<IBinder> &wakeLockToken) {
278 pthread_mutex_lock(&mLock);
279 if (wakeLockToken.get() == nullptr) {
280 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
281 } else {
282 if (mCount == 0) {
283 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
284 }
285 ++mCount;
286 }
287 pthread_mutex_unlock(&mLock);
288 }
289
290 // call when you release a partial wakelock.
291 void release(const sp<IBinder> &wakeLockToken) {
292 if (wakeLockToken.get() == nullptr) {
293 return;
294 }
295 pthread_mutex_lock(&mLock);
296 if (--mCount < 0) {
297 ALOGE("negative wakelock count");
298 mCount = 0;
299 }
300 pthread_mutex_unlock(&mLock);
301 }
302
303 // retrieves the boottime timebase offset from monotonic.
304 int64_t getBoottimeOffset() {
305 pthread_mutex_lock(&mLock);
306 int64_t boottimeOffset = mBoottimeOffset;
307 pthread_mutex_unlock(&mLock);
308 return boottimeOffset;
309 }
310
311 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
312 // and the selected timebase.
313 // Currently only TIMEBASE_BOOTTIME is allowed.
314 //
315 // This only needs to be called upon acquiring the first partial wakelock
316 // after all other partial wakelocks are released.
317 //
318 // We do an empirical measurement of the offset rather than parsing
319 // /proc/timer_list since the latter is not a formal kernel ABI.
320 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
321 int clockbase;
322 switch (timebase) {
323 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
324 clockbase = SYSTEM_TIME_BOOTTIME;
325 break;
326 default:
327 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
328 break;
329 }
330 // try three times to get the clock offset, choose the one
331 // with the minimum gap in measurements.
332 const int tries = 3;
333 nsecs_t bestGap, measured;
334 for (int i = 0; i < tries; ++i) {
335 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
336 const nsecs_t tbase = systemTime(clockbase);
337 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
338 const nsecs_t gap = tmono2 - tmono;
339 if (i == 0 || gap < bestGap) {
340 bestGap = gap;
341 measured = tbase - ((tmono + tmono2) >> 1);
342 }
343 }
344
345 // to avoid micro-adjusting, we don't change the timebase
346 // unless it is significantly different.
347 //
348 // Assumption: It probably takes more than toleranceNs to
349 // suspend and resume the device.
350 static int64_t toleranceNs = 10000; // 10 us
351 if (llabs(*offset - measured) > toleranceNs) {
352 ALOGV("Adjusting timebase offset old: %lld new: %lld",
353 (long long)*offset, (long long)measured);
354 *offset = measured;
355 }
356 }
357
358 pthread_mutex_t mLock;
359 int32_t mCount;
360 int64_t mBoottimeOffset;
361} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800362
363// ----------------------------------------------------------------------------
364// CPU Stats
365// ----------------------------------------------------------------------------
366
367class CpuStats {
368public:
369 CpuStats();
370 void sample(const String8 &title);
371#ifdef DEBUG_CPU_USAGE
372private:
373 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700374 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800375
Andy Hung16698b82018-08-01 10:48:38 -0700376 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800377
378 int mCpuNum; // thread's current CPU number
379 int mCpukHz; // frequency of thread's current CPU in kHz
380#endif
381};
382
383CpuStats::CpuStats()
384#ifdef DEBUG_CPU_USAGE
385 : mCpuNum(-1), mCpukHz(-1)
386#endif
387{
388}
389
Glenn Kasten0f11b512014-01-31 16:18:54 -0800390void CpuStats::sample(const String8 &title
391#ifndef DEBUG_CPU_USAGE
392 __unused
393#endif
394 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800395#ifdef DEBUG_CPU_USAGE
396 // get current thread's delta CPU time in wall clock ns
397 double wcNs;
398 bool valid = mCpuUsage.sampleAndEnable(wcNs);
399
400 // record sample for wall clock statistics
401 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700402 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800403 }
404
405 // get the current CPU number
406 int cpuNum = sched_getcpu();
407
408 // get the current CPU frequency in kHz
409 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
410
411 // check if either CPU number or frequency changed
412 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
413 mCpuNum = cpuNum;
414 mCpukHz = cpukHz;
415 // ignore sample for purposes of cycles
416 valid = false;
417 }
418
419 // if no change in CPU number or frequency, then record sample for cycle statistics
420 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700421 const double cycles = wcNs * cpukHz * 0.000001;
422 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800423 }
424
Eric Tan5b13ff82018-07-27 11:20:17 -0700425 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800426 // mCpuUsage.elapsed() is expensive, so don't call it every loop
427 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700428 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800429 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700430 const double perLoop = elapsed / (double) n;
431 const double perLoop100 = perLoop * 0.01;
432 const double perLoop1k = perLoop * 0.001;
433 const double mean = mWcStats.getMean();
434 const double stddev = mWcStats.getStdDev();
435 const double minimum = mWcStats.getMin();
436 const double maximum = mWcStats.getMax();
437 const double meanCycles = mHzStats.getMean();
438 const double stddevCycles = mHzStats.getStdDev();
439 const double minCycles = mHzStats.getMin();
440 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800441 mCpuUsage.resetElapsed();
442 mWcStats.reset();
443 mHzStats.reset();
444 ALOGD("CPU usage for %s over past %.1f secs\n"
445 " (%u mixer loops at %.1f mean ms per loop):\n"
446 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
447 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
448 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
449 title.string(),
450 elapsed * .000000001, n, perLoop * .000001,
451 mean * .001,
452 stddev * .001,
453 minimum * .001,
454 maximum * .001,
455 mean / perLoop100,
456 stddev / perLoop100,
457 minimum / perLoop100,
458 maximum / perLoop100,
459 meanCycles / perLoop1k,
460 stddevCycles / perLoop1k,
461 minCycles / perLoop1k,
462 maxCycles / perLoop1k);
463
464 }
465 }
466#endif
467};
468
469// ----------------------------------------------------------------------------
470// ThreadBase
471// ----------------------------------------------------------------------------
472
Glenn Kasten97b7b752014-09-28 13:04:24 -0700473// static
474const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
475{
476 switch (type) {
477 case MIXER:
478 return "MIXER";
479 case DIRECT:
480 return "DIRECT";
481 case DUPLICATING:
482 return "DUPLICATING";
483 case RECORD:
484 return "RECORD";
485 case OFFLOAD:
486 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800487 case MMAP:
488 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700489 default:
490 return "unknown";
491 }
492}
493
Eric Laurent81784c32012-11-19 14:55:58 -0800494AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -0700495 type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800496 : Thread(false /*canCallJava*/),
497 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700498 mAudioFlinger(audioFlinger),
Andy Hungb68f5eb2019-12-03 16:49:17 -0800499 mMetricsId(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id)),
Glenn Kasten70949c42013-08-06 07:40:12 -0700500 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800501 // are set by PlaybackThread::readOutputParameters_l() or
502 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700503 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700504 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700505 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800506 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700507 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800508 mSystemReady(systemReady),
509 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800510{
Andy Hungb68f5eb2019-12-03 16:49:17 -0800511 mediametrics::LogItem(mMetricsId)
512 .setPid(getpid())
513 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
514 .set(AMEDIAMETRICS_PROP_TYPE, threadTypeToString(type))
515 .set(AMEDIAMETRICS_PROP_THREADID, id)
516 .record();
517
Eric Laurent296fb132015-05-01 11:38:42 -0700518 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800519}
520
521AudioFlinger::ThreadBase::~ThreadBase()
522{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700523 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700524 mConfigEvents.clear();
525
Eric Laurent81784c32012-11-19 14:55:58 -0800526 // do not lock the mutex in destructor
527 releaseWakeLock_l();
528 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800529 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800530 binder->unlinkToDeath(mDeathRecipient);
531 }
Andy Hungd0979812019-02-21 15:51:44 -0800532
533 sendStatistics(true /* force */);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800534
535 mediametrics::LogItem(mMetricsId)
536 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_DTOR)
537 .record();
Eric Laurent81784c32012-11-19 14:55:58 -0800538}
539
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700540status_t AudioFlinger::ThreadBase::readyToRun()
541{
542 status_t status = initCheck();
543 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800544 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700545 } else {
546 ALOGE("No working audio driver found.");
547 }
548 return status;
549}
550
Eric Laurent81784c32012-11-19 14:55:58 -0800551void AudioFlinger::ThreadBase::exit()
552{
553 ALOGV("ThreadBase::exit");
554 // do any cleanup required for exit to succeed
555 preExit();
556 {
557 // This lock prevents the following race in thread (uniprocessor for illustration):
558 // if (!exitPending()) {
559 // // context switch from here to exit()
560 // // exit() calls requestExit(), what exitPending() observes
561 // // exit() calls signal(), which is dropped since no waiters
562 // // context switch back from exit() to here
563 // mWaitWorkCV.wait(...);
564 // // now thread is hung
565 // }
566 AutoMutex lock(mLock);
567 requestExit();
568 mWaitWorkCV.broadcast();
569 }
570 // When Thread::requestExitAndWait is made virtual and this method is renamed to
571 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
572 requestExitAndWait();
573}
574
575status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
576{
Eric Laurent81784c32012-11-19 14:55:58 -0800577 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
578 Mutex::Autolock _l(mLock);
579
Eric Laurent10351942014-05-08 18:49:52 -0700580 return sendSetParameterConfigEvent_l(keyValuePairs);
581}
582
583// sendConfigEvent_l() must be called with ThreadBase::mLock held
584// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
585status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
586{
587 status_t status = NO_ERROR;
588
Eric Laurent72e3f392015-05-20 14:43:50 -0700589 if (event->mRequiresSystemReady && !mSystemReady) {
590 event->mWaitStatus = false;
591 mPendingConfigEvents.add(event);
592 return status;
593 }
Eric Laurent10351942014-05-08 18:49:52 -0700594 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700595 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800596 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700597 mLock.unlock();
598 {
599 Mutex::Autolock _l(event->mLock);
600 while (event->mWaitStatus) {
601 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
602 event->mStatus = TIMED_OUT;
603 event->mWaitStatus = false;
604 }
605 }
606 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800607 }
Eric Laurent10351942014-05-08 18:49:52 -0700608 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800609 return status;
610}
611
Eric Laurent09f1ed22019-04-24 17:45:17 -0700612void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
613 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800614{
615 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700616 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800617}
618
619// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700620void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
621 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800622{
Andy Hungd0979812019-02-21 15:51:44 -0800623 // The audio statistics history is exponentially weighted to forget events
624 // about five or more seconds in the past. In order to have
625 // crisper statistics for mediametrics, we reset the statistics on
626 // an IoConfigEvent, to reflect different properties for a new device.
627 mIoJitterMs.reset();
628 mLatencyMs.reset();
629 mProcessTimeMs.reset();
630 mTimestampVerifier.discontinuity();
631
Eric Laurent09f1ed22019-04-24 17:45:17 -0700632 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700633 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800634}
635
Mikhail Naganov83f04272017-02-07 10:45:09 -0800636void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700637{
638 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800639 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700640}
641
Eric Laurent81784c32012-11-19 14:55:58 -0800642// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800643void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
644 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800645{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800646 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700647 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800648}
649
Eric Laurent10351942014-05-08 18:49:52 -0700650// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
651status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800652{
Andy Hung2ddee192015-12-18 17:34:44 -0800653 sp<ConfigEvent> configEvent;
654 AudioParameter param(keyValuePair);
655 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700656 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800657 setMasterMono_l(value != 0);
658 if (param.size() == 1) {
659 return NO_ERROR; // should be a solo parameter - we don't pass down
660 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700661 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800662 configEvent = new SetParameterConfigEvent(param.toString());
663 } else {
664 configEvent = new SetParameterConfigEvent(keyValuePair);
665 }
Eric Laurent10351942014-05-08 18:49:52 -0700666 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700667}
668
Eric Laurent1c333e22014-05-20 10:48:17 -0700669status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
670 const struct audio_patch *patch,
671 audio_patch_handle_t *handle)
672{
673 Mutex::Autolock _l(mLock);
674 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
675 status_t status = sendConfigEvent_l(configEvent);
676 if (status == NO_ERROR) {
677 CreateAudioPatchConfigEventData *data =
678 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
679 *handle = data->mHandle;
680 }
681 return status;
682}
683
684status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
685 const audio_patch_handle_t handle)
686{
687 Mutex::Autolock _l(mLock);
688 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
689 return sendConfigEvent_l(configEvent);
690}
691
jiabinc52b1ff2019-10-31 17:20:42 -0700692status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
693 const DeviceDescriptorBaseVector& outDevices)
694{
695 if (type() != RECORD) {
696 // The update out device operation is only for record thread.
697 return INVALID_OPERATION;
698 }
699 Mutex::Autolock _l(mLock);
700 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
701 return sendConfigEvent_l(configEvent);
702}
703
Eric Laurent1c333e22014-05-20 10:48:17 -0700704
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700705// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700706void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700707{
Eric Laurent10351942014-05-08 18:49:52 -0700708 bool configChanged = false;
709
Eric Laurent81784c32012-11-19 14:55:58 -0800710 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700711 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700712 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800713 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700714 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700715 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700716 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
717 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800718 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700719 true /*asynchronous*/);
720 if (err != 0) {
721 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700722 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700723 }
724 } break;
725 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700726 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700727 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700728 } break;
729 case CFG_EVENT_SET_PARAMETER: {
730 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
731 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
732 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700733 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
734 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700735 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700736 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700737 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700738 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700739 CreateAudioPatchConfigEventData *data =
740 (CreateAudioPatchConfigEventData *)event->mData.get();
741 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700742 const DeviceTypeSet newDevices = getDeviceTypes();
743 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
744 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
745 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700746 } break;
747 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700748 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700749 ReleaseAudioPatchConfigEventData *data =
750 (ReleaseAudioPatchConfigEventData *)event->mData.get();
751 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700752 const DeviceTypeSet newDevices = getDeviceTypes();
753 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
754 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
755 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
756 } break;
757 case CFG_EVENT_UPDATE_OUT_DEVICE: {
758 UpdateOutDevicesConfigEventData *data =
759 (UpdateOutDevicesConfigEventData *)event->mData.get();
760 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700761 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700762 default:
Eric Laurent10351942014-05-08 18:49:52 -0700763 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700764 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800765 }
Eric Laurent10351942014-05-08 18:49:52 -0700766 {
767 Mutex::Autolock _l(event->mLock);
768 if (event->mWaitStatus) {
769 event->mWaitStatus = false;
770 event->mCond.signal();
771 }
772 }
773 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
774 }
775
776 if (configChanged) {
777 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800778 }
Eric Laurent81784c32012-11-19 14:55:58 -0800779}
780
Marco Nelissenb2208842014-02-07 14:00:50 -0800781String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
782 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700783 const audio_channel_representation_t representation =
784 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700785
786 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800787 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700788 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
789 if (output) {
790 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
791 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
792 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
793 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
794 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
795 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
796 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
797 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
798 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
799 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
800 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
801 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
802 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
803 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
804 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
805 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
806 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
807 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700808 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
809 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800810 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
811 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700812 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
813 } else {
814 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
815 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
816 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
817 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
818 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
819 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
820 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
821 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
822 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
823 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
824 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
825 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700826 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
827 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
828 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
829 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
830 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
831 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700832 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
833 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
834 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
835 }
836 const int len = s.length();
837 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700838 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700839 s.unlockBuffer(len - 2); // remove trailing ", "
840 }
841 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800842 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700843 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
844 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
845 return s;
846 default:
847 s.appendFormat("unknown mask, representation:%d bits:%#x",
848 representation, audio_channel_mask_get_bits(mask));
849 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800850 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800851}
852
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700853void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800854{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800855 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
856 this, mThreadName, getTid(), type(), threadTypeToString(type()));
857
Eric Laurent81784c32012-11-19 14:55:58 -0800858 bool locked = AudioFlinger::dumpTryLock(mLock);
859 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800860 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800861 }
862
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700863 dumpBase_l(fd, args);
864 dumpInternals_l(fd, args);
865 dumpTracks_l(fd, args);
866 dumpEffectChains_l(fd, args);
867
868 if (locked) {
869 mLock.unlock();
870 }
871
872 dprintf(fd, " Local log:\n");
873 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
874}
875
876void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
877{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700878 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700879 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700880 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700881 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700882 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700883 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700884 dprintf(fd, " Channel count: %u\n", mChannelCount);
885 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800886 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700887 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700888 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700889 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800890 size_t numConfig = mConfigEvents.size();
891 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700892 const size_t SIZE = 256;
893 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800894 for (size_t i = 0; i < numConfig; i++) {
895 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700896 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800897 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700898 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800899 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700900 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800901 }
Andy Hung293558a2017-03-21 12:19:20 -0700902 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700903 dprintf(fd, " Output devices: %s (%s)\n",
904 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
905 dprintf(fd, " Input device: %#x (%s)\n",
906 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800907 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800908
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700909 // Dump timestamp statistics for the Thread types that support it.
910 if (mType == RECORD
911 || mType == MIXER
912 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700913 || mType == DIRECT
914 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700915 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700916 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700917 }
918
Andy Hung446f4df2019-02-21 12:26:41 -0800919 if (mLastIoBeginNs > 0) { // MMAP may not set this
920 dprintf(fd, " Last %s occurred (msecs): %lld\n",
921 isOutput() ? "write" : "read",
922 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
923 }
924
925 if (mProcessTimeMs.getN() > 0) {
926 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
927 }
928
929 if (mIoJitterMs.getN() > 0) {
930 dprintf(fd, " Hal %s jitter ms stats: %s\n",
931 isOutput() ? "write" : "read",
932 mIoJitterMs.toString().c_str());
933 }
934
Andy Hunge6c37112019-02-26 17:38:10 -0800935 if (mLatencyMs.getN() > 0) {
936 dprintf(fd, " Threadloop %s latency stats: %s\n",
937 isOutput() ? "write" : "read",
938 mLatencyMs.toString().c_str());
939 }
Eric Laurent81784c32012-11-19 14:55:58 -0800940}
941
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700942void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800943{
944 const size_t SIZE = 256;
945 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800946
Marco Nelissenb2208842014-02-07 14:00:50 -0800947 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000948 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800949 write(fd, buffer, strlen(buffer));
950
Marco Nelissenb2208842014-02-07 14:00:50 -0800951 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800952 sp<EffectChain> chain = mEffectChains[i];
953 if (chain != 0) {
954 chain->dump(fd, args);
955 }
956 }
957}
958
Andy Hungdae27702016-10-31 14:01:16 -0700959void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800960{
961 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700962 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800963}
964
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100965String16 AudioFlinger::ThreadBase::getWakeLockTag()
966{
967 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800968 case MIXER:
969 return String16("AudioMix");
970 case DIRECT:
971 return String16("AudioDirectOut");
972 case DUPLICATING:
973 return String16("AudioDup");
974 case RECORD:
975 return String16("AudioIn");
976 case OFFLOAD:
977 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800978 case MMAP:
979 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800980 default:
981 ALOG_ASSERT(false);
982 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100983 }
984}
985
Andy Hungdae27702016-10-31 14:01:16 -0700986void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800987{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800988 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800989 if (mPowerManager != 0) {
990 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700991 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
992 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700993 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100994 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700995 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700996 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800997 if (status == NO_ERROR) {
998 mWakeLockToken = binder;
999 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001000 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001001 }
Wei Jia3f273d12015-11-24 09:06:49 -08001002
Andy Hung3f0c9022016-01-15 17:49:46 -08001003 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001004 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1005 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001006}
1007
1008void AudioFlinger::ThreadBase::releaseWakeLock()
1009{
1010 Mutex::Autolock _l(mLock);
1011 releaseWakeLock_l();
1012}
1013
1014void AudioFlinger::ThreadBase::releaseWakeLock_l()
1015{
Andy Hung3f0c9022016-01-15 17:49:46 -08001016 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001017 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001018 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001019 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001020 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1021 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001022 }
1023 mWakeLockToken.clear();
1024 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001025}
1026
1027void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001028 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001029 // use checkService() to avoid blocking if power service is not up yet
1030 sp<IBinder> binder =
1031 defaultServiceManager()->checkService(String16("power"));
1032 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001033 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001034 } else {
1035 mPowerManager = interface_cast<IPowerManager>(binder);
1036 binder->linkToDeath(mDeathRecipient);
1037 }
1038 }
1039}
1040
Andy Hungd01b0f12016-11-07 16:10:30 -08001041void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001042 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001043
1044#if !LOG_NDEBUG
1045 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001046 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001047 s << uid << " ";
1048 }
1049 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1050#endif
1051
Andy Hung438e7572015-12-14 15:51:17 -08001052 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1053 if (mSystemReady) {
1054 ALOGE("no wake lock to update, but system ready!");
1055 } else {
1056 ALOGW("no wake lock to update, system not ready yet");
1057 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001058 return;
1059 }
1060 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001061 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
1062 status_t status = mPowerManager->updateWakeLockUids(
1063 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
1064 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001065 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001066 }
1067}
1068
Eric Laurent81784c32012-11-19 14:55:58 -08001069void AudioFlinger::ThreadBase::clearPowerManager()
1070{
1071 Mutex::Autolock _l(mLock);
1072 releaseWakeLock_l();
1073 mPowerManager.clear();
1074}
1075
jiabinc52b1ff2019-10-31 17:20:42 -07001076void AudioFlinger::ThreadBase::updateOutDevices(
1077 const DeviceDescriptorBaseVector& outDevices __unused)
1078{
1079 ALOGE("%s should only be called in RecordThread", __func__);
1080}
1081
Glenn Kasten0f11b512014-01-31 16:18:54 -08001082void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001083{
1084 sp<ThreadBase> thread = mThread.promote();
1085 if (thread != 0) {
1086 thread->clearPowerManager();
1087 }
1088 ALOGW("power manager service died !!!");
1089}
1090
Eric Laurent81784c32012-11-19 14:55:58 -08001091void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001092 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001093{
1094 sp<EffectChain> chain = getEffectChain_l(sessionId);
1095 if (chain != 0) {
1096 if (type != NULL) {
1097 chain->setEffectSuspended_l(type, suspend);
1098 } else {
1099 chain->setEffectSuspendedAll_l(suspend);
1100 }
1101 }
1102
1103 updateSuspendedSessions_l(type, suspend, sessionId);
1104}
1105
1106void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1107{
1108 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1109 if (index < 0) {
1110 return;
1111 }
1112
1113 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1114 mSuspendedSessions.valueAt(index);
1115
1116 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001117 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001118 for (int j = 0; j < desc->mRefCount; j++) {
1119 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1120 chain->setEffectSuspendedAll_l(true);
1121 } else {
1122 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1123 desc->mType.timeLow);
1124 chain->setEffectSuspended_l(&desc->mType, true);
1125 }
1126 }
1127 }
1128}
1129
1130void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1131 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001132 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001133{
1134 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1135
1136 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1137
1138 if (suspend) {
1139 if (index >= 0) {
1140 sessionEffects = mSuspendedSessions.valueAt(index);
1141 } else {
1142 mSuspendedSessions.add(sessionId, sessionEffects);
1143 }
1144 } else {
1145 if (index < 0) {
1146 return;
1147 }
1148 sessionEffects = mSuspendedSessions.valueAt(index);
1149 }
1150
1151
1152 int key = EffectChain::kKeyForSuspendAll;
1153 if (type != NULL) {
1154 key = type->timeLow;
1155 }
1156 index = sessionEffects.indexOfKey(key);
1157
1158 sp<SuspendedSessionDesc> desc;
1159 if (suspend) {
1160 if (index >= 0) {
1161 desc = sessionEffects.valueAt(index);
1162 } else {
1163 desc = new SuspendedSessionDesc();
1164 if (type != NULL) {
1165 desc->mType = *type;
1166 }
1167 sessionEffects.add(key, desc);
1168 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1169 }
1170 desc->mRefCount++;
1171 } else {
1172 if (index < 0) {
1173 return;
1174 }
1175 desc = sessionEffects.valueAt(index);
1176 if (--desc->mRefCount == 0) {
1177 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1178 sessionEffects.removeItemsAt(index);
1179 if (sessionEffects.isEmpty()) {
1180 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1181 sessionId);
1182 mSuspendedSessions.removeItem(sessionId);
1183 }
1184 }
1185 }
1186 if (!sessionEffects.isEmpty()) {
1187 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1188 }
1189}
1190
Eric Laurent6b446ce2019-12-13 10:56:31 -08001191void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1192 audio_session_t sessionId,
1193 bool threadLocked) {
1194 if (!threadLocked) {
1195 mLock.lock();
1196 }
Eric Laurent81784c32012-11-19 14:55:58 -08001197
Eric Laurent81784c32012-11-19 14:55:58 -08001198 if (mType != RECORD) {
1199 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1200 // another session. This gives the priority to well behaved effect control panels
1201 // and applications not using global effects.
1202 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1203 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001204 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001205 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1206 }
1207 }
1208
Eric Laurent6b446ce2019-12-13 10:56:31 -08001209 if (!threadLocked) {
1210 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001211 }
1212}
1213
Eric Laurent4c415062016-06-17 16:14:16 -07001214// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1215status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1216 const effect_descriptor_t *desc, audio_session_t sessionId)
1217{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001218 // No global output effect sessions on record threads
1219 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1220 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001221 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1222 desc->name, mThreadName);
1223 return BAD_VALUE;
1224 }
1225 // only pre processing effects on record thread
1226 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1227 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1228 desc->name, mThreadName);
1229 return BAD_VALUE;
1230 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001231
1232 // always allow effects without processing load or latency
1233 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1234 return NO_ERROR;
1235 }
1236
Eric Laurent4c415062016-06-17 16:14:16 -07001237 audio_input_flags_t flags = mInput->flags;
1238 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1239 if (flags & AUDIO_INPUT_FLAG_RAW) {
1240 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1241 desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1245 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1246 desc->name, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 }
1250 return NO_ERROR;
1251}
1252
1253// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1254status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1255 const effect_descriptor_t *desc, audio_session_t sessionId)
1256{
1257 // no preprocessing on playback threads
1258 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1259 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1260 " thread %s", desc->name, mThreadName);
1261 return BAD_VALUE;
1262 }
1263
Eric Laurent3e4de772017-07-16 16:55:08 -07001264 // always allow effects without processing load or latency
1265 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1266 return NO_ERROR;
1267 }
1268
Eric Laurent4c415062016-06-17 16:14:16 -07001269 switch (mType) {
1270 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001271#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001272 // Reject any effect on mixer multichannel sinks.
1273 // TODO: fix both format and multichannel issues with effects.
1274 if (mChannelCount != FCC_2) {
1275 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1276 " thread %s", desc->name, mChannelCount, mThreadName);
1277 return BAD_VALUE;
1278 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001279#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001280 audio_output_flags_t flags = mOutput->flags;
1281 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1282 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1283 // global effects are applied only to non fast tracks if they are SW
1284 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1285 break;
1286 }
1287 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1288 // only post processing on output stage session
1289 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1290 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1291 " on output stage session", desc->name);
1292 return BAD_VALUE;
1293 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001294 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1295 // only post processing on output stage session
1296 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1297 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1298 " on device session", desc->name);
1299 return BAD_VALUE;
1300 }
Eric Laurent4c415062016-06-17 16:14:16 -07001301 } else {
1302 // no restriction on effects applied on non fast tracks
1303 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1304 break;
1305 }
1306 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001307
Eric Laurent4c415062016-06-17 16:14:16 -07001308 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1309 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1310 desc->name);
1311 return BAD_VALUE;
1312 }
1313 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1314 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1315 " in fast mode", desc->name);
1316 return BAD_VALUE;
1317 }
1318 }
1319 } break;
1320 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001321 // nothing actionable on offload threads, if the effect:
1322 // - is offloadable: the effect can be created
1323 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1324 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001325 break;
1326 case DIRECT:
1327 // Reject any effect on Direct output threads for now, since the format of
1328 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1329 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1330 desc->name, mThreadName);
1331 return BAD_VALUE;
1332 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001333#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001334 // Reject any effect on mixer multichannel sinks.
1335 // TODO: fix both format and multichannel issues with effects.
1336 if (mChannelCount != FCC_2) {
1337 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1338 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1339 return BAD_VALUE;
1340 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001341#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001342 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001343 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1344 " thread %s", desc->name, mThreadName);
1345 return BAD_VALUE;
1346 }
1347 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1348 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1349 " DUPLICATING thread %s", desc->name, mThreadName);
1350 return BAD_VALUE;
1351 }
1352 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1353 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1354 " DUPLICATING thread %s", desc->name, mThreadName);
1355 return BAD_VALUE;
1356 }
1357 break;
1358 default:
1359 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1360 }
1361
1362 return NO_ERROR;
1363}
1364
Eric Laurent81784c32012-11-19 14:55:58 -08001365// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1366sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1367 const sp<AudioFlinger::Client>& client,
1368 const sp<IEffectClient>& effectClient,
1369 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001370 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001371 effect_descriptor_t *desc,
1372 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001373 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001374 bool pinned,
1375 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001376{
1377 sp<EffectModule> effect;
1378 sp<EffectHandle> handle;
1379 status_t lStatus;
1380 sp<EffectChain> chain;
1381 bool chainCreated = false;
1382 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001383 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001384
1385 lStatus = initCheck();
1386 if (lStatus != NO_ERROR) {
1387 ALOGW("createEffect_l() Audio driver not initialized.");
1388 goto Exit;
1389 }
1390
Eric Laurent81784c32012-11-19 14:55:58 -08001391 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1392
1393 { // scope for mLock
1394 Mutex::Autolock _l(mLock);
1395
Eric Laurent4c415062016-06-17 16:14:16 -07001396 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001397 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001398 goto Exit;
1399 }
1400
Eric Laurent81784c32012-11-19 14:55:58 -08001401 // check for existing effect chain with the requested audio session
1402 chain = getEffectChain_l(sessionId);
1403 if (chain == 0) {
1404 // create a new chain for this session
1405 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1406 chain = new EffectChain(this, sessionId);
1407 addEffectChain_l(chain);
1408 chain->setStrategy(getStrategyForSession_l(sessionId));
1409 chainCreated = true;
1410 } else {
1411 effect = chain->getEffectFromDesc_l(desc);
1412 }
1413
1414 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1415
1416 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001417 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001418 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001419 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001420 if (lStatus != NO_ERROR) {
1421 goto Exit;
1422 }
1423 effectCreated = true;
1424
jiabinc52b1ff2019-10-31 17:20:42 -07001425 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001426 effect->setDevices(outDeviceTypeAddrs());
1427 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001428 effect->setMode(mAudioFlinger->getMode());
1429 effect->setAudioSource(mAudioSource);
1430 }
1431 // create effect handle and connect it to effect module
1432 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001433 lStatus = handle->initCheck();
1434 if (lStatus == OK) {
1435 lStatus = effect->addHandle(handle.get());
1436 }
Eric Laurent81784c32012-11-19 14:55:58 -08001437 if (enabled != NULL) {
1438 *enabled = (int)effect->isEnabled();
1439 }
1440 }
1441
1442Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001443 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001444 Mutex::Autolock _l(mLock);
1445 if (effectCreated) {
1446 chain->removeEffect_l(effect);
1447 }
Eric Laurent81784c32012-11-19 14:55:58 -08001448 if (chainCreated) {
1449 removeEffectChain_l(chain);
1450 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001451 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001452 }
1453
Glenn Kasten9156ef32013-08-06 15:39:08 -07001454 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001455 return handle;
1456}
1457
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001458void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1459 bool unpinIfLast)
1460{
1461 bool remove = false;
1462 sp<EffectModule> effect;
1463 {
1464 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001465 sp<EffectBase> effectBase = handle->effect().promote();
1466 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001467 return;
1468 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001469 effect = effectBase->asEffectModule();
1470 if (effect == nullptr) {
1471 return;
1472 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001473 // restore suspended effects if the disconnected handle was enabled and the last one.
1474 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1475 if (remove) {
1476 removeEffect_l(effect, true);
1477 }
1478 }
1479 if (remove) {
1480 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001481 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001482 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001483 }
1484 }
1485}
1486
Eric Laurent6b446ce2019-12-13 10:56:31 -08001487void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
1488 if (mType == OFFLOAD || mType == MMAP) {
1489 Mutex::Autolock _l(mLock);
1490 broadcast_l();
1491 }
1492 if (!effect->isOffloadable()) {
1493 if (mType == ThreadBase::OFFLOAD) {
1494 PlaybackThread *t = (PlaybackThread *)this;
1495 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1496 }
1497 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1498 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1499 }
1500 }
1501}
1502
1503void AudioFlinger::ThreadBase::onEffectDisable() {
1504 if (mType == OFFLOAD || mType == MMAP) {
1505 Mutex::Autolock _l(mLock);
1506 broadcast_l();
1507 }
1508}
1509
Glenn Kastend848eb42016-03-08 13:42:11 -08001510sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1511 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001512{
1513 Mutex::Autolock _l(mLock);
1514 return getEffect_l(sessionId, effectId);
1515}
1516
Glenn Kastend848eb42016-03-08 13:42:11 -08001517sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1518 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001519{
1520 sp<EffectChain> chain = getEffectChain_l(sessionId);
1521 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1522}
1523
Eric Laurent6c796322019-04-09 14:13:17 -07001524std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1525{
1526 sp<EffectChain> chain = getEffectChain_l(sessionId);
1527 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1528}
1529
Eric Laurent81784c32012-11-19 14:55:58 -08001530// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1531// PlaybackThread::mLock held
1532status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1533{
1534 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001535 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001536 sp<EffectChain> chain = getEffectChain_l(sessionId);
1537 bool chainCreated = false;
1538
Eric Laurent5baf2af2013-09-12 17:37:00 -07001539 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001540 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001541 this, effect->desc().name, effect->desc().flags);
1542
Eric Laurent81784c32012-11-19 14:55:58 -08001543 if (chain == 0) {
1544 // create a new chain for this session
1545 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1546 chain = new EffectChain(this, sessionId);
1547 addEffectChain_l(chain);
1548 chain->setStrategy(getStrategyForSession_l(sessionId));
1549 chainCreated = true;
1550 }
1551 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1552
1553 if (chain->getEffectFromId_l(effect->id()) != 0) {
1554 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1555 this, effect->desc().name, chain.get());
1556 return BAD_VALUE;
1557 }
1558
Eric Laurent5baf2af2013-09-12 17:37:00 -07001559 effect->setOffloaded(mType == OFFLOAD, mId);
1560
Eric Laurent81784c32012-11-19 14:55:58 -08001561 status_t status = chain->addEffect_l(effect);
1562 if (status != NO_ERROR) {
1563 if (chainCreated) {
1564 removeEffectChain_l(chain);
1565 }
1566 return status;
1567 }
1568
jiabin8f278ee2019-11-11 12:16:27 -08001569 effect->setDevices(outDeviceTypeAddrs());
1570 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001571 effect->setMode(mAudioFlinger->getMode());
1572 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001573
Eric Laurent81784c32012-11-19 14:55:58 -08001574 return NO_ERROR;
1575}
1576
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001577void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001578
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001579 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001580 effect_descriptor_t desc = effect->desc();
1581 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1582 detachAuxEffect_l(effect->id());
1583 }
1584
Eric Laurent6b446ce2019-12-13 10:56:31 -08001585 sp<EffectChain> chain = effect->callback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001586 if (chain != 0) {
1587 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001588 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001589 removeEffectChain_l(chain);
1590 }
1591 } else {
1592 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1593 }
1594}
1595
1596void AudioFlinger::ThreadBase::lockEffectChains_l(
1597 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1598{
1599 effectChains = mEffectChains;
1600 for (size_t i = 0; i < mEffectChains.size(); i++) {
1601 mEffectChains[i]->lock();
1602 }
1603}
1604
1605void AudioFlinger::ThreadBase::unlockEffectChains(
1606 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1607{
1608 for (size_t i = 0; i < effectChains.size(); i++) {
1609 effectChains[i]->unlock();
1610 }
1611}
1612
Glenn Kastend848eb42016-03-08 13:42:11 -08001613sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001614{
1615 Mutex::Autolock _l(mLock);
1616 return getEffectChain_l(sessionId);
1617}
1618
Glenn Kastend848eb42016-03-08 13:42:11 -08001619sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1620 const
Eric Laurent81784c32012-11-19 14:55:58 -08001621{
1622 size_t size = mEffectChains.size();
1623 for (size_t i = 0; i < size; i++) {
1624 if (mEffectChains[i]->sessionId() == sessionId) {
1625 return mEffectChains[i];
1626 }
1627 }
1628 return 0;
1629}
1630
1631void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1632{
1633 Mutex::Autolock _l(mLock);
1634 size_t size = mEffectChains.size();
1635 for (size_t i = 0; i < size; i++) {
1636 mEffectChains[i]->setMode_l(mode);
1637 }
1638}
1639
Mikhail Naganovdc769682018-05-04 15:34:08 -07001640void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001641{
1642 config->type = AUDIO_PORT_TYPE_MIX;
1643 config->ext.mix.handle = mId;
1644 config->sample_rate = mSampleRate;
1645 config->format = mFormat;
1646 config->channel_mask = mChannelMask;
1647 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1648 AUDIO_PORT_CONFIG_FORMAT;
1649}
1650
Eric Laurent72e3f392015-05-20 14:43:50 -07001651void AudioFlinger::ThreadBase::systemReady()
1652{
1653 Mutex::Autolock _l(mLock);
1654 if (mSystemReady) {
1655 return;
1656 }
1657 mSystemReady = true;
1658
1659 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1660 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1661 }
1662 mPendingConfigEvents.clear();
1663}
1664
Andy Hungdae27702016-10-31 14:01:16 -07001665template <typename T>
1666ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1667 ssize_t index = mActiveTracks.indexOf(track);
1668 if (index >= 0) {
1669 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1670 return index;
1671 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001672 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001673 mActiveTracksGeneration++;
1674 mLatestActiveTrack = track;
1675 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001676 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001677 return mActiveTracks.add(track);
1678}
1679
1680template <typename T>
1681ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1682 ssize_t index = mActiveTracks.remove(track);
1683 if (index < 0) {
1684 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1685 return index;
1686 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001687 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001688 mActiveTracksGeneration++;
1689 --mBatteryCounter[track->uid()].second;
1690 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001691 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001692#ifdef TEE_SINK
1693 track->dumpTee(-1 /* fd */, "_REMOVE");
1694#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001695 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001696 return index;
1697}
1698
1699template <typename T>
1700void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1701 for (const sp<T> &track : mActiveTracks) {
1702 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001703 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001704 }
1705 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001706 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001707 mActiveTracks.clear();
1708 mLatestActiveTrack.clear();
1709 mBatteryCounter.clear();
1710}
1711
1712template <typename T>
1713void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1714 sp<ThreadBase> thread, bool force) {
1715 // Updates ActiveTracks client uids to the thread wakelock.
1716 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1717 thread->updateWakeLockUids_l(getWakeLockUids());
1718 mLastActiveTracksGeneration = mActiveTracksGeneration;
1719 }
1720
1721 // Updates BatteryNotifier uids
1722 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1723 const uid_t uid = it->first;
1724 ssize_t &previous = it->second.first;
1725 ssize_t &current = it->second.second;
1726 if (current > 0) {
1727 if (previous == 0) {
1728 BatteryNotifier::getInstance().noteStartAudio(uid);
1729 }
1730 previous = current;
1731 ++it;
1732 } else if (current == 0) {
1733 if (previous > 0) {
1734 BatteryNotifier::getInstance().noteStopAudio(uid);
1735 }
1736 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1737 } else /* (current < 0) */ {
1738 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1739 }
1740 }
1741}
Eric Laurent83b88082014-06-20 18:31:16 -07001742
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001743template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001744bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1745 const bool hasChanged = mHasChanged;
1746 mHasChanged = false;
1747 return hasChanged;
1748}
1749
1750template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001751void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1752 const char *funcName, const sp<T> &track) const {
1753 if (mLocalLog != nullptr) {
1754 String8 result;
1755 track->appendDump(result, false /* active */);
1756 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1757 }
1758}
1759
Eric Laurent6acd1d42017-01-04 14:23:29 -08001760void AudioFlinger::ThreadBase::broadcast_l()
1761{
1762 // Thread could be blocked waiting for async
1763 // so signal it to handle state changes immediately
1764 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1765 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1766 mSignalPending = true;
1767 mWaitWorkCV.broadcast();
1768}
1769
Andy Hungd0979812019-02-21 15:51:44 -08001770// Call only from threadLoop() or when it is idle.
1771// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1772void AudioFlinger::ThreadBase::sendStatistics(bool force)
1773{
1774 // Do not log if we have no stats.
1775 // We choose the timestamp verifier because it is the most likely item to be present.
1776 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1777 if (nstats == 0) {
1778 return;
1779 }
1780
1781 // Don't log more frequently than once per 12 hours.
1782 // We use BOOTTIME to include suspend time.
1783 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1784 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1785 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1786 return;
1787 }
1788
1789 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1790 mLastRecordedTimeNs = timeNs;
1791
Ray Essickf27e9872019-12-07 06:28:46 -08001792 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001793
1794#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1795
1796 // thread configuration
1797 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1798 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1799 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1800 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1801 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1802 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1803 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001804 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1805 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001806
1807 // thread statistics
1808 if (mIoJitterMs.getN() > 0) {
1809 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1810 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1811 }
1812 if (mProcessTimeMs.getN() > 0) {
1813 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1814 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1815 }
1816 const auto tsjitter = mTimestampVerifier.getJitterMs();
1817 if (tsjitter.getN() > 0) {
1818 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1819 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1820 }
1821 if (mLatencyMs.getN() > 0) {
1822 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1823 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1824 }
1825
1826 item->selfrecord();
1827}
1828
Eric Laurent81784c32012-11-19 14:55:58 -08001829// ----------------------------------------------------------------------------
1830// Playback
1831// ----------------------------------------------------------------------------
1832
1833AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1834 AudioStreamOut* output,
1835 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001836 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001837 bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07001838 : ThreadBase(audioFlinger, id, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001839 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001840 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001841 mMixerBuffer(NULL),
1842 mMixerBufferSize(0),
1843 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1844 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001845 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001846 mEffectBuffer(NULL),
1847 mEffectBufferSize(0),
1848 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1849 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001850 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001851 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001852 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001853 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001854 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001855 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001856 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001857 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001858 mMixerStatus(MIXER_IDLE),
1859 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001860 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001861 mBytesRemaining(0),
1862 mCurrentWriteLength(0),
1863 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001864 mWriteAckSequence(0),
1865 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001866 mScreenState(AudioFlinger::mScreenState),
1867 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001868 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001869 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1870 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001871{
Glenn Kastend7dca052015-03-05 16:05:54 -08001872 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1873 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001874
1875 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1876 // it would be safer to explicitly pass initial masterVolume/masterMute as
1877 // parameter.
1878 //
1879 // If the HAL we are using has support for master volume or master mute,
1880 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1881 // and the mute set to false).
1882 mMasterVolume = audioFlinger->masterVolume_l();
1883 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001884 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001885 if (mOutput->audioHwDev->canSetMasterVolume()) {
1886 mMasterVolume = 1.0;
1887 }
1888
1889 if (mOutput->audioHwDev->canSetMasterMute()) {
1890 mMasterMute = false;
1891 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001892 mIsMsdDevice = strcmp(
1893 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001894 }
1895
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001896 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001897
Andy Hungc8fddf32018-08-08 18:32:37 -07001898 // TODO: We may also match on address as well as device type for
1899 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001900 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001901 // TODO: This property should be ensure that only contains one single device type.
1902 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1903 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001904 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1905 : AUDIO_DEVICE_NONE));
1906 }
1907
Eric Laurent223fd5c2014-11-11 13:43:36 -08001908 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001909 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001910 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001911 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001912 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1913 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001914 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001915 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1916 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001917 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1918 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001919}
1920
1921AudioFlinger::PlaybackThread::~PlaybackThread()
1922{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001923 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001924 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001925 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001926 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001927}
1928
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001929// Thread virtuals
1930
1931void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001932{
jiabinf6eb4c32020-02-25 14:06:25 -08001933 if (mOutput == nullptr || mOutput->stream == nullptr) {
1934 ALOGE("The stream is not open yet"); // This should not happen.
1935 } else {
1936 // setEventCallback will need a strong pointer as a parameter. Calling it
1937 // here instead of constructor of PlaybackThread so that the onFirstRef
1938 // callback would not be made on an incompletely constructed object.
1939 if (mOutput->stream->setEventCallback(this) != OK) {
1940 ALOGE("Failed to add event callback");
1941 }
1942 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001943 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001944}
1945
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001946// ThreadBase virtuals
1947void AudioFlinger::PlaybackThread::preExit()
1948{
1949 ALOGV(" preExit()");
1950 // FIXME this is using hard-coded strings but in the future, this functionality will be
1951 // converted to use audio HAL extensions required to support tunneling
1952 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1953 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1954}
1955
1956void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001957{
Eric Laurent81784c32012-11-19 14:55:58 -08001958 String8 result;
1959
Marco Nelissenb2208842014-02-07 14:00:50 -08001960 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001961 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1962 const stream_type_t *st = &mStreamTypes[i];
1963 if (i > 0) {
1964 result.appendFormat(", ");
1965 }
1966 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1967 if (st->mute) {
1968 result.append("M");
1969 }
1970 }
1971 result.append("\n");
1972 write(fd, result.string(), result.length());
1973 result.clear();
1974
Eric Laurent81784c32012-11-19 14:55:58 -08001975 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1976 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001977 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001978 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001979
1980 size_t numtracks = mTracks.size();
1981 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001982 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001983 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001984 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001985 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001986 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001987 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001988 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001989 for (size_t i = 0; i < numtracks; ++i) {
1990 sp<Track> track = mTracks[i];
1991 if (track != 0) {
1992 bool active = mActiveTracks.indexOf(track) >= 0;
1993 if (active) {
1994 numactiveseen++;
1995 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001996 result.append(prefix);
1997 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001998 }
1999 }
2000 } else {
2001 result.append("\n");
2002 }
2003 if (numactiveseen != numactive) {
2004 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002005 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002006 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002007 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002008 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002009 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002010 sp<Track> track = mActiveTracks[i];
2011 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002012 result.append(prefix);
2013 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002014 }
2015 }
2016 }
2017
2018 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002019}
2020
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002021void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002022{
Andy Hung04cb8f72020-03-20 13:44:33 -07002023 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002024 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002025 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2026 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2027 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2028 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002029 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002030 dprintf(fd, " Total writes: %d\n", mNumWrites);
2031 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2032 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2033 dprintf(fd, " Suspend count: %d\n", mSuspended);
2034 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2035 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2036 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2037 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002038 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002039 AudioStreamOut *output = mOutput;
2040 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002041 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002042 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002043 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2044 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2045 if (mPipeSink.get() != nullptr) {
2046 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2047 }
2048 if (output != nullptr) {
2049 dprintf(fd, " Hal stream dump:\n");
2050 (void)output->stream->dump(fd);
2051 }
Eric Laurent81784c32012-11-19 14:55:58 -08002052}
2053
Eric Laurent81784c32012-11-19 14:55:58 -08002054// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2055sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2056 const sp<AudioFlinger::Client>& client,
2057 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002058 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002059 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002060 audio_format_t format,
2061 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002062 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002063 size_t *pNotificationFrameCount,
2064 uint32_t notificationsPerBuffer,
2065 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002066 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002067 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002068 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002069 pid_t creatorPid,
Eric Laurent81784c32012-11-19 14:55:58 -08002070 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08002071 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002072 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002073 audio_port_handle_t portId,
2074 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002075{
Glenn Kasten74935e42013-12-19 08:56:45 -08002076 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002077 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002078 sp<Track> track;
2079 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002080 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002081 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002082 uint32_t sampleRate;
2083
2084 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2085 lStatus = BAD_VALUE;
2086 goto Exit;
2087 }
Eric Laurent21da6472017-11-09 16:29:26 -08002088
2089 if (*pSampleRate == 0) {
2090 *pSampleRate = mSampleRate;
2091 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002092 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002093
2094 // special case for FAST flag considered OK if fast mixer is present
2095 if (hasFastMixer()) {
2096 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2097 }
2098
2099 // Check if requested flags are compatible with output stream flags
2100 if ((*flags & outputFlags) != *flags) {
2101 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2102 *flags, outputFlags);
2103 *flags = (audio_output_flags_t)(*flags & outputFlags);
2104 }
Eric Laurent81784c32012-11-19 14:55:58 -08002105
Eric Laurent81784c32012-11-19 14:55:58 -08002106 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002107 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002108 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002109 // PCM data
2110 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002111 // TODO: extract as a data library function that checks that a computationally
2112 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002113 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002114 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2115 (channelMask == AUDIO_CHANNEL_OUT_MONO
2116 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002117 // hardware sample rate
2118 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002119 // normal mixer has an associated fast mixer
2120 hasFastMixer() &&
2121 // there are sufficient fast track slots available
2122 (mFastTrackAvailMask != 0)
2123 // FIXME test that MixerThread for this fast track has a capable output HAL
2124 // FIXME add a permission test also?
2125 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002126 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2127 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002128 // read the fast track multiplier property the first time it is needed
2129 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2130 if (ok != 0) {
2131 ALOGE("%s pthread_once failed: %d", __func__, ok);
2132 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002133 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002134 }
Eric Laurent4c415062016-06-17 16:14:16 -07002135
2136 // check compatibility with audio effects.
2137 { // scope for mLock
2138 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002139 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002140 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002141 AUDIO_SESSION_OUTPUT_STAGE,
2142 AUDIO_SESSION_OUTPUT_MIX,
2143 sessionId,
2144 }) {
2145 sp<EffectChain> chain = getEffectChain_l(session);
2146 if (chain.get() != nullptr) {
2147 audio_output_flags_t old = *flags;
2148 chain->checkOutputFlagCompatibility(flags);
2149 if (old != *flags) {
2150 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2151 (int)session, (int)old, (int)*flags);
2152 }
Eric Laurent4c415062016-06-17 16:14:16 -07002153 }
2154 }
2155 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002156 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002157 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2158 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002159 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002160 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2161 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002162 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002163 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002164 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002165 audio_is_linear_pcm(format),
2166 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002167 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002168 }
2169 }
Eric Laurent21da6472017-11-09 16:29:26 -08002170
2171 if (!audio_has_proportional_frames(format)) {
2172 if (sharedBuffer != 0) {
2173 // Same comment as below about ignoring frameCount parameter for set()
2174 frameCount = sharedBuffer->size();
2175 } else if (frameCount == 0) {
2176 frameCount = mNormalFrameCount;
2177 }
2178 if (notificationFrameCount != frameCount) {
2179 notificationFrameCount = frameCount;
2180 }
2181 } else if (sharedBuffer != 0) {
2182 // FIXME: Ensure client side memory buffers need
2183 // not have additional alignment beyond sample
2184 // (e.g. 16 bit stereo accessed as 32 bit frame).
2185 size_t alignment = audio_bytes_per_sample(format);
2186 if (alignment & 1) {
2187 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2188 alignment = 1;
2189 }
2190 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2191 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2192 if (channelCount > 1) {
2193 // More than 2 channels does not require stronger alignment than stereo
2194 alignment <<= 1;
2195 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002196 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002197 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002198 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002199 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002200 goto Exit;
2201 }
Eric Laurent21da6472017-11-09 16:29:26 -08002202
2203 // When initializing a shared buffer AudioTrack via constructors,
2204 // there's no frameCount parameter.
2205 // But when initializing a shared buffer AudioTrack via set(),
2206 // there _is_ a frameCount parameter. We silently ignore it.
2207 frameCount = sharedBuffer->size() / frameSize;
2208 } else {
2209 size_t minFrameCount = 0;
2210 // For fast tracks we try to respect the application's request for notifications per buffer.
2211 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2212 if (notificationsPerBuffer > 0) {
2213 // Avoid possible arithmetic overflow during multiplication.
2214 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2215 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2216 notificationsPerBuffer, mFrameCount);
2217 } else {
2218 minFrameCount = mFrameCount * notificationsPerBuffer;
2219 }
2220 }
2221 } else {
2222 // For normal PCM streaming tracks, update minimum frame count.
2223 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2224 // cover audio hardware latency.
2225 // This is probably too conservative, but legacy application code may depend on it.
2226 // If you change this calculation, also review the start threshold which is related.
2227 uint32_t latencyMs = latency_l();
2228 if (latencyMs == 0) {
2229 ALOGE("Error when retrieving output stream latency");
2230 lStatus = UNKNOWN_ERROR;
2231 goto Exit;
2232 }
2233
2234 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2235 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2236
Eric Laurent81784c32012-11-19 14:55:58 -08002237 }
Eric Laurent21da6472017-11-09 16:29:26 -08002238 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002239 frameCount = minFrameCount;
2240 }
Eric Laurent81784c32012-11-19 14:55:58 -08002241 }
Eric Laurent21da6472017-11-09 16:29:26 -08002242
2243 // Make sure that application is notified with sufficient margin before underrun.
2244 // The client can divide the AudioTrack buffer into sub-buffers,
2245 // and expresses its desire to server as the notification frame count.
2246 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2247 size_t maxNotificationFrames;
2248 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2249 // notify every HAL buffer, regardless of the size of the track buffer
2250 maxNotificationFrames = mFrameCount;
2251 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002252 // Triple buffer the notification period for a triple buffered mixer period;
2253 // otherwise, double buffering for the notification period is fine.
2254 //
2255 // TODO: This should be moved to AudioTrack to modify the notification period
2256 // on AudioTrack::setBufferSizeInFrames() changes.
2257 const int nBuffering =
2258 (uint64_t{frameCount} * mSampleRate)
2259 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2260
Eric Laurent21da6472017-11-09 16:29:26 -08002261 maxNotificationFrames = frameCount / nBuffering;
2262 // If client requested a fast track but this was denied, then use the smaller maximum.
2263 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2264 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2265 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2266 maxNotificationFrames = maxNotificationFramesFastDenied;
2267 }
2268 }
2269 }
2270 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2271 if (notificationFrameCount == 0) {
2272 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2273 maxNotificationFrames, frameCount);
2274 } else {
2275 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2276 notificationFrameCount, maxNotificationFrames, frameCount);
2277 }
2278 notificationFrameCount = maxNotificationFrames;
2279 }
2280 }
2281
Glenn Kasten74935e42013-12-19 08:56:45 -08002282 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002283 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002284
Glenn Kastenc3df8382014-03-13 15:05:25 -07002285 switch (mType) {
2286
2287 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002288 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002289 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002290 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2291 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002292 sampleRate, format, channelMask, mOutput, mFormat);
2293 lStatus = BAD_VALUE;
2294 goto Exit;
2295 }
2296 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002297 break;
2298
2299 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002300 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002301 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2302 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002303 sampleRate, format, channelMask, mOutput, mFormat);
2304 lStatus = BAD_VALUE;
2305 goto Exit;
2306 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002307 break;
2308
2309 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002310 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002311 ALOGE("createTrack_l() Bad parameter: format %#x \""
2312 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002313 format, mOutput, mFormat);
2314 lStatus = BAD_VALUE;
2315 goto Exit;
2316 }
Andy Hungcd044842014-08-07 11:04:34 -07002317 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002318 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2319 lStatus = BAD_VALUE;
2320 goto Exit;
2321 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002322 break;
2323
Eric Laurent81784c32012-11-19 14:55:58 -08002324 }
2325
2326 lStatus = initCheck();
2327 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002328 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002329 goto Exit;
2330 }
2331
2332 { // scope for mLock
2333 Mutex::Autolock _l(mLock);
2334
2335 // all tracks in same audio session must share the same routing strategy otherwise
2336 // conflicts will happen when tracks are moved from one output to another by audio policy
2337 // manager
2338 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2339 for (size_t i = 0; i < mTracks.size(); ++i) {
2340 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002341 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002342 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2343 if (sessionId == t->sessionId() && strategy != actual) {
2344 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2345 strategy, actual);
2346 lStatus = BAD_VALUE;
2347 goto Exit;
2348 }
2349 }
2350 }
2351
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002352 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002353 channelMask, frameCount,
2354 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002355 sessionId, creatorPid, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002356
Glenn Kasten03003332013-08-06 15:40:54 -07002357 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2358 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002359 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002360 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002361 goto Exit;
2362 }
2363 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002364 {
2365 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2366 if (callback.get() != nullptr) {
2367 mAudioTrackCallbacks.emplace(callback);
2368 }
2369 }
Eric Laurent81784c32012-11-19 14:55:58 -08002370
2371 sp<EffectChain> chain = getEffectChain_l(sessionId);
2372 if (chain != 0) {
2373 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2374 track->setMainBuffer(chain->inBuffer());
2375 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2376 chain->incTrackCnt();
2377 }
2378
Eric Laurent05067782016-06-01 18:27:28 -07002379 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002380 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2381 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2382 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002383 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002384 }
2385 }
2386
2387 lStatus = NO_ERROR;
2388
2389Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002390 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002391 return track;
2392}
2393
Andy Hung1bc088a2018-02-09 15:57:31 -08002394template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002395ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2396{
Andy Hungc0691382018-09-12 18:01:57 -07002397 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002398 const ssize_t index = mTracks.remove(track);
2399 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002400 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002401 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002402 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002403 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002404 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002405 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002406 }
2407 return index;
2408}
2409
Eric Laurent81784c32012-11-19 14:55:58 -08002410uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2411{
2412 return latency;
2413}
2414
2415uint32_t AudioFlinger::PlaybackThread::latency() const
2416{
2417 Mutex::Autolock _l(mLock);
2418 return latency_l();
2419}
2420uint32_t AudioFlinger::PlaybackThread::latency_l() const
2421{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002422 uint32_t latency;
2423 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2424 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002425 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002426 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002427}
2428
2429void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2430{
2431 Mutex::Autolock _l(mLock);
2432 // Don't apply master volume in SW if our HAL can do it for us.
2433 if (mOutput && mOutput->audioHwDev &&
2434 mOutput->audioHwDev->canSetMasterVolume()) {
2435 mMasterVolume = 1.0;
2436 } else {
2437 mMasterVolume = value;
2438 }
2439}
2440
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002441void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2442{
2443 mMasterBalance.store(balance);
2444}
2445
Eric Laurent81784c32012-11-19 14:55:58 -08002446void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2447{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002448 if (isDuplicating()) {
2449 return;
2450 }
Eric Laurent81784c32012-11-19 14:55:58 -08002451 Mutex::Autolock _l(mLock);
2452 // Don't apply master mute in SW if our HAL can do it for us.
2453 if (mOutput && mOutput->audioHwDev &&
2454 mOutput->audioHwDev->canSetMasterMute()) {
2455 mMasterMute = false;
2456 } else {
2457 mMasterMute = muted;
2458 }
2459}
2460
2461void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2462{
2463 Mutex::Autolock _l(mLock);
2464 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002465 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002466}
2467
2468void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2469{
2470 Mutex::Autolock _l(mLock);
2471 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002472 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002473}
2474
2475float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2476{
2477 Mutex::Autolock _l(mLock);
2478 return mStreamTypes[stream].volume;
2479}
2480
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002481void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2482{
2483 mOutput->stream->setVolume(left, right);
2484}
2485
Eric Laurent81784c32012-11-19 14:55:58 -08002486// addTrack_l() must be called with ThreadBase::mLock held
2487status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2488{
2489 status_t status = ALREADY_EXISTS;
2490
Eric Laurent81784c32012-11-19 14:55:58 -08002491 if (mActiveTracks.indexOf(track) < 0) {
2492 // the track is newly added, make sure it fills up all its
2493 // buffers before playing. This is to ensure the client will
2494 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002495 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002496 TrackBase::track_state state = track->mState;
2497 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002498 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002499 mLock.lock();
2500 // abort track was stopped/paused while we released the lock
2501 if (state != track->mState) {
2502 if (status == NO_ERROR) {
2503 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002504 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002505 mLock.lock();
2506 }
2507 return INVALID_OPERATION;
2508 }
2509 // abort if start is rejected by audio policy manager
2510 if (status != NO_ERROR) {
2511 return PERMISSION_DENIED;
2512 }
2513#ifdef ADD_BATTERY_DATA
2514 // to track the speaker usage
2515 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2516#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002517 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002518 }
2519
Eric Laurent51716182016-02-29 18:00:56 -08002520 // set retry count for buffer fill
2521 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002522 if (track->isStopping_1()) {
2523 track->mRetryCount = kMaxTrackStopRetriesOffload;
2524 } else {
2525 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2526 }
2527 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002528 } else {
2529 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002530 track->mFillingUpStatus =
2531 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002532 }
2533
jiabin245cdd92018-12-07 17:55:15 -08002534 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2535 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002536 // Unlock due to VibratorService will lock for this call and will
2537 // call Tracks.mute/unmute which also require thread's lock.
2538 mLock.unlock();
2539 const int intensity = AudioFlinger::onExternalVibrationStart(
2540 track->getExternalVibration());
2541 mLock.lock();
jiabinbf6b0ec2019-02-12 12:30:12 -08002542 track->setHapticIntensity(static_cast<AudioMixer::haptic_intensity_t>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002543 // Haptic playback should be enabled by vibrator service.
2544 if (track->getHapticPlaybackEnabled()) {
2545 // Disable haptic playback of all active track to ensure only
2546 // one track playing haptic if current track should play haptic.
2547 for (const auto &t : mActiveTracks) {
2548 t->setHapticPlaybackEnabled(false);
2549 }
jiabin245cdd92018-12-07 17:55:15 -08002550 }
jiabin245cdd92018-12-07 17:55:15 -08002551 }
2552
Eric Laurent81784c32012-11-19 14:55:58 -08002553 track->mResetDone = false;
2554 track->mPresentationCompleteFrames = 0;
2555 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002556 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2557 if (chain != 0) {
2558 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2559 track->sessionId());
2560 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002561 }
2562
Andy Hungc2b11cb2020-04-22 09:04:01 -07002563 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002564 status = NO_ERROR;
2565 }
2566
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002567 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002568 return status;
2569}
2570
Eric Laurentbfb1b832013-01-07 09:53:42 -08002571bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002572{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002573 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002574 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002575 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2576 track->mState = TrackBase::STOPPED;
2577 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002578 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002579 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002580 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002581 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002582
2583 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002584}
2585
2586void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2587{
2588 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002589
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002590 String8 result;
2591 track->appendDump(result, false /* active */);
2592 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002593
Eric Laurent81784c32012-11-19 14:55:58 -08002594 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002595 if (track->isFastTrack()) {
2596 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002597 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002598 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2599 mFastTrackAvailMask |= 1 << index;
2600 // redundant as track is about to be destroyed, for dumpsys only
2601 track->mFastIndex = -1;
2602 }
2603 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2604 if (chain != 0) {
2605 chain->decTrackCnt();
2606 }
2607}
2608
2609String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2610{
Eric Laurent81784c32012-11-19 14:55:58 -08002611 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002612 String8 out_s8;
2613 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2614 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002615 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002616 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002617}
2618
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002619status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2620 Mutex::Autolock _l(mLock);
2621 if (mOutput == nullptr || mOutput->stream == nullptr) {
2622 return NO_INIT;
2623 }
2624 return mOutput->stream->selectPresentation(presentationId, programId);
2625}
2626
Eric Laurent09f1ed22019-04-24 17:45:17 -07002627void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2628 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002629 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2630 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002631
Eric Laurent73e26b62015-04-27 16:55:58 -07002632 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002633
2634 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002635 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002636 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002637 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002638 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002639 desc->mChannelMask = mChannelMask;
2640 desc->mSamplingRate = mSampleRate;
2641 desc->mFormat = mFormat;
2642 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002643 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002644 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002645 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002646 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002647 case AUDIO_CLIENT_STARTED:
2648 desc->mPatch = mPatch;
2649 desc->mPortId = portId;
2650 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002651 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002652 default:
2653 break;
2654 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002655 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002656}
2657
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002658void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002660 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002661}
2662
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002663void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002665 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666}
2667
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002668void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002669{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002670 mCallbackThread->setAsyncError();
2671}
2672
jiabinf6eb4c32020-02-25 14:06:25 -08002673void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2674 const std::basic_string<uint8_t>& metadataBs)
2675{
2676 std::thread([this, metadataBs]() {
2677 audio_utils::metadata::Data metadata =
2678 audio_utils::metadata::dataFromByteString(metadataBs);
2679 if (metadata.empty()) {
2680 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2681 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2682 (int)metadataBs.size());
2683 return;
2684 }
2685
2686 audio_utils::metadata::ByteString metaDataStr =
2687 audio_utils::metadata::byteStringFromData(metadata);
2688 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2689 Mutex::Autolock _l(mAudioTrackCbLock);
2690 for (const auto& callback : mAudioTrackCallbacks) {
2691 callback->onCodecFormatChanged(metadataVec);
2692 }
2693 }).detach();
2694}
2695
Eric Laurent3b4529e2013-09-05 18:09:19 -07002696void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002697{
2698 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002699 // reject out of sequence requests
2700 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2701 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002702 mWaitWorkCV.signal();
2703 }
2704}
2705
Eric Laurent3b4529e2013-09-05 18:09:19 -07002706void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002707{
2708 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002709 // reject out of sequence requests
2710 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002711 // Register discontinuity when HW drain is completed because that can cause
2712 // the timestamp frame position to reset to 0 for direct and offload threads.
2713 // (Out of sequence requests are ignored, since the discontinuity would be handled
2714 // elsewhere, e.g. in flush).
2715 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002716 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002717 mWaitWorkCV.signal();
2718 }
2719}
2720
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002721void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002722{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002723 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002724 mSampleRate = mOutput->getSampleRate();
2725 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002726 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002727 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002728 }
Andy Hung9a592762014-07-21 21:56:01 -07002729 if ((mType == MIXER || mType == DUPLICATING)
2730 && !isValidPcmSinkChannelMask(mChannelMask)) {
2731 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2732 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002733 }
Andy Hunge5412692014-05-16 11:25:07 -07002734 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002735 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002736
2737 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002738 status_t result = mOutput->stream->getFormat(&mHALFormat);
2739 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002740 // Get format from the shim, which will be different than the HAL format
2741 // if playing compressed audio over HDMI passthrough.
2742 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002743 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002744 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002745 }
Andy Hung6146c082014-03-18 11:56:15 -07002746 if ((mType == MIXER || mType == DUPLICATING)
2747 && !isValidPcmSinkFormat(mFormat)) {
2748 LOG_FATAL("HAL format %#x not supported for mixed output",
2749 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002750 }
Phil Burk062e67a2015-02-11 13:40:50 -08002751 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002752 result = mOutput->stream->getBufferSize(&mBufferSize);
2753 LOG_ALWAYS_FATAL_IF(result != OK,
2754 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002755 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002756 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002757 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002758 mFrameCount);
2759 }
2760
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002761 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2762 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002763 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002764 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002765 }
2766 }
2767
Eric Laurentd1f69b02014-12-15 14:33:13 -08002768 mHwSupportsPause = false;
2769 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002770 bool supportsPause = false, supportsResume = false;
2771 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2772 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002773 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002774 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002775 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002776 } else if (supportsResume) {
2777 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002778 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002779 }
2780 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002781 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2782 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2783 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002784
Andy Hungfbfc3952015-01-15 13:33:51 -08002785 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2786 // For best precision, we use float instead of the associated output
2787 // device format (typically PCM 16 bit).
2788
2789 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2790 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2791 mBufferSize = mFrameSize * mFrameCount;
2792
2793 // TODO: We currently use the associated output device channel mask and sample rate.
2794 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2795 // (if a valid mask) to avoid premature downmix.
2796 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2797 // instead of the output device sample rate to avoid loss of high frequency information.
2798 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2799 }
2800
Andy Hung09a50072014-02-27 14:30:47 -08002801 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002802 double multiplier = 1.0;
2803 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2804 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002805 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2806 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002807
Eric Laurent81784c32012-11-19 14:55:58 -08002808 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2809 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2810 maxNormalFrameCount = maxNormalFrameCount & ~15;
2811 if (maxNormalFrameCount < minNormalFrameCount) {
2812 maxNormalFrameCount = minNormalFrameCount;
2813 }
2814 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2815 if (multiplier <= 1.0) {
2816 multiplier = 1.0;
2817 } else if (multiplier <= 2.0) {
2818 if (2 * mFrameCount <= maxNormalFrameCount) {
2819 multiplier = 2.0;
2820 } else {
2821 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2822 }
2823 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002824 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002825 }
2826 }
2827 mNormalFrameCount = multiplier * mFrameCount;
2828 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002829 if (mType == MIXER || mType == DUPLICATING) {
2830 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2831 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002832 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002833 mNormalFrameCount);
2834
Andy Hung08fb1742015-05-31 23:22:10 -07002835 // Check if we want to throttle the processing to no more than 2x normal rate
2836 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002837 mThreadThrottleTimeMs = 0;
2838 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002839 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2840
Andy Hung010a1a12014-03-13 13:57:33 -07002841 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2842 // Originally this was int16_t[] array, need to remove legacy implications.
2843 free(mSinkBuffer);
2844 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002845 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2846 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2847 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002848 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002849
Andy Hung69aed5f2014-02-25 17:24:40 -08002850 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2851 // drives the output.
2852 free(mMixerBuffer);
2853 mMixerBuffer = NULL;
2854 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002855 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002856 mMixerBufferSize = mNormalFrameCount * mChannelCount
2857 * audio_bytes_per_sample(mMixerBufferFormat);
2858 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2859 }
Andy Hung98ef9782014-03-04 14:46:50 -08002860 free(mEffectBuffer);
2861 mEffectBuffer = NULL;
2862 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002863 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002864 mEffectBufferSize = mNormalFrameCount * mChannelCount
2865 * audio_bytes_per_sample(mEffectBufferFormat);
2866 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2867 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002868
jiabin245cdd92018-12-07 17:55:15 -08002869 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2870 mChannelMask &= ~mHapticChannelMask;
2871 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2872 mChannelCount -= mHapticChannelCount;
2873
Eric Laurent81784c32012-11-19 14:55:58 -08002874 // force reconfiguration of effect chains and engines to take new buffer size and audio
2875 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002876 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002877 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2878 // matter.
2879 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2880 Vector< sp<EffectChain> > effectChains = mEffectChains;
2881 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002882 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2883 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002884 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002885
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002886 audio_output_flags_t flags = mOutput->flags;
Andy Hungb68f5eb2019-12-03 16:49:17 -08002887 mediametrics::LogItem item(mMetricsId);
2888 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2889 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2890 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2891 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2892 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2893 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2894 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2895 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2896 (int32_t)mHapticChannelMask)
2897 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2898 (int32_t)mHapticChannelCount)
2899 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2900 formatToString(mHALFormat).c_str())
2901 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2902 (int32_t)mFrameCount) // sic - added HAL
2903 ;
2904 uint32_t latencyMs;
2905 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2906 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2907 }
2908 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08002909}
2910
Kevin Rocard069c2712018-03-29 19:09:14 -07002911void AudioFlinger::PlaybackThread::updateMetadata_l()
2912{
Kevin Rocard12381092018-04-11 09:19:59 -07002913 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2914 return; // That should not happen
2915 }
2916 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2917 for (const sp<Track> &track : mActiveTracks) {
2918 // Do not short-circuit as all hasChanged states must be reset
2919 // as all the metadata are going to be sent
2920 hasChanged |= track->readAndClearHasChanged();
2921 }
2922 if (!hasChanged) {
2923 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002924 }
2925 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002926 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002927 for (const sp<Track> &track : mActiveTracks) {
2928 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002929 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002930 }
Kevin Rocard12381092018-04-11 09:19:59 -07002931 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002932}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002933
Kevin Rocard12381092018-04-11 09:19:59 -07002934void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2935 const StreamOutHalInterface::SourceMetadata& metadata)
2936{
2937 mOutput->stream->updateSourceMetadata(metadata);
2938};
2939
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002940status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002941{
2942 if (halFrames == NULL || dspFrames == NULL) {
2943 return BAD_VALUE;
2944 }
2945 Mutex::Autolock _l(mLock);
2946 if (initCheck() != NO_ERROR) {
2947 return INVALID_OPERATION;
2948 }
Andy Hung818e7a32016-02-16 18:08:07 -08002949 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002950 *halFrames = framesWritten;
2951
2952 if (isSuspended()) {
2953 // return an estimation of rendered frames when the output is suspended
2954 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002955 *dspFrames = (uint32_t)
2956 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002957 return NO_ERROR;
2958 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002959 status_t status;
2960 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002961 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002962 *dspFrames = (size_t)frames;
2963 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002964 }
2965}
2966
Glenn Kastend848eb42016-03-08 13:42:11 -08002967uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002968{
2969 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2970 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2971 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2972 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2973 }
2974 for (size_t i = 0; i < mTracks.size(); i++) {
2975 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002976 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002977 return AudioSystem::getStrategyForStream(track->streamType());
2978 }
2979 }
2980 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2981}
2982
2983
Phil Burk062e67a2015-02-11 13:40:50 -08002984AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002985{
2986 Mutex::Autolock _l(mLock);
2987 return mOutput;
2988}
2989
Phil Burk062e67a2015-02-11 13:40:50 -08002990AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002991{
2992 Mutex::Autolock _l(mLock);
2993 AudioStreamOut *output = mOutput;
2994 mOutput = NULL;
2995 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2996 // must push a NULL and wait for ack
2997 mOutputSink.clear();
2998 mPipeSink.clear();
2999 mNormalSink.clear();
3000 return output;
3001}
3002
3003// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003004sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003005{
3006 if (mOutput == NULL) {
3007 return NULL;
3008 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003009 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003010}
3011
3012uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3013{
3014 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3015}
3016
3017status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3018{
3019 if (!isValidSyncEvent(event)) {
3020 return BAD_VALUE;
3021 }
3022
3023 Mutex::Autolock _l(mLock);
3024
3025 for (size_t i = 0; i < mTracks.size(); ++i) {
3026 sp<Track> track = mTracks[i];
3027 if (event->triggerSession() == track->sessionId()) {
3028 (void) track->setSyncEvent(event);
3029 return NO_ERROR;
3030 }
3031 }
3032
3033 return NAME_NOT_FOUND;
3034}
3035
3036bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3037{
3038 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3039}
3040
3041void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3042 const Vector< sp<Track> >& tracksToRemove)
3043{
Andy Hungfe726a62018-09-27 15:17:25 -07003044 // Miscellaneous track cleanup when removed from the active list,
3045 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003046#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003047 for (const auto& track : tracksToRemove) {
3048 if (track->isExternalTrack()) {
3049 // to track the speaker usage
3050 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003051 }
3052 }
Andy Hungfe726a62018-09-27 15:17:25 -07003053#else
3054 (void)tracksToRemove; // suppress unused warning
3055#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003056}
3057
3058void AudioFlinger::PlaybackThread::checkSilentMode_l()
3059{
3060 if (!mMasterMute) {
3061 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003062 if (mOutDeviceTypeAddrs.empty()) {
3063 ALOGD("ro.audio.silent is ignored since no output device is set");
3064 return;
3065 }
jiabinc52b1ff2019-10-31 17:20:42 -07003066 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003067 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3068 return;
3069 }
Eric Laurent81784c32012-11-19 14:55:58 -08003070 if (property_get("ro.audio.silent", value, "0") > 0) {
3071 char *endptr;
3072 unsigned long ul = strtoul(value, &endptr, 0);
3073 if (*endptr == '\0' && ul != 0) {
3074 ALOGD("Silence is golden");
3075 // The setprop command will not allow a property to be changed after
3076 // the first time it is set, so we don't have to worry about un-muting.
3077 setMasterMute_l(true);
3078 }
3079 }
3080 }
3081}
3082
3083// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003084ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003085{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003086 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003087 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003088 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003089 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003090
3091 // If an NBAIO sink is present, use it to write the normal mixer's submix
3092 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003093
Andy Hung010a1a12014-03-13 13:57:33 -07003094 const size_t count = mBytesRemaining / mFrameSize;
3095
Simon Wilson2d590962012-11-29 15:18:50 -08003096 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003097 // update the setpoint when AudioFlinger::mScreenState changes
3098 uint32_t screenState = AudioFlinger::mScreenState;
3099 if (screenState != mScreenState) {
3100 mScreenState = screenState;
3101 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3102 if (pipe != NULL) {
3103 pipe->setAvgFrames((mScreenState & 1) ?
3104 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3105 }
3106 }
Andy Hung010a1a12014-03-13 13:57:33 -07003107 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003108 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003109 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003110 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003111#ifdef TEE_SINK
3112 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3113#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003114 } else {
3115 bytesWritten = framesWritten;
3116 }
3117 // otherwise use the HAL / AudioStreamOut directly
3118 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003119 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003120
Eric Laurentbfb1b832013-01-07 09:53:42 -08003121 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003122 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3123 mWriteAckSequence += 2;
3124 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003125 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003126 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003127 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003128 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003129 // FIXME We should have an implementation of timestamps for direct output threads.
3130 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003131 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003132 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003133
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134 if (mUseAsyncWrite &&
3135 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3136 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003137 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003138 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003139 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003140 }
Eric Laurent81784c32012-11-19 14:55:58 -08003141 }
3142
Eric Laurent81784c32012-11-19 14:55:58 -08003143 mNumWrites++;
3144 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07003145 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003146 return bytesWritten;
3147}
3148
3149void AudioFlinger::PlaybackThread::threadLoop_drain()
3150{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003151 bool supportsDrain = false;
3152 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003153 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3154 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003155 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3156 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003157 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003158 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003159 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003160 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003161 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162 }
3163}
3164
3165void AudioFlinger::PlaybackThread::threadLoop_exit()
3166{
Eric Laurent275e8e92014-11-30 15:14:47 -08003167 {
3168 Mutex::Autolock _l(mLock);
3169 for (size_t i = 0; i < mTracks.size(); i++) {
3170 sp<Track> track = mTracks[i];
3171 track->invalidate();
3172 }
Andy Hungdae27702016-10-31 14:01:16 -07003173 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3174 // After we exit there are no more track changes sent to BatteryNotifier
3175 // because that requires an active threadLoop.
3176 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3177 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003178 }
Eric Laurent81784c32012-11-19 14:55:58 -08003179}
3180
3181/*
3182The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003183 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003184 - mActiveSleepTimeUs from activeSleepTimeUs()
3185 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003186 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3187 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003188 - maxPeriod from frame count and sample rate (MIXER only)
3189
3190The parameters that affect these derived values are:
3191 - frame count
3192 - frame size
3193 - sample rate
3194 - device type: A2DP or not
3195 - device latency
3196 - format: PCM or not
3197 - active sleep time
3198 - idle sleep time
3199*/
3200
3201void AudioFlinger::PlaybackThread::cacheParameters_l()
3202{
Andy Hung25c2dac2014-02-27 14:56:00 -08003203 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003204 mActiveSleepTimeUs = activeSleepTimeUs();
3205 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003206
3207 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3208 // truncating audio when going to standby.
3209 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003210 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003211 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3212 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3213 }
3214 }
Eric Laurent81784c32012-11-19 14:55:58 -08003215}
3216
Eric Laurent13084622016-05-17 10:51:49 -07003217bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003218{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003219 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003220 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003221 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003222 size_t size = mTracks.size();
3223 for (size_t i = 0; i < size; i++) {
3224 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003225 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003226 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003227 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003228 }
3229 }
Eric Laurent13084622016-05-17 10:51:49 -07003230 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003231}
3232
Haynes Mathew George05317d22016-05-03 16:34:26 -07003233void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3234{
3235 Mutex::Autolock _l(mLock);
3236 invalidateTracks_l(streamType);
3237}
3238
Eric Laurent81784c32012-11-19 14:55:58 -08003239status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3240{
Glenn Kastend848eb42016-03-08 13:42:11 -08003241 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003242 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003243 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003244 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3245 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3246 &halInBuffer);
3247 if (result != OK) return result;
3248 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003249 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003250 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003251 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003252 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003253 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003254 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003255 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003256 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003257 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003258 &halInBuffer);
3259 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003260#ifdef FLOAT_EFFECT_CHAIN
3261 buffer = halInBuffer->audioBuffer()->f32;
3262#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003263 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003264#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003265 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3266 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003267 }
3268
3269 // Attach all tracks with same session ID to this chain.
3270 for (size_t i = 0; i < mTracks.size(); ++i) {
3271 sp<Track> track = mTracks[i];
3272 if (session == track->sessionId()) {
3273 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3274 buffer);
3275 track->setMainBuffer(buffer);
3276 chain->incTrackCnt();
3277 }
3278 }
3279
3280 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003281 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003282 if (session == track->sessionId()) {
3283 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3284 chain->incActiveTrackCnt();
3285 }
3286 }
3287 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003288 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003289 chain->setInBuffer(halInBuffer);
3290 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003291 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3292 // chains list in order to be processed last as it contains output device effects.
3293 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3294 // processing effects specific to an output stream before effects applied to all streams
3295 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003296 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3297 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003298 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003299 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003300 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003301 // Effect chain for other sessions are inserted at beginning of effect
3302 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003303 // sessions is not important.
3304 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003305 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3306 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003307 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003308 size_t size = mEffectChains.size();
3309 size_t i = 0;
3310 for (i = 0; i < size; i++) {
3311 if (mEffectChains[i]->sessionId() < session) {
3312 break;
3313 }
3314 }
3315 mEffectChains.insertAt(chain, i);
3316 checkSuspendOnAddEffectChain_l(chain);
3317
3318 return NO_ERROR;
3319}
3320
3321size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3322{
Glenn Kastend848eb42016-03-08 13:42:11 -08003323 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003324
3325 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3326
3327 for (size_t i = 0; i < mEffectChains.size(); i++) {
3328 if (chain == mEffectChains[i]) {
3329 mEffectChains.removeAt(i);
3330 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003331 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003332 if (session == track->sessionId()) {
3333 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3334 chain.get(), session);
3335 chain->decActiveTrackCnt();
3336 }
3337 }
3338
3339 // detach all tracks with same session ID from this chain
3340 for (size_t i = 0; i < mTracks.size(); ++i) {
3341 sp<Track> track = mTracks[i];
3342 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003343 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003344 chain->decTrackCnt();
3345 }
3346 }
3347 break;
3348 }
3349 }
3350 return mEffectChains.size();
3351}
3352
3353status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003354 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003355{
3356 Mutex::Autolock _l(mLock);
3357 return attachAuxEffect_l(track, EffectId);
3358}
3359
3360status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003361 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003362{
3363 status_t status = NO_ERROR;
3364
3365 if (EffectId == 0) {
3366 track->setAuxBuffer(0, NULL);
3367 } else {
3368 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3369 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3370 if (effect != 0) {
3371 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3372 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3373 } else {
3374 status = INVALID_OPERATION;
3375 }
3376 } else {
3377 status = BAD_VALUE;
3378 }
3379 }
3380 return status;
3381}
3382
3383void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3384{
3385 for (size_t i = 0; i < mTracks.size(); ++i) {
3386 sp<Track> track = mTracks[i];
3387 if (track->auxEffectId() == effectId) {
3388 attachAuxEffect_l(track, 0);
3389 }
3390 }
3391}
3392
3393bool AudioFlinger::PlaybackThread::threadLoop()
3394{
Glenn Kasten388d5712017-04-07 14:38:41 -07003395 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003396
Eric Laurent81784c32012-11-19 14:55:58 -08003397 Vector< sp<Track> > tracksToRemove;
3398
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003399 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003400 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
3401 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003402
3403 // MIXER
3404 nsecs_t lastWarning = 0;
3405
3406 // DUPLICATING
3407 // FIXME could this be made local to while loop?
3408 writeFrames = 0;
3409
3410 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003411 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003412
3413 if (mType == MIXER) {
3414 sleepTimeShift = 0;
3415 }
3416
3417 CpuStats cpuStats;
3418 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3419
3420 acquireWakeLock();
3421
Glenn Kasteneef598c2017-04-03 14:41:13 -07003422 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3423 // thread associated with this PlaybackThread.
3424 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3425 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003426 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3427 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003428 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003429 const char *logString = NULL;
3430
rago1bb90822017-05-02 18:31:48 -07003431 // Estimated time for next buffer to be written to hal. This is used only on
3432 // suspended mode (for now) to help schedule the wait time until next iteration.
3433 nsecs_t timeLoopNextNs = 0;
3434
Eric Laurent664539d2013-09-23 18:24:31 -07003435 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003436
Andy Hungf3234512018-07-03 14:51:47 -07003437 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3438 // TODO: add confirmation checks:
3439 // 1) DIRECT threads and linear PCM format really resets to 0?
3440 // 2) Is frame count really valid if not linear pcm?
3441 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3442 if (mType == OFFLOAD || mType == DIRECT) {
3443 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3444 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003445 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003446
Andy Hung446f4df2019-02-21 12:26:41 -08003447 // loopCount is used for statistics and diagnostics.
3448 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003449 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003450 // Log merge requests are performed during AudioFlinger binder transactions, but
3451 // that does not cover audio playback. It's requested here for that reason.
3452 mAudioFlinger->requestLogMerge();
3453
Eric Laurent81784c32012-11-19 14:55:58 -08003454 cpuStats.sample(myName);
3455
3456 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003457 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003458 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003459
Andy Hung2dbffc22018-08-08 18:50:41 -07003460 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3461 //
jiabinc52b1ff2019-10-31 17:20:42 -07003462 // Note: we access outDeviceTypes() outside of mLock.
3463 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003464 // Here, we try for the AF lock, but do not block on it as the latency
3465 // is more informational.
3466 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3467 std::vector<PatchPanel::SoftwarePatch> swPatches;
3468 double latencyMs;
3469 status_t status = INVALID_OPERATION;
3470 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3471 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3472 && swPatches.size() > 0) {
3473 status = swPatches[0].getLatencyMs_l(&latencyMs);
3474 downstreamPatchHandle = swPatches[0].getPatchHandle();
3475 }
3476 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003477 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003478 lastDownstreamPatchHandle = downstreamPatchHandle;
3479 }
3480 if (status == OK) {
3481 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003482 // latency of 5 seconds).
3483 const double minLatency = 0., maxLatency = 5000.;
3484 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003485 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003486 } else {
3487 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003488 if (latencyMs < minLatency) latencyMs = minLatency;
3489 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003490 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003491 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003492 }
3493 mAudioFlinger->mLock.unlock();
3494 }
3495 } else {
3496 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3497 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003498 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003499 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3500 }
3501 }
3502
Eric Laurent81784c32012-11-19 14:55:58 -08003503 { // scope for mLock
3504
3505 Mutex::Autolock _l(mLock);
3506
Eric Laurent021cf962014-05-13 10:18:14 -07003507 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003508
Glenn Kasteneef598c2017-04-03 14:41:13 -07003509 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003510 if (logString != NULL) {
3511 mNBLogWriter->logTimestamp();
3512 mNBLogWriter->log(logString);
3513 logString = NULL;
3514 }
3515
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003516 // Collect timestamp statistics for the Playback Thread types that support it.
3517 if (mType == MIXER
3518 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003519 || mType == DIRECT
3520 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003521 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003522 // and associate with the sink frames written out. We need
3523 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003524 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003525 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003526 if (mStandby) {
3527 mTimestampVerifier.discontinuity();
3528 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3529 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3530 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3531 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003532
3533 if (isTimestampCorrectionEnabled()) {
3534 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3535 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3536 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3537 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3538 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3539 = correctedTimestamp.mFrames;
3540 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3541 = correctedTimestamp.mTimeNs;
3542 ALOGV("TS_AFTER: %d %lld %lld", id(),
3543 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3544 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003545
3546 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003547 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003548 const int64_t newPosition =
3549 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003550 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003551 // prevent retrograde
3552 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3553 newPosition,
3554 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3555 - mSuspendedFrames));
3556 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003557 }
3558
Andy Hung818e7a32016-02-16 18:08:07 -08003559 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003560 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003561
3562 // We keep track of the last valid kernel position in case we are in underrun
3563 // and the normal mixer period is the same as the fast mixer period, or there
3564 // is some error from the HAL.
3565 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3566 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3567 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3568 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3569 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3570
3571 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3572 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3573 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3574 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003575 }
3576
3577 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3578 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003579 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003580 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003581 }
3582
Andy Hung818e7a32016-02-16 18:08:07 -08003583 // copy over kernel info
3584 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003585 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3586 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003587 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3588 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003589 } else {
3590 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003591 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003592
Andy Hungc54b1ff2016-02-23 14:07:07 -08003593 // mFramesWritten for non-offloaded tracks are contiguous
3594 // even after standby() is called. This is useful for the track frame
3595 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003596 bool serverLocationUpdate = false;
3597 if (mFramesWritten != lastFramesWritten) {
3598 serverLocationUpdate = true;
3599 lastFramesWritten = mFramesWritten;
3600 }
3601 // Only update timestamps if there is a meaningful change.
3602 // Either the kernel timestamp must be valid or we have written something.
3603 if (kernelLocationUpdate || serverLocationUpdate) {
3604 if (serverLocationUpdate) {
3605 // use the time before we called the HAL write - it is a bit more accurate
3606 // to when the server last read data than the current time here.
3607 //
Andy Hung446f4df2019-02-21 12:26:41 -08003608 // If we haven't written anything, mLastIoBeginNs will be -1
Andy Hung69488c42016-05-16 18:43:33 -07003609 // and we use systemTime().
3610 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
Andy Hung446f4df2019-02-21 12:26:41 -08003611 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
3612 ? systemTime() : mLastIoBeginNs;
Andy Hung69488c42016-05-16 18:43:33 -07003613 }
Andy Hungdae27702016-10-31 14:01:16 -07003614
3615 for (const sp<Track> &t : mActiveTracks) {
3616 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003617 t->updateTrackFrameInfo(
3618 t->mAudioTrackServerProxy->framesReleased(),
3619 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003620 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003621 mTimestamp);
3622 }
Andy Hunge10393e2015-06-12 13:59:33 -07003623 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003624 }
Andy Hunge6c37112019-02-26 17:38:10 -08003625
3626 if (audio_has_proportional_frames(mFormat)) {
3627 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
3628 if (latencyMs != 0.) { // note 0. means timestamp is empty.
3629 mLatencyMs.add(latencyMs);
3630 }
3631 }
3632
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003633 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003634#if 0
3635 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003636 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003637 timespec ts;
3638 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003639 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003640 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003641 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003642 }
3643 ++z;
3644#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003645 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003646 if (mSignalPending) {
3647 // A signal was raised while we were unlocked
3648 mSignalPending = false;
3649 } else if (waitingAsyncCallback_l()) {
3650 if (exitPending()) {
3651 break;
3652 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003653 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003654 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003655 releaseWakeLock_l();
3656 released = true;
3657 }
Andy Hung10cbff12017-02-21 17:30:14 -08003658
3659 const int64_t waitNs = computeWaitTimeNs_l();
3660 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3661 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3662 if (status == TIMED_OUT) {
3663 mSignalPending = true; // if timeout recheck everything
3664 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003665 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003666 if (released) {
3667 acquireWakeLock_l();
3668 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003669 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3670 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003671
3672 continue;
3673 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003674 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003675 isSuspended()) {
3676 // put audio hardware into standby after short delay
3677 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003678
3679 threadLoop_standby();
3680
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003681 // This is where we go into standby
3682 if (!mStandby) {
3683 LOG_AUDIO_STATE();
3684 }
Eric Laurent81784c32012-11-19 14:55:58 -08003685 mStandby = true;
Andy Hungd0979812019-02-21 15:51:44 -08003686 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003687 }
3688
Eric Tan39ec8d62018-07-24 09:49:29 -07003689 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003690 // we're about to wait, flush the binder command buffer
3691 IPCThreadState::self()->flushCommands();
3692
3693 clearOutputTracks();
3694
3695 if (exitPending()) {
3696 break;
3697 }
3698
3699 releaseWakeLock_l();
3700 // wait until we have something to do...
3701 ALOGV("%s going to sleep", myName.string());
3702 mWaitWorkCV.wait(mLock);
3703 ALOGV("%s waking up", myName.string());
3704 acquireWakeLock_l();
3705
3706 mMixerStatus = MIXER_IDLE;
3707 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3708 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003709 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003710 checkSilentMode_l();
3711
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003712 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3713 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003714 if (mType == MIXER) {
3715 sleepTimeShift = 0;
3716 }
3717
3718 continue;
3719 }
3720 }
Eric Laurent81784c32012-11-19 14:55:58 -08003721 // mMixerStatusIgnoringFastTracks is also updated internally
3722 mMixerStatus = prepareTracks_l(&tracksToRemove);
3723
Andy Hungdae27702016-10-31 14:01:16 -07003724 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003725
Kevin Rocard069c2712018-03-29 19:09:14 -07003726 updateMetadata_l();
3727
Eric Laurent81784c32012-11-19 14:55:58 -08003728 // prevent any changes in effect chain list and in each effect chain
3729 // during mixing and effect process as the audio buffers could be deleted
3730 // or modified if an effect is created or deleted
3731 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003732
3733 // Determine which session to pick up haptic data.
3734 // This must be done under the same lock as prepareTracks_l().
3735 // TODO: Write haptic data directly to sink buffer when mixing.
3736 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3737 for (const auto& track : mActiveTracks) {
3738 if (track->getHapticPlaybackEnabled()) {
3739 activeHapticSessionId = track->sessionId();
3740 break;
3741 }
3742 }
3743 }
3744
Andy Hungc1646382019-04-30 16:12:10 -07003745 // Acquire a local copy of active tracks with lock (release w/o lock).
3746 //
3747 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3748 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3749 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3750 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003751 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003752
Eric Laurentbfb1b832013-01-07 09:53:42 -08003753 if (mBytesRemaining == 0) {
3754 mCurrentWriteLength = 0;
3755 if (mMixerStatus == MIXER_TRACKS_READY) {
3756 // threadLoop_mix() sets mCurrentWriteLength
3757 threadLoop_mix();
3758 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3759 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003760 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003761 // must be written to HAL
3762 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003763 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003764 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003765
3766 // Tally underrun frames as we are inserting 0s here.
3767 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003768 if (track->mFillingUpStatus == Track::FS_ACTIVE
3769 && !track->isStopped()
3770 && !track->isPaused()
3771 && !track->isTerminated()) {
3772 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3773 __func__, track->id(), track->getTrackStateAsString(),
3774 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003775 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3776 }
3777 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003778 }
3779 }
Andy Hung98ef9782014-03-04 14:46:50 -08003780 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003781 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003782 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3783 // or mSinkBuffer (if there are no effects).
3784 //
3785 // This is done pre-effects computation; if effects change to
3786 // support higher precision, this needs to move.
3787 //
3788 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003789 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003790 if (mMixerBufferValid) {
3791 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3792 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3793
Andy Hung2ddee192015-12-18 17:34:44 -08003794 // mono blend occurs for mixer threads only (not direct or offloaded)
3795 // and is handled here if we're going directly to the sink.
3796 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003797 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3798 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003799 }
3800
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003801 if (!hasFastMixer()) {
3802 // Balance must take effect after mono conversion.
3803 // We do it here if there is no FastMixer.
3804 // mBalance detects zero balance within the class for speed (not needed here).
3805 mBalance.setBalance(mMasterBalance.load());
3806 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3807 }
3808
Andy Hung98ef9782014-03-04 14:46:50 -08003809 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003810 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3811
3812 // If we're going directly to the sink and there are haptic channels,
3813 // we should adjust channels as the sample data is partially interleaved
3814 // in this case.
3815 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3816 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3817 mChannelCount + mHapticChannelCount,
3818 audio_bytes_per_sample(format),
3819 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3820 }
Andy Hung98ef9782014-03-04 14:46:50 -08003821 }
3822
Eric Laurentbfb1b832013-01-07 09:53:42 -08003823 mBytesRemaining = mCurrentWriteLength;
3824 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003825 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3826 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3827 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3828 mBytesWritten += mBytesRemaining;
3829 mFramesWritten += framesRemaining;
3830 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003831 mBytesRemaining = 0;
3832 }
Eric Laurent81784c32012-11-19 14:55:58 -08003833
Eric Laurentbfb1b832013-01-07 09:53:42 -08003834 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003835 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003836 for (size_t i = 0; i < effectChains.size(); i ++) {
3837 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003838 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003839 if (activeHapticSessionId != AUDIO_SESSION_NONE
3840 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003841 // Haptic data is active in this case, copy it directly from
3842 // in buffer to out buffer.
3843 const size_t audioBufferSize = mNormalFrameCount
3844 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3845 memcpy_by_audio_format(
3846 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3847 EFFECT_BUFFER_FORMAT,
3848 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3849 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3850 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003851 }
Eric Laurent81784c32012-11-19 14:55:58 -08003852 }
3853 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003854 // Process effect chains for offloaded thread even if no audio
3855 // was read from audio track: process only updates effect state
3856 // and thus does have to be synchronized with audio writes but may have
3857 // to be called while waiting for async write callback
3858 if (mType == OFFLOAD) {
3859 for (size_t i = 0; i < effectChains.size(); i ++) {
3860 effectChains[i]->process_l();
3861 }
3862 }
Eric Laurent81784c32012-11-19 14:55:58 -08003863
Andy Hung98ef9782014-03-04 14:46:50 -08003864 // Only if the Effects buffer is enabled and there is data in the
3865 // Effects buffer (buffer valid), we need to
3866 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003867 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003868 if (mEffectBufferValid) {
3869 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003870
3871 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003872 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3873 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003874 }
3875
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003876 if (!hasFastMixer()) {
3877 // Balance must take effect after mono conversion.
3878 // We do it here if there is no FastMixer.
3879 // mBalance detects zero balance within the class for speed (not needed here).
3880 mBalance.setBalance(mMasterBalance.load());
3881 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3882 }
3883
Andy Hung98ef9782014-03-04 14:46:50 -08003884 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003885 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3886 // The sample data is partially interleaved when haptic channels exist,
3887 // we need to adjust channels here.
3888 if (mHapticChannelCount > 0) {
3889 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3890 mChannelCount + mHapticChannelCount,
3891 audio_bytes_per_sample(mFormat),
3892 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3893 }
Andy Hung98ef9782014-03-04 14:46:50 -08003894 }
3895
Eric Laurent81784c32012-11-19 14:55:58 -08003896 // enable changes in effect chain
3897 unlockEffectChains(effectChains);
3898
Eric Laurentbfb1b832013-01-07 09:53:42 -08003899 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003900 // mSleepTimeUs == 0 means we must write to audio hardware
3901 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003902 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003903 // writePeriodNs is updated >= 0 when ret > 0.
3904 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003905 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003906 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003907 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003908 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003909 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003910 if (ret < 0) {
3911 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003912 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003913 mBytesWritten += ret;
3914 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003915 const int64_t frames = ret / mFrameSize;
3916 mFramesWritten += frames;
3917
3918 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3919 // process information relating to write time.
3920 if (audio_has_proportional_frames(mFormat)) {
3921 // we are in a continuous mixing cycle
3922 if (mMixerStatus == MIXER_TRACKS_READY &&
3923 loopCount == lastLoopCountWritten + 1) {
3924
3925 const double jitterMs =
3926 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3927 {frames, writePeriodNs},
3928 {0, 0} /* lastTimestamp */, mSampleRate);
3929 const double processMs =
3930 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3931
3932 Mutex::Autolock _l(mLock);
3933 mIoJitterMs.add(jitterMs);
3934 mProcessTimeMs.add(processMs);
3935 }
3936
3937 // write blocked detection
3938 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3939 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3940 mNumDelayedWrites++;
3941 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3942 ATRACE_NAME("underrun");
3943 ALOGW("write blocked for %lld msecs, "
3944 "%d delayed writes, thread %d",
3945 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3946 mNumDelayedWrites, mId);
3947 lastWarning = lastIoEndNs;
3948 }
3949 }
3950 }
3951 // update timing info.
3952 mLastIoBeginNs = lastIoBeginNs;
3953 mLastIoEndNs = lastIoEndNs;
3954 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003955 }
3956 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3957 (mMixerStatus == MIXER_DRAIN_ALL)) {
3958 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003959 }
Andy Hung08fb1742015-05-31 23:22:10 -07003960 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003961
3962 if (mThreadThrottle
3963 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003964 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003965 // Limit MixerThread data processing to no more than twice the
3966 // expected processing rate.
3967 //
3968 // This helps prevent underruns with NuPlayer and other applications
3969 // which may set up buffers that are close to the minimum size, or use
3970 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3971 //
3972 // The throttle smooths out sudden large data drains from the device,
3973 // e.g. when it comes out of standby, which often causes problems with
3974 // (1) mixer threads without a fast mixer (which has its own warm-up)
3975 // (2) minimum buffer sized tracks (even if the track is full,
3976 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003977 //
3978 // Total time spent in last processing cycle equals time spent in
3979 // 1. threadLoop_write, as well as time spent in
3980 // 2. threadLoop_mix (significant for heavy mixing, especially
3981 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003982
Andy Hung446f4df2019-02-21 12:26:41 -08003983 // it's OK if deltaMs is an overestimate.
3984
3985 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003986
Ivan Lozanoea04d392017-11-07 14:37:07 -08003987 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003988 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08003989 mediametrics::LogItem(mMetricsId)
3990 // ms units always double
3991 .set(AMEDIAMETRICS_PROP_THROTTLEMS, (double)throttleMs)
3992 .record();
3993
Andy Hung08fb1742015-05-31 23:22:10 -07003994 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003995 // notify of throttle start on verbose log
3996 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3997 "mixer(%p) throttle begin:"
3998 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003999 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004000 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004001 // Throttle must be attributed to the previous mixer loop's write time
4002 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004003 // This also ensures proper timing statistics.
4004 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004005 } else {
4006 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4007 if (diff > 0) {
4008 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004009 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004010 ALOGD_IF(!isSingleDeviceType(
4011 outDeviceTypes(), audio_is_a2dp_out_device) &&
4012 !isSingleDeviceType(
4013 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004014 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004015 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4016 }
Andy Hung08fb1742015-05-31 23:22:10 -07004017 }
4018 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004019 }
Eric Laurent81784c32012-11-19 14:55:58 -08004020
Eric Laurentbfb1b832013-01-07 09:53:42 -08004021 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004022 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004023 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004024 // suspended requires accurate metering of sleep time.
4025 if (isSuspended()) {
4026 // advance by expected sleepTime
4027 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4028 const nsecs_t nowNs = systemTime();
4029
4030 // compute expected next time vs current time.
4031 // (negative deltas are treated as delays).
4032 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4033 if (deltaNs < -kMaxNextBufferDelayNs) {
4034 // Delays longer than the max allowed trigger a reset.
4035 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4036 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4037 timeLoopNextNs = nowNs + deltaNs;
4038 } else if (deltaNs < 0) {
4039 // Delays within the max delay allowed: zero the delta/sleepTime
4040 // to help the system catch up in the next iteration(s)
4041 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4042 deltaNs = 0;
4043 }
4044 // update sleep time (which is >= 0)
4045 mSleepTimeUs = deltaNs / 1000;
4046 }
Eric Laurente93cc032016-05-05 10:15:10 -07004047 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4048 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004049 }
Glenn Kastene7754022014-10-31 12:11:26 -07004050 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004051 }
Eric Laurent81784c32012-11-19 14:55:58 -08004052 }
4053
4054 // Finally let go of removed track(s), without the lock held
4055 // since we can't guarantee the destructors won't acquire that
4056 // same lock. This will also mutate and push a new fast mixer state.
4057 threadLoop_removeTracks(tracksToRemove);
4058 tracksToRemove.clear();
4059
4060 // FIXME I don't understand the need for this here;
4061 // it was in the original code but maybe the
4062 // assignment in saveOutputTracks() makes this unnecessary?
4063 clearOutputTracks();
4064
4065 // Effect chains will be actually deleted here if they were removed from
4066 // mEffectChains list during mixing or effects processing
4067 effectChains.clear();
4068
4069 // FIXME Note that the above .clear() is no longer necessary since effectChains
4070 // is now local to this block, but will keep it for now (at least until merge done).
4071 }
4072
Eric Laurentbfb1b832013-01-07 09:53:42 -08004073 threadLoop_exit();
4074
Eric Laurentcf817a22014-08-04 20:36:31 -07004075 if (!mStandby) {
4076 threadLoop_standby();
4077 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004078 }
4079
4080 releaseWakeLock();
4081
4082 ALOGV("Thread %p type %d exiting", this, mType);
4083 return false;
4084}
4085
Eric Laurentbfb1b832013-01-07 09:53:42 -08004086// removeTracks_l() must be called with ThreadBase::mLock held
4087void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4088{
Andy Hungfe726a62018-09-27 15:17:25 -07004089 for (const auto& track : tracksToRemove) {
4090 mActiveTracks.remove(track);
4091 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4092 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4093 if (chain != 0) {
4094 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4095 __func__, track->id(), chain.get(), track->sessionId());
4096 chain->decActiveTrackCnt();
4097 }
4098 // If an external client track, inform APM we're no longer active, and remove if needed.
4099 // We do this under lock so that the state is consistent if the Track is destroyed.
4100 if (track->isExternalTrack()) {
4101 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004102 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004103 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004104 }
4105 }
Andy Hungfe726a62018-09-27 15:17:25 -07004106 if (track->isTerminated()) {
4107 // remove from our tracks vector
4108 removeTrack_l(track);
4109 }
jiabin57303cc2018-12-18 15:45:57 -08004110 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4111 && mHapticChannelCount > 0) {
4112 mLock.unlock();
4113 // Unlock due to VibratorService will lock for this call and will
4114 // call Tracks.mute/unmute which also require thread's lock.
4115 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4116 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08004117 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004118 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004119}
Eric Laurent81784c32012-11-19 14:55:58 -08004120
Eric Laurentaccc1472013-09-20 09:36:34 -07004121status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4122{
4123 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004124 ExtendedTimestamp ets;
4125 status_t status = mNormalSink->getTimestamp(ets);
4126 if (status == NO_ERROR) {
4127 status = ets.getBestTimestamp(&timestamp);
4128 }
4129 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004130 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004131 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07004132 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004133 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07004134 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11004135 if (mDownstreamLatencyStatMs.getN() > 0) {
4136 const uint32_t positionOffset =
4137 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4138 if (positionOffset > timestamp.mPosition) {
4139 timestamp.mPosition = 0;
4140 } else {
4141 timestamp.mPosition -= positionOffset;
4142 }
4143 }
Eric Laurentaccc1472013-09-20 09:36:34 -07004144 return NO_ERROR;
4145 }
4146 }
4147 return INVALID_OPERATION;
4148}
Eric Laurent1c333e22014-05-20 10:48:17 -07004149
Eric Laurenteab90452019-06-24 15:17:46 -07004150// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4151// still applied by the mixer.
4152// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4153// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4154// if more than one track are active
4155status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4156{
4157 status_t result = NO_ERROR;
4158 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4159 if (*volume != mLeftVolFloat) {
4160 result = mOutput->stream->setVolume(*volume, *volume);
4161 ALOGE_IF(result != OK,
4162 "Error when setting output stream volume: %d", result);
4163 if (result == NO_ERROR) {
4164 mLeftVolFloat = *volume;
4165 }
4166 }
4167 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4168 // remove stream volume contribution from software volume.
4169 if (mLeftVolFloat == *volume) {
4170 *volume = 1.0f;
4171 }
4172 }
4173 return result;
4174}
4175
Eric Laurent054d9d32015-04-24 08:48:48 -07004176status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4177 audio_patch_handle_t *handle)
4178{
Andy Hungf60abce2016-08-26 11:37:54 -07004179 status_t status;
4180 if (property_get_bool("af.patch_park", false /* default_value */)) {
4181 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4182 // or if HAL does not properly lock against access.
4183 AutoPark<FastMixer> park(mFastMixer);
4184 status = PlaybackThread::createAudioPatch_l(patch, handle);
4185 } else {
4186 status = PlaybackThread::createAudioPatch_l(patch, handle);
4187 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004188 return status;
4189}
4190
Eric Laurent1c333e22014-05-20 10:48:17 -07004191status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4192 audio_patch_handle_t *handle)
4193{
4194 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004195
4196 // store new device and send to effects
4197 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004198 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004199 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004200 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4201 && !mOutput->audioHwDev->supportsAudioPatches(),
4202 "Enumerated device type(%#x) must not be used "
4203 "as it does not support audio patches",
4204 patch->sinks[i].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004205 type |= patch->sinks[i].ext.device.type;
jiabinc52b1ff2019-10-31 17:20:42 -07004206 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4207 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004208 }
4209
François Gaffie0c280aa2018-07-25 10:02:15 +02004210 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004211#ifdef ADD_BATTERY_DATA
4212 // when changing the audio output device, call addBatteryData to notify
4213 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004214 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004215 uint32_t params = 0;
4216 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004217 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004218 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004219 }
4220
Eric Laurent054d9d32015-04-24 08:48:48 -07004221 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004222 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004223 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4224 }
4225
4226 if (params != 0) {
4227 addBatteryData(params);
4228 }
4229 }
4230#endif
4231
4232 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004233 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004234 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004235
jiabinc52b1ff2019-10-31 17:20:42 -07004236 // mPatch.num_sinks is not set when the thread is created so that
4237 // the first patch creation triggers an ioConfigChanged callback
4238 bool configChanged = (mPatch.num_sinks == 0) ||
4239 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004240 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004241 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004242 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004243
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004244 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004245 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4246 status = hwDevice->createAudioPatch(patch->num_sources,
4247 patch->sources,
4248 patch->num_sinks,
4249 patch->sinks,
4250 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004251 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004252 char *address;
4253 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4254 //FIXME: we only support address on first sink with HAL version < 3.0
4255 address = audio_device_address_to_parameter(
4256 patch->sinks[0].ext.device.type,
4257 patch->sinks[0].ext.device.address);
4258 } else {
4259 address = (char *)calloc(1, 1);
4260 }
4261 AudioParameter param = AudioParameter(String8(address));
4262 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004263 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004264 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004265 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004266 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004267 const std::string patchSinksAsString = patchSinksToString(patch);
4268 mediametrics::LogItem item(mMetricsId);
4269 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATEAUDIOPATCH)
4270 .set(AMEDIAMETRICS_PROP_OUTPUTDEVICES, patchSinksAsString.c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08004271 .record();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004272 // also dispatch to active AudioTracks for MediaMetrics
4273 for (const auto &track : mActiveTracks) {
4274 track->logEndInterval();
4275 track->logBeginInterval(patchSinksAsString);
4276 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004277
Eric Laurente8726fe2015-06-26 09:39:24 -07004278 if (configChanged) {
4279 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4280 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004281 return status;
4282}
4283
Eric Laurent054d9d32015-04-24 08:48:48 -07004284status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4285{
Andy Hungf60abce2016-08-26 11:37:54 -07004286 status_t status;
4287 if (property_get_bool("af.patch_park", false /* default_value */)) {
4288 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4289 // or if HAL does not properly lock against access.
4290 AutoPark<FastMixer> park(mFastMixer);
4291 status = PlaybackThread::releaseAudioPatch_l(handle);
4292 } else {
4293 status = PlaybackThread::releaseAudioPatch_l(handle);
4294 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004295 return status;
4296}
4297
Eric Laurent1c333e22014-05-20 10:48:17 -07004298status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4299{
4300 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004301
jiabinc52b1ff2019-10-31 17:20:42 -07004302 mPatch = audio_patch{};
4303 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004304
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004305 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004306 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4307 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004308 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004309 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004310 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004311 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004312 }
4313 return status;
4314}
4315
Eric Laurent83b88082014-06-20 18:31:16 -07004316void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4317{
4318 Mutex::Autolock _l(mLock);
4319 mTracks.add(track);
4320}
4321
4322void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4323{
4324 Mutex::Autolock _l(mLock);
4325 destroyTrack_l(track);
4326}
4327
Mikhail Naganovdc769682018-05-04 15:34:08 -07004328void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004329{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004330 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004331 config->role = AUDIO_PORT_ROLE_SOURCE;
4332 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4333 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004334 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4335 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4336 config->flags.output = mOutput->flags;
4337 }
Eric Laurent83b88082014-06-20 18:31:16 -07004338}
4339
Eric Laurent81784c32012-11-19 14:55:58 -08004340// ----------------------------------------------------------------------------
4341
4342AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004343 audio_io_handle_t id, bool systemReady, type_t type)
4344 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004345 // mAudioMixer below
4346 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004347 mFastMixerFutex(0),
4348 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004349 // mOutputSink below
4350 // mPipeSink below
4351 // mNormalSink below
4352{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004353 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004354 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004355 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004356 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004357 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4358 mNormalFrameCount);
4359 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4360
Andy Hungfbfc3952015-01-15 13:33:51 -08004361 if (type == DUPLICATING) {
4362 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4363 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4364 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4365 return;
4366 }
Eric Laurent81784c32012-11-19 14:55:58 -08004367 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004368 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004369 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004370 const NBAIO_Format offers[1] = {Format_from_SR_C(
4371 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004372#if !LOG_NDEBUG
4373 ssize_t index =
4374#else
4375 (void)
4376#endif
4377 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004378 ALOG_ASSERT(index == 0);
4379
4380 // initialize fast mixer depending on configuration
4381 bool initFastMixer;
4382 switch (kUseFastMixer) {
4383 case FastMixer_Never:
4384 initFastMixer = false;
4385 break;
4386 case FastMixer_Always:
4387 initFastMixer = true;
4388 break;
4389 case FastMixer_Static:
4390 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004391 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4392 // where the period is less than an experimentally determined threshold that can be
4393 // scheduled reliably with CFS. However, the BT A2DP HAL is
4394 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4395 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004396 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004397 break;
4398 }
Andy Hungfda69402017-02-15 14:33:12 -08004399 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4400 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4401 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004402 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004403 audio_format_t fastMixerFormat;
4404 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4405 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4406 } else {
4407 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4408 }
4409 if (mFormat != fastMixerFormat) {
4410 // change our Sink format to accept our intermediate precision
4411 mFormat = fastMixerFormat;
4412 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004413 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004414 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4415 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4416 }
Eric Laurent81784c32012-11-19 14:55:58 -08004417
4418 // create a MonoPipe to connect our submix to FastMixer
4419 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004420
Andy Hung1258c1a2014-05-23 21:22:17 -07004421 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004422 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004423 format.mFormat = fastMixerFormat;
4424 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4425
Eric Laurent81784c32012-11-19 14:55:58 -08004426 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4427 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4428 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4429 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4430 const NBAIO_Format offers[1] = {format};
4431 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004432#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004433 ssize_t index =
4434#else
4435 (void)
4436#endif
4437 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004438 ALOG_ASSERT(index == 0);
4439 monoPipe->setAvgFrames((mScreenState & 1) ?
4440 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4441 mPipeSink = monoPipe;
4442
Eric Laurent81784c32012-11-19 14:55:58 -08004443 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004444 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004445 FastMixerStateQueue *sq = mFastMixer->sq();
4446#ifdef STATE_QUEUE_DUMP
4447 sq->setObserverDump(&mStateQueueObserverDump);
4448 sq->setMutatorDump(&mStateQueueMutatorDump);
4449#endif
4450 FastMixerState *state = sq->begin();
4451 FastTrack *fastTrack = &state->mFastTracks[0];
4452 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4453 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4454 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004455 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4456 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004457 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004458 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabin84114c32019-04-10 16:38:07 -07004459 fastTrack->mHapticIntensity = AudioMixer::HAPTIC_SCALE_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004460 fastTrack->mGeneration++;
4461 state->mFastTracksGen++;
4462 state->mTrackMask = 1;
4463 // fast mixer will use the HAL output sink
4464 state->mOutputSink = mOutputSink.get();
4465 state->mOutputSinkGen++;
4466 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004467 // specify sink channel mask when haptic channel mask present as it can not
4468 // be calculated directly from channel count
4469 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4470 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004471 state->mCommand = FastMixerState::COLD_IDLE;
4472 // already done in constructor initialization list
4473 //mFastMixerFutex = 0;
4474 state->mColdFutexAddr = &mFastMixerFutex;
4475 state->mColdGen++;
4476 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004477 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4478 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004479 sq->end();
4480 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4481
Eric Tan0513b5d2018-09-17 10:32:48 -07004482 NBLog::thread_info_t info;
4483 info.id = mId;
4484 info.type = NBLog::FASTMIXER;
4485 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4486
Eric Laurent81784c32012-11-19 14:55:58 -08004487 // start the fast mixer
4488 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4489 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004490 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004491 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004492
4493#ifdef AUDIO_WATCHDOG
4494 // create and start the watchdog
4495 mAudioWatchdog = new AudioWatchdog();
4496 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4497 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4498 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004499 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004500#endif
Andy Hung8946a282018-04-19 20:04:56 -07004501 } else {
4502#ifdef TEE_SINK
4503 // Only use the MixerThread tee if there is no FastMixer.
4504 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4505 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4506#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004507 }
4508
4509 switch (kUseFastMixer) {
4510 case FastMixer_Never:
4511 case FastMixer_Dynamic:
4512 mNormalSink = mOutputSink;
4513 break;
4514 case FastMixer_Always:
4515 mNormalSink = mPipeSink;
4516 break;
4517 case FastMixer_Static:
4518 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4519 break;
4520 }
4521}
4522
4523AudioFlinger::MixerThread::~MixerThread()
4524{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004525 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004526 FastMixerStateQueue *sq = mFastMixer->sq();
4527 FastMixerState *state = sq->begin();
4528 if (state->mCommand == FastMixerState::COLD_IDLE) {
4529 int32_t old = android_atomic_inc(&mFastMixerFutex);
4530 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004531 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004532 }
4533 }
4534 state->mCommand = FastMixerState::EXIT;
4535 sq->end();
4536 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4537 mFastMixer->join();
4538 // Though the fast mixer thread has exited, it's state queue is still valid.
4539 // We'll use that extract the final state which contains one remaining fast track
4540 // corresponding to our sub-mix.
4541 state = sq->begin();
4542 ALOG_ASSERT(state->mTrackMask == 1);
4543 FastTrack *fastTrack = &state->mFastTracks[0];
4544 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4545 delete fastTrack->mBufferProvider;
4546 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004547 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004548#ifdef AUDIO_WATCHDOG
4549 if (mAudioWatchdog != 0) {
4550 mAudioWatchdog->requestExit();
4551 mAudioWatchdog->requestExitAndWait();
4552 mAudioWatchdog.clear();
4553 }
4554#endif
4555 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004556 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004557 delete mAudioMixer;
4558}
4559
4560
4561uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4562{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004563 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004564 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4565 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4566 }
4567 return latency;
4568}
4569
Eric Laurentbfb1b832013-01-07 09:53:42 -08004570ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004571{
4572 // FIXME we should only do one push per cycle; confirm this is true
4573 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004574 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004575 FastMixerStateQueue *sq = mFastMixer->sq();
4576 FastMixerState *state = sq->begin();
4577 if (state->mCommand != FastMixerState::MIX_WRITE &&
4578 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4579 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004580
4581 // FIXME workaround for first HAL write being CPU bound on some devices
4582 ATRACE_BEGIN("write");
4583 mOutput->write((char *)mSinkBuffer, 0);
4584 ATRACE_END();
4585
Eric Laurent81784c32012-11-19 14:55:58 -08004586 int32_t old = android_atomic_inc(&mFastMixerFutex);
4587 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004588 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004589 }
4590#ifdef AUDIO_WATCHDOG
4591 if (mAudioWatchdog != 0) {
4592 mAudioWatchdog->resume();
4593 }
4594#endif
4595 }
4596 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004597#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004598 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004599 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004600#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004601 sq->end();
4602 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4603 if (kUseFastMixer == FastMixer_Dynamic) {
4604 mNormalSink = mPipeSink;
4605 }
4606 } else {
4607 sq->end(false /*didModify*/);
4608 }
4609 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004610 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004611}
4612
4613void AudioFlinger::MixerThread::threadLoop_standby()
4614{
4615 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004616 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004617 FastMixerStateQueue *sq = mFastMixer->sq();
4618 FastMixerState *state = sq->begin();
4619 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004620 // Report any frames trapped in the Monopipe
4621 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4622 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4623 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4624 "monoPipeWritten:%lld monoPipeLeft:%lld",
4625 (long long)mFramesWritten, (long long)mSuspendedFrames,
4626 (long long)mPipeSink->framesWritten(), pipeFrames);
4627 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4628
Eric Laurent81784c32012-11-19 14:55:58 -08004629 state->mCommand = FastMixerState::COLD_IDLE;
4630 state->mColdFutexAddr = &mFastMixerFutex;
4631 state->mColdGen++;
4632 mFastMixerFutex = 0;
4633 sq->end();
4634 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4635 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4636 if (kUseFastMixer == FastMixer_Dynamic) {
4637 mNormalSink = mOutputSink;
4638 }
4639#ifdef AUDIO_WATCHDOG
4640 if (mAudioWatchdog != 0) {
4641 mAudioWatchdog->pause();
4642 }
4643#endif
4644 } else {
4645 sq->end(false /*didModify*/);
4646 }
4647 }
4648 PlaybackThread::threadLoop_standby();
4649}
4650
Eric Laurentbfb1b832013-01-07 09:53:42 -08004651bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4652{
4653 return false;
4654}
4655
4656bool AudioFlinger::PlaybackThread::shouldStandby_l()
4657{
4658 return !mStandby;
4659}
4660
4661bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4662{
4663 Mutex::Autolock _l(mLock);
4664 return waitingAsyncCallback_l();
4665}
4666
Eric Laurent81784c32012-11-19 14:55:58 -08004667// shared by MIXER and DIRECT, overridden by DUPLICATING
4668void AudioFlinger::PlaybackThread::threadLoop_standby()
4669{
4670 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004671 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004672 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004673 // discard any pending drain or write ack by incrementing sequence
4674 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4675 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004676 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004677 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4678 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004679 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004680 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004681}
4682
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004683void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4684{
4685 ALOGV("signal playback thread");
4686 broadcast_l();
4687}
4688
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004689void AudioFlinger::PlaybackThread::onAsyncError()
4690{
4691 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4692 invalidateTracks((audio_stream_type_t)i);
4693 }
4694}
4695
Eric Laurent81784c32012-11-19 14:55:58 -08004696void AudioFlinger::MixerThread::threadLoop_mix()
4697{
Eric Laurent81784c32012-11-19 14:55:58 -08004698 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004699 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004700 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004701 // increase sleep time progressively when application underrun condition clears.
4702 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4703 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4704 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004705 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004706 sleepTimeShift--;
4707 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004708 mSleepTimeUs = 0;
4709 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004710 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004711
Eric Laurent81784c32012-11-19 14:55:58 -08004712}
4713
4714void AudioFlinger::MixerThread::threadLoop_sleepTime()
4715{
4716 // If no tracks are ready, sleep once for the duration of an output
4717 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004718 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004719 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004720 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4721 // Using the Monopipe availableToWrite, we estimate the
4722 // sleep time to retry for more data (before we underrun).
4723 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4724 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4725 const size_t pipeFrames = monoPipe->maxFrames();
4726 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4727 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4728 const size_t framesDelay = std::min(
4729 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4730 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4731 pipeFrames, framesLeft, framesDelay);
4732 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4733 } else {
4734 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4735 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4736 mSleepTimeUs = kMinThreadSleepTimeUs;
4737 }
4738 // reduce sleep time in case of consecutive application underruns to avoid
4739 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4740 // duration we would end up writing less data than needed by the audio HAL if
4741 // the condition persists.
4742 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4743 sleepTimeShift++;
4744 }
Eric Laurent81784c32012-11-19 14:55:58 -08004745 }
4746 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004747 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004748 }
4749 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004750 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4751 // before effects processing or output.
4752 if (mMixerBufferValid) {
4753 memset(mMixerBuffer, 0, mMixerBufferSize);
4754 } else {
4755 memset(mSinkBuffer, 0, mSinkBufferSize);
4756 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004757 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004758 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4759 "anticipated start");
4760 }
4761 // TODO add standby time extension fct of effect tail
4762}
4763
4764// prepareTracks_l() must be called with ThreadBase::mLock held
4765AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4766 Vector< sp<Track> > *tracksToRemove)
4767{
Andy Hungc0691382018-09-12 18:01:57 -07004768 // clean up deleted track ids in AudioMixer before allocating new tracks
4769 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4770 // for each trackId, destroy it in the AudioMixer
4771 if (mAudioMixer->exists(trackId)) {
4772 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004773 }
4774 });
Andy Hungc0691382018-09-12 18:01:57 -07004775 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004776
4777 mixer_state mixerStatus = MIXER_IDLE;
4778 // find out which tracks need to be processed
4779 size_t count = mActiveTracks.size();
4780 size_t mixedTracks = 0;
4781 size_t tracksWithEffect = 0;
4782 // counts only _active_ fast tracks
4783 size_t fastTracks = 0;
4784 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4785
4786 float masterVolume = mMasterVolume;
4787 bool masterMute = mMasterMute;
4788
4789 if (masterMute) {
4790 masterVolume = 0;
4791 }
4792 // Delegate master volume control to effect in output mix effect chain if needed
4793 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4794 if (chain != 0) {
4795 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4796 chain->setVolume_l(&v, &v);
4797 masterVolume = (float)((v + (1 << 23)) >> 24);
4798 chain.clear();
4799 }
4800
4801 // prepare a new state to push
4802 FastMixerStateQueue *sq = NULL;
4803 FastMixerState *state = NULL;
4804 bool didModify = false;
4805 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004806 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004807 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004808 sq = mFastMixer->sq();
4809 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004810 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004811 }
4812
Andy Hung69aed5f2014-02-25 17:24:40 -08004813 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004814 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004815
Andy Hungbd3b2b02018-05-21 10:53:11 -07004816 // DeferredOperations handles statistics after setting mixerStatus.
4817 class DeferredOperations {
4818 public:
Andy Hungb68f5eb2019-12-03 16:49:17 -08004819 DeferredOperations(mixer_state *mixerStatus, const std::string &metricsId)
4820 : mMixerStatus(mixerStatus)
4821 , mMetricsId(metricsId) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004822
4823 // when leaving scope, tally frames properly.
4824 ~DeferredOperations() {
4825 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4826 // because that is when the underrun occurs.
4827 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungb68f5eb2019-12-03 16:49:17 -08004828 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004829 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004830 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004831 }
4832 }
4833 }
4834
4835 // tallyUnderrunFrames() is called to update the track counters
4836 // with the number of underrun frames for a particular mixer period.
4837 // We defer tallying until we know the final mixer status.
4838 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4839 mUnderrunFrames.emplace_back(track, underrunFrames);
4840 }
4841
4842 private:
4843 const mixer_state * const mMixerStatus;
Andy Hungc2b11cb2020-04-22 09:04:01 -07004844 const std::string& __unused mMetricsId;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004845 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004846 } deferredOperations(&mixerStatus, mMetricsId);
4847 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004848
jiabin245cdd92018-12-07 17:55:15 -08004849 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004850 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004851 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004852
4853 // this const just means the local variable doesn't change
4854 Track* const track = t.get();
4855
4856 // process fast tracks
4857 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004858 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4859 "%s(%d): FastTrack(%d) present without FastMixer",
4860 __func__, id(), track->id());
4861
jiabin245cdd92018-12-07 17:55:15 -08004862 if (track->getHapticPlaybackEnabled()) {
4863 noFastHapticTrack = false;
4864 }
Eric Laurent81784c32012-11-19 14:55:58 -08004865
4866 // It's theoretically possible (though unlikely) for a fast track to be created
4867 // and then removed within the same normal mix cycle. This is not a problem, as
4868 // the track never becomes active so it's fast mixer slot is never touched.
4869 // The converse, of removing an (active) track and then creating a new track
4870 // at the identical fast mixer slot within the same normal mix cycle,
4871 // is impossible because the slot isn't marked available until the end of each cycle.
4872 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004873 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004874 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4875 FastTrack *fastTrack = &state->mFastTracks[j];
4876
4877 // Determine whether the track is currently in underrun condition,
4878 // and whether it had a recent underrun.
4879 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4880 FastTrackUnderruns underruns = ftDump->mUnderruns;
4881 uint32_t recentFull = (underruns.mBitFields.mFull -
4882 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4883 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4884 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4885 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4886 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4887 uint32_t recentUnderruns = recentPartial + recentEmpty;
4888 track->mObservedUnderruns = underruns;
4889 // don't count underruns that occur while stopping or pausing
4890 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004891 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004892 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4893 recentUnderruns > 0) {
4894 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004895 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004896 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004897 // Immediately account for FastTrack underruns.
4898 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004899
4900 // This is similar to the state machine for normal tracks,
4901 // with a few modifications for fast tracks.
4902 bool isActive = true;
4903 switch (track->mState) {
4904 case TrackBase::STOPPING_1:
4905 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004906 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004907 track->mState = TrackBase::STOPPING_2;
4908 }
4909 break;
4910 case TrackBase::PAUSING:
4911 // ramp down is not yet implemented
4912 track->setPaused();
4913 break;
4914 case TrackBase::RESUMING:
4915 // ramp up is not yet implemented
4916 track->mState = TrackBase::ACTIVE;
4917 break;
4918 case TrackBase::ACTIVE:
4919 if (recentFull > 0 || recentPartial > 0) {
4920 // track has provided at least some frames recently: reset retry count
4921 track->mRetryCount = kMaxTrackRetries;
4922 }
4923 if (recentUnderruns == 0) {
4924 // no recent underruns: stay active
4925 break;
4926 }
4927 // there has recently been an underrun of some kind
4928 if (track->sharedBuffer() == 0) {
4929 // were any of the recent underruns "empty" (no frames available)?
4930 if (recentEmpty == 0) {
4931 // no, then ignore the partial underruns as they are allowed indefinitely
4932 break;
4933 }
4934 // there has recently been an "empty" underrun: decrement the retry counter
4935 if (--(track->mRetryCount) > 0) {
4936 break;
4937 }
4938 // indicate to client process that the track was disabled because of underrun;
4939 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004940 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004941 // remove from active list, but state remains ACTIVE [confusing but true]
4942 isActive = false;
4943 break;
4944 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004945 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004946 case TrackBase::STOPPING_2:
4947 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004948 case TrackBase::STOPPED:
4949 case TrackBase::FLUSHED: // flush() while active
4950 // Check for presentation complete if track is inactive
4951 // We have consumed all the buffers of this track.
4952 // This would be incomplete if we auto-paused on underrun
4953 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004954 uint32_t latency = 0;
4955 status_t result = mOutput->stream->getLatency(&latency);
4956 ALOGE_IF(result != OK,
4957 "Error when retrieving output stream latency: %d", result);
4958 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004959 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004960 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4961 // track stays in active list until presentation is complete
4962 break;
4963 }
4964 }
4965 if (track->isStopping_2()) {
4966 track->mState = TrackBase::STOPPED;
4967 }
4968 if (track->isStopped()) {
4969 // Can't reset directly, as fast mixer is still polling this track
4970 // track->reset();
4971 // So instead mark this track as needing to be reset after push with ack
4972 resetMask |= 1 << i;
4973 }
4974 isActive = false;
4975 break;
4976 case TrackBase::IDLE:
4977 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004978 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004979 }
4980
4981 if (isActive) {
4982 // was it previously inactive?
4983 if (!(state->mTrackMask & (1 << j))) {
4984 ExtendedAudioBufferProvider *eabp = track;
4985 VolumeProvider *vp = track;
4986 fastTrack->mBufferProvider = eabp;
4987 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004988 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004989 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08004990 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08004991 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08004992 fastTrack->mGeneration++;
4993 state->mTrackMask |= 1 << j;
4994 didModify = true;
4995 // no acknowledgement required for newly active tracks
4996 }
Kevin Rocard12381092018-04-11 09:19:59 -07004997 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07004998 float volume;
4999 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5000 volume = 0.f;
5001 } else {
5002 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5003 }
5004
5005 handleVoipVolume_l(&volume);
5006
Eric Laurent81784c32012-11-19 14:55:58 -08005007 // cache the combined master volume and stream type volume for fast mixer; this
5008 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005009 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005010 proxy->framesReleased()).first;
5011 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005012 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005013 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5014 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5015 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005016
Kevin Rocard12381092018-04-11 09:19:59 -07005017 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005018 ++fastTracks;
5019 } else {
5020 // was it previously active?
5021 if (state->mTrackMask & (1 << j)) {
5022 fastTrack->mBufferProvider = NULL;
5023 fastTrack->mGeneration++;
5024 state->mTrackMask &= ~(1 << j);
5025 didModify = true;
5026 // If any fast tracks were removed, we must wait for acknowledgement
5027 // because we're about to decrement the last sp<> on those tracks.
5028 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5029 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005030 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5031 // AudioTrack may start (which may not be with a start() but with a write()
5032 // after underrun) and immediately paused or released. In that case the
5033 // FastTrack state hasn't had time to update.
5034 // TODO Remove the ALOGW when this theory is confirmed.
5035 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005036 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5037 j, track->mState, state->mTrackMask, recentUnderruns,
5038 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005039 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005040 }
5041 tracksToRemove->add(track);
5042 // Avoids a misleading display in dumpsys
5043 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5044 }
jiabin245cdd92018-12-07 17:55:15 -08005045 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5046 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5047 didModify = true;
5048 }
Eric Laurent81784c32012-11-19 14:55:58 -08005049 continue;
5050 }
5051
5052 { // local variable scope to avoid goto warning
5053
5054 audio_track_cblk_t* cblk = track->cblk();
5055
5056 // The first time a track is added we wait
5057 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005058 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005059
5060 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005061 // use the trackId as the AudioMixer name.
5062 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005063 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005064 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005065 track->mChannelMask,
5066 track->mFormat,
5067 track->mSessionId);
5068 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005069 ALOGW("%s(): AudioMixer cannot create track(%d)"
5070 " mask %#x, format %#x, sessionId %d",
5071 __func__, trackId,
5072 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005073 tracksToRemove->add(track);
5074 track->invalidate(); // consider it dead.
5075 continue;
5076 }
5077 }
5078
Eric Laurent81784c32012-11-19 14:55:58 -08005079 // make sure that we have enough frames to mix one full buffer.
5080 // enforce this condition only once to enable draining the buffer in case the client
5081 // app does not call stop() and relies on underrun to stop:
5082 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5083 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005084 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005085 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005086 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005087
5088 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005089 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005090 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5091 // add frames already consumed but not yet released by the resampler
5092 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005093 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005094
Eric Laurent81784c32012-11-19 14:55:58 -08005095 uint32_t minFrames = 1;
5096 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5097 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005098 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005099 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005100
5101 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005102 if (ATRACE_ENABLED()) {
5103 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005104 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005105 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005106 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005107 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005108 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005109 !track->isPaused() && !track->isTerminated())
5110 {
Andy Hungc0691382018-09-12 18:01:57 -07005111 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005112
5113 mixedTracks++;
5114
Andy Hung69aed5f2014-02-25 17:24:40 -08005115 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5116 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005117 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005118 if (track->mainBuffer() != mSinkBuffer &&
5119 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005120 if (mEffectBufferEnabled) {
5121 mEffectBufferValid = true; // Later can set directly.
5122 }
Eric Laurent81784c32012-11-19 14:55:58 -08005123 chain = getEffectChain_l(track->sessionId());
5124 // Delegate volume control to effect in track effect chain if needed
5125 if (chain != 0) {
5126 tracksWithEffect++;
5127 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005128 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005129 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005130 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005131 }
5132 }
5133
5134
5135 int param = AudioMixer::VOLUME;
5136 if (track->mFillingUpStatus == Track::FS_FILLED) {
5137 // no ramp for the first volume setting
5138 track->mFillingUpStatus = Track::FS_ACTIVE;
5139 if (track->mState == TrackBase::RESUMING) {
5140 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005141 // If a new track is paused immediately after start, do not ramp on resume.
5142 if (cblk->mServer != 0) {
5143 param = AudioMixer::RAMP_VOLUME;
5144 }
Eric Laurent81784c32012-11-19 14:55:58 -08005145 }
Andy Hungc0691382018-09-12 18:01:57 -07005146 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005147 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005148 // FIXME should not make a decision based on mServer
5149 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005150 // If the track is stopped before the first frame was mixed,
5151 // do not apply ramp
5152 param = AudioMixer::RAMP_VOLUME;
5153 }
5154
5155 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005156 uint32_t vl, vr; // in U8.24 integer format
5157 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005158 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005159 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005160 // Always fetch volumeshaper volume to ensure state is updated.
5161 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5162 const float vh = track->getVolumeHandler()->getVolume(
5163 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005164
Eric Laurenteab90452019-06-24 15:17:46 -07005165 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5166 v = 0;
5167 }
5168
5169 handleVoipVolume_l(&v);
5170
5171 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005172 vl = vr = 0;
5173 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005174 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005175 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005176 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005177 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5178 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005179 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005180 if (vlf > GAIN_FLOAT_UNITY) {
5181 ALOGV("Track left volume out of range: %.3g", vlf);
5182 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005183 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005184 if (vrf > GAIN_FLOAT_UNITY) {
5185 ALOGV("Track right volume out of range: %.3g", vrf);
5186 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005187 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005188 // now apply the master volume and stream type volume and shaper volume
5189 vlf *= v * vh;
5190 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005191 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005192 // then derive vl and vr as U8.24 versions for the effect chain
5193 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5194 vl = (uint32_t) (scaleto8_24 * vlf);
5195 vr = (uint32_t) (scaleto8_24 * vrf);
5196 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005197 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005198 // send level comes from shared memory and so may be corrupt
5199 if (sendLevel > MAX_GAIN_INT) {
5200 ALOGV("Track send level out of range: %04X", sendLevel);
5201 sendLevel = MAX_GAIN_INT;
5202 }
Andy Hung6be49402014-05-30 10:42:03 -07005203 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5204 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005205 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005206
Kevin Rocard12381092018-04-11 09:19:59 -07005207 track->setFinalVolume((vrf + vlf) / 2.f);
5208
Eric Laurent81784c32012-11-19 14:55:58 -08005209 // Delegate volume control to effect in track effect chain if needed
5210 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5211 // Do not ramp volume if volume is controlled by effect
5212 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005213 // Update remaining floating point volume levels
5214 vlf = (float)vl / (1 << 24);
5215 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005216 track->mHasVolumeController = true;
5217 } else {
5218 // force no volume ramp when volume controller was just disabled or removed
5219 // from effect chain to avoid volume spike
5220 if (track->mHasVolumeController) {
5221 param = AudioMixer::VOLUME;
5222 }
5223 track->mHasVolumeController = false;
5224 }
5225
Eric Laurent81784c32012-11-19 14:55:58 -08005226 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005227 mAudioMixer->setBufferProvider(trackId, track);
5228 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005229
Andy Hungc0691382018-09-12 18:01:57 -07005230 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5231 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5232 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005233 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005234 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005235 AudioMixer::TRACK,
5236 AudioMixer::FORMAT, (void *)track->format());
5237 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005238 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005239 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005240 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005241 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005242 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005243 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005244 AudioMixer::MIXER_CHANNEL_MASK,
5245 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005246 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005247 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005248 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005249 if (reqSampleRate == 0) {
5250 reqSampleRate = mSampleRate;
5251 } else if (reqSampleRate > maxSampleRate) {
5252 reqSampleRate = maxSampleRate;
5253 }
Eric Laurent81784c32012-11-19 14:55:58 -08005254 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005255 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005256 AudioMixer::RESAMPLE,
5257 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005258 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005259
Andy Hung333ab962019-05-28 20:23:35 -07005260 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005261 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005262 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005263 AudioMixer::TIMESTRETCH,
5264 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005265 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005266
Andy Hung69aed5f2014-02-25 17:24:40 -08005267 /*
5268 * Select the appropriate output buffer for the track.
5269 *
Andy Hung98ef9782014-03-04 14:46:50 -08005270 * Tracks with effects go into their own effects chain buffer
5271 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005272 *
5273 * Other tracks can use mMixerBuffer for higher precision
5274 * channel accumulation. If this buffer is enabled
5275 * (mMixerBufferEnabled true), then selected tracks will accumulate
5276 * into it.
5277 *
5278 */
5279 if (mMixerBufferEnabled
5280 && (track->mainBuffer() == mSinkBuffer
5281 || track->mainBuffer() == mMixerBuffer)) {
5282 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005283 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005284 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005285 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005286 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005287 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005288 AudioMixer::TRACK,
5289 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5290 // TODO: override track->mainBuffer()?
5291 mMixerBufferValid = true;
5292 } else {
5293 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005294 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005295 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005296 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005297 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005298 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005299 AudioMixer::TRACK,
5300 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5301 }
Eric Laurent81784c32012-11-19 14:55:58 -08005302 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005303 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005304 AudioMixer::TRACK,
5305 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005306 mAudioMixer->setParameter(
5307 trackId,
5308 AudioMixer::TRACK,
5309 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005310 mAudioMixer->setParameter(
5311 trackId,
5312 AudioMixer::TRACK,
5313 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005314
5315 // reset retry count
5316 track->mRetryCount = kMaxTrackRetries;
5317
5318 // If one track is ready, set the mixer ready if:
5319 // - the mixer was not ready during previous round OR
5320 // - no other track is not ready
5321 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5322 mixerStatus != MIXER_TRACKS_ENABLED) {
5323 mixerStatus = MIXER_TRACKS_READY;
5324 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005325
5326 // Enable the next few lines to instrument a test for underrun log handling.
5327 // TODO: Remove when we have a better way of testing the underrun log.
5328#if 0
5329 static int i;
5330 if ((++i & 0xf) == 0) {
5331 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5332 }
5333#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005334 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005335 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005336 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005337 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5338 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005339 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005340 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005341 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005342
Eric Laurent81784c32012-11-19 14:55:58 -08005343 // clear effect chain input buffer if an active track underruns to avoid sending
5344 // previous audio buffer again to effects
5345 chain = getEffectChain_l(track->sessionId());
5346 if (chain != 0) {
5347 chain->clearInputBuffer();
5348 }
5349
Andy Hungc0691382018-09-12 18:01:57 -07005350 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005351 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5352 track->isStopped() || track->isPaused()) {
5353 // We have consumed all the buffers of this track.
5354 // Remove it from the list of active tracks.
5355 // TODO: use actual buffer filling status instead of latency when available from
5356 // audio HAL
5357 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005358 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005359 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5360 if (track->isStopped()) {
5361 track->reset();
5362 }
5363 tracksToRemove->add(track);
5364 }
5365 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005366 // No buffers for this track. Give it a few chances to
5367 // fill a buffer, then remove it from active list.
5368 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005369 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5370 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005371 tracksToRemove->add(track);
5372 // indicate to client process that the track was disabled because of underrun;
5373 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005374 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005375 // If one track is not ready, mark the mixer also not ready if:
5376 // - the mixer was ready during previous round OR
5377 // - no other track is ready
5378 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5379 mixerStatus != MIXER_TRACKS_READY) {
5380 mixerStatus = MIXER_TRACKS_ENABLED;
5381 }
5382 }
Andy Hungc0691382018-09-12 18:01:57 -07005383 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005384 }
5385
5386 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005387
5388 }
5389
jiabin245cdd92018-12-07 17:55:15 -08005390 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5391 // When there is no fast track playing haptic and FastMixer exists,
5392 // enabling the first FastTrack, which provides mixed data from normal
5393 // tracks, to play haptic data.
5394 FastTrack *fastTrack = &state->mFastTracks[0];
5395 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5396 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5397 didModify = true;
5398 }
5399 }
5400
Eric Laurent81784c32012-11-19 14:55:58 -08005401 // Push the new FastMixer state if necessary
5402 bool pauseAudioWatchdog = false;
5403 if (didModify) {
5404 state->mFastTracksGen++;
5405 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5406 if (kUseFastMixer == FastMixer_Dynamic &&
5407 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5408 state->mCommand = FastMixerState::COLD_IDLE;
5409 state->mColdFutexAddr = &mFastMixerFutex;
5410 state->mColdGen++;
5411 mFastMixerFutex = 0;
5412 if (kUseFastMixer == FastMixer_Dynamic) {
5413 mNormalSink = mOutputSink;
5414 }
5415 // If we go into cold idle, need to wait for acknowledgement
5416 // so that fast mixer stops doing I/O.
5417 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5418 pauseAudioWatchdog = true;
5419 }
Eric Laurent81784c32012-11-19 14:55:58 -08005420 }
5421 if (sq != NULL) {
5422 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005423 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5424 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5425 // when bringing the output sink into standby.)
5426 //
5427 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5428 //
5429 // This occurs with BT suspend when we idle the FastMixer with
5430 // active tracks, which may be added or removed.
5431 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005432 }
5433#ifdef AUDIO_WATCHDOG
5434 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5435 mAudioWatchdog->pause();
5436 }
5437#endif
5438
5439 // Now perform the deferred reset on fast tracks that have stopped
5440 while (resetMask != 0) {
5441 size_t i = __builtin_ctz(resetMask);
5442 ALOG_ASSERT(i < count);
5443 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005444 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005445 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5446 track->reset();
5447 }
5448
Andy Hung80d03d22018-04-10 10:32:11 -07005449 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5450 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5451 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5452 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5453 // See also the implementation of destroyTrack_l().
5454 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005455 const int trackId = track->id();
5456 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5457 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005458 }
5459 }
5460
Eric Laurent81784c32012-11-19 14:55:58 -08005461 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005462 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005463
Eric Laurent97d547d2014-09-02 14:45:53 -07005464 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5465 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005466 }
5467
5468 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005469 // as long as there are effects we should clear the effects buffer, to avoid
5470 // passing a non-clean buffer to the effect chain
5471 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005472 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005473 // sink or mix buffer must be cleared if all tracks are connected to an
5474 // effect chain as in this case the mixer will not write to the sink or mix buffer
5475 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005476 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5477 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005478 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005479 if (mMixerBufferValid) {
5480 memset(mMixerBuffer, 0, mMixerBufferSize);
5481 // TODO: In testing, mSinkBuffer below need not be cleared because
5482 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5483 // after mixing.
5484 //
5485 // To enforce this guarantee:
5486 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5487 // (mixedTracks == 0 && fastTracks > 0))
5488 // must imply MIXER_TRACKS_READY.
5489 // Later, we may clear buffers regardless, and skip much of this logic.
5490 }
Andy Hung98ef9782014-03-04 14:46:50 -08005491 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005492 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005493 }
5494
5495 // if any fast tracks, then status is ready
5496 mMixerStatusIgnoringFastTracks = mixerStatus;
5497 if (fastTracks > 0) {
5498 mixerStatus = MIXER_TRACKS_READY;
5499 }
5500 return mixerStatus;
5501}
5502
Eric Laurentad7dd962016-09-22 12:38:37 -07005503// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005504uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005505{
5506 uint32_t trackCount = 0;
5507 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005508 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005509 trackCount++;
5510 }
5511 }
5512 return trackCount;
5513}
5514
Andy Hung1bc088a2018-02-09 15:57:31 -08005515// isTrackAllowed_l() must be called with ThreadBase::mLock held
5516bool AudioFlinger::MixerThread::isTrackAllowed_l(
5517 audio_channel_mask_t channelMask, audio_format_t format,
5518 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005519{
Andy Hung1bc088a2018-02-09 15:57:31 -08005520 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5521 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005522 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005523 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005524 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005525 ALOGW("%s: invalid format: %#x", __func__, format);
5526 return false;
5527 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005528 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005529 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5530 return false;
5531 }
5532 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005533}
5534
Eric Laurent10351942014-05-08 18:49:52 -07005535// checkForNewParameter_l() must be called with ThreadBase::mLock held
5536bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5537 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005538{
Eric Laurent81784c32012-11-19 14:55:58 -08005539 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005540 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005541
Eric Laurent10351942014-05-08 18:49:52 -07005542 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005543
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005544 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005545
Eric Laurent10351942014-05-08 18:49:52 -07005546 AudioParameter param = AudioParameter(keyValuePair);
5547 int value;
5548 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5549 reconfig = true;
5550 }
5551 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005552 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005553 status = BAD_VALUE;
5554 } else {
5555 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005556 reconfig = true;
5557 }
Eric Laurent10351942014-05-08 18:49:52 -07005558 }
5559 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005560 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005561 status = BAD_VALUE;
5562 } else {
5563 // no need to save value, since it's constant
5564 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005565 }
Eric Laurent10351942014-05-08 18:49:52 -07005566 }
5567 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5568 // do not accept frame count changes if tracks are open as the track buffer
5569 // size depends on frame count and correct behavior would not be guaranteed
5570 // if frame count is changed after track creation
5571 if (!mTracks.isEmpty()) {
5572 status = INVALID_OPERATION;
5573 } else {
5574 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005575 }
Eric Laurent10351942014-05-08 18:49:52 -07005576 }
5577 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005578 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005579 }
Eric Laurent81784c32012-11-19 14:55:58 -08005580
Eric Laurent10351942014-05-08 18:49:52 -07005581 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005582 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005583 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005584 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005585 mStandby = true;
5586 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005587 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005588 }
Eric Laurent10351942014-05-08 18:49:52 -07005589 if (status == NO_ERROR && reconfig) {
5590 readOutputParameters_l();
5591 delete mAudioMixer;
5592 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005593 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005594 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005595 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005596 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005597 track->mChannelMask,
5598 track->mFormat,
5599 track->mSessionId);
5600 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005601 "%s(): AudioMixer cannot create track(%d)"
5602 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005603 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005604 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005605 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005606 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005607 }
Eric Laurent81784c32012-11-19 14:55:58 -08005608 }
5609
Eric Laurent42537be2016-01-08 17:16:42 -08005610 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005611}
5612
5613
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005614void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005615{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005616 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005617 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005618 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005619 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005620 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5621 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5622 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005623 if (hasFastMixer()) {
5624 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5625
5626 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5627 // while we are dumping it. It may be inconsistent, but it won't mutate!
5628 // This is a large object so we place it on the heap.
5629 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005630 const std::unique_ptr<FastMixerDumpState> copy =
5631 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005632 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005633
5634#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005635 // Similar for state queue
5636 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5637 observerCopy.dump(fd);
5638 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5639 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005640#endif
5641
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005642#ifdef AUDIO_WATCHDOG
5643 if (mAudioWatchdog != 0) {
5644 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5645 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5646 wdCopy.dump(fd);
5647 }
5648#endif
5649
5650 } else {
5651 dprintf(fd, " No FastMixer\n");
5652 }
Eric Laurent81784c32012-11-19 14:55:58 -08005653}
5654
5655uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5656{
5657 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5658}
5659
5660uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5661{
5662 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5663}
5664
5665void AudioFlinger::MixerThread::cacheParameters_l()
5666{
5667 PlaybackThread::cacheParameters_l();
5668
5669 // FIXME: Relaxed timing because of a certain device that can't meet latency
5670 // Should be reduced to 2x after the vendor fixes the driver issue
5671 // increase threshold again due to low power audio mode. The way this warning
5672 // threshold is calculated and its usefulness should be reconsidered anyway.
5673 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5674}
5675
5676// ----------------------------------------------------------------------------
5677
5678AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005679 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5680 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005681{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005682 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005683}
5684
Eric Laurent81784c32012-11-19 14:55:58 -08005685AudioFlinger::DirectOutputThread::~DirectOutputThread()
5686{
5687}
5688
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005689void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005690{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005691 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005692 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5693 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5694}
5695
5696void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5697{
5698 Mutex::Autolock _l(mLock);
5699 if (mMasterBalance != balance) {
5700 mMasterBalance.store(balance);
5701 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5702 broadcast_l();
5703 }
5704}
5705
Eric Laurent5850c4c2016-11-10 13:04:31 -08005706void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005707{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005708 float left, right;
5709
Andy Hung333ab962019-05-28 20:23:35 -07005710 // Ensure volumeshaper state always advances even when muted.
5711 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5712 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5713 proxy->framesReleased());
5714 mVolumeShaperActive = shaperActive;
5715
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005716 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005717 left = right = 0;
5718 } else {
5719 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005720 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005721
Glenn Kastenc56f3422014-03-21 17:53:17 -07005722 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5723 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5724 if (left > GAIN_FLOAT_UNITY) {
5725 left = GAIN_FLOAT_UNITY;
5726 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005727 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005728 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5729 if (right > GAIN_FLOAT_UNITY) {
5730 right = GAIN_FLOAT_UNITY;
5731 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005732 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005733 }
5734
5735 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005736 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005737 if (left != mLeftVolFloat || right != mRightVolFloat) {
5738 mLeftVolFloat = left;
5739 mRightVolFloat = right;
5740
Eric Laurentbfb1b832013-01-07 09:53:42 -08005741 // Delegate volume control to effect in track effect chain if needed
5742 // only one effect chain can be present on DirectOutputThread, so if
5743 // there is one, the track is connected to it
5744 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005745 // if effect chain exists, volume is handled by it.
5746 // Convert volumes from float to 8.24
5747 uint32_t vl = (uint32_t)(left * (1 << 24));
5748 uint32_t vr = (uint32_t)(right * (1 << 24));
5749 // Direct/Offload effect chains set output volume in setVolume_l().
5750 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5751 } else {
5752 // otherwise we directly set the volume.
5753 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005754 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005755 }
5756 }
5757}
5758
Phil Burk43b4dcc2015-06-09 16:53:44 -07005759void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5760{
5761 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005762 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005763
Eric Laurent0f0631e2015-07-06 18:01:25 -07005764 if (previousTrack != 0 && latestTrack != 0) {
5765 if (mType == DIRECT) {
5766 if (previousTrack.get() != latestTrack.get()) {
5767 mFlushPending = true;
5768 }
5769 } else /* mType == OFFLOAD */ {
5770 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5771 mFlushPending = true;
5772 }
5773 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005774 } else if (previousTrack == 0) {
5775 // there could be an old track added back during track transition for direct
5776 // output, so always issues flush to flush data of the previous track if it
5777 // was already destroyed with HAL paused, then flush can resume the playback
5778 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005779 }
5780 PlaybackThread::onAddNewTrack_l();
5781}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005782
Eric Laurent81784c32012-11-19 14:55:58 -08005783AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5784 Vector< sp<Track> > *tracksToRemove
5785)
5786{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005787 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005788 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005789 bool doHwPause = false;
5790 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005791
5792 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005793 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005794 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005795 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005796 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005797 continue;
5798 }
5799
Eric Laurent5850c4c2016-11-10 13:04:31 -08005800 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005801#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005802 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005803#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005804 // Only consider last track started for volume and mixer state control.
5805 // In theory an older track could underrun and restart after the new one starts
5806 // but as we only care about the transition phase between two tracks on a
5807 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005808 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005809 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005810
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005811 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005812 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005813 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005814 doHwPause = true;
5815 mHwPaused = true;
5816 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005817 } else if (track->isFlushPending()) {
5818 track->flushAck();
5819 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005820 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005821 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005822 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005823 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005824 if (last) {
5825 mLeftVolFloat = mRightVolFloat = -1.0;
5826 if (mHwPaused) {
5827 doHwResume = true;
5828 mHwPaused = false;
5829 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005830 }
5831 }
5832
Eric Laurent81784c32012-11-19 14:55:58 -08005833 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005834 // for all its buffers to be filled before processing it.
5835 // Allow draining the buffer in case the client
5836 // app does not call stop() and relies on underrun to stop:
5837 // hence the test on (track->mRetryCount > 1).
5838 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005839 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005840 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005841 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005842 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005843 minFrames = mNormalFrameCount;
5844 } else {
5845 minFrames = 1;
5846 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005847
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005848 const size_t framesReady = track->framesReady();
5849 const int trackId = track->id();
5850 if (ATRACE_ENABLED()) {
5851 std::string traceName("nRdy");
5852 traceName += std::to_string(trackId);
5853 ATRACE_INT(traceName.c_str(), framesReady);
5854 }
5855 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005856 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005857 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005858 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005859
5860 if (track->mFillingUpStatus == Track::FS_FILLED) {
5861 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005862 if (last) {
5863 // make sure processVolume_l() will apply new volume even if 0
5864 mLeftVolFloat = mRightVolFloat = -1.0;
5865 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005866 if (!mHwSupportsPause) {
5867 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005868 }
5869 }
5870
5871 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005872 processVolume_l(track, last);
5873 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005874 sp<Track> previousTrack = mPreviousTrack.promote();
5875 if (previousTrack != 0) {
5876 if (track != previousTrack.get()) {
5877 // Flush any data still being written from last track
5878 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005879 // Invalidate previous track to force a seek when resuming.
5880 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005881 }
5882 }
5883 mPreviousTrack = track;
5884
Eric Laurentd595b7c2013-04-03 17:27:56 -07005885 // reset retry count
5886 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005887 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005888 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005889 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005890 doHwResume = true;
5891 mHwPaused = false;
5892 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005893 }
Eric Laurent81784c32012-11-19 14:55:58 -08005894 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005895 // clear effect chain input buffer if the last active track started underruns
5896 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005897 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005898 mEffectChains[0]->clearInputBuffer();
5899 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005900 if (track->isStopping_1()) {
5901 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005902 if (last && mHwPaused) {
5903 doHwResume = true;
5904 mHwPaused = false;
5905 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005906 }
5907 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5908 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005909 // We have consumed all the buffers of this track.
5910 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005911 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005912 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005913 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5914 } else {
5915 audioHALFrames = 0;
5916 }
5917
Andy Hung818e7a32016-02-16 18:08:07 -08005918 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005919 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005920 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08005921 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005922 if (track->isStopping_2()) {
5923 track->mState = TrackBase::STOPPED;
5924 }
Eric Laurent81784c32012-11-19 14:55:58 -08005925 if (track->isStopped()) {
5926 track->reset();
5927 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005928 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005929 }
5930 } else {
5931 // No buffers for this track. Give it a few chances to
5932 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005933 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005934 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005935 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005936 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005937 // indicate to client process that the track was disabled because of underrun;
5938 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005939 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005940 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005941 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5942 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005943 framesReady, minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005944 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005945 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005946 doHwPause = true;
5947 mHwPaused = true;
5948 }
Eric Laurent81784c32012-11-19 14:55:58 -08005949 }
5950 }
5951 }
5952 }
5953
Eric Laurentd1f69b02014-12-15 14:33:13 -08005954 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005955 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005956 for (size_t i = 0; i < mTracks.size(); i++) {
5957 if (mTracks[i]->isFlushPending()) {
5958 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005959 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005960 }
5961 }
5962 }
5963
5964 // make sure the pause/flush/resume sequence is executed in the right order.
5965 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5966 // before flush and then resume HW. This can happen in case of pause/flush/resume
5967 // if resume is received before pause is executed.
5968 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005969 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005970 status_t result = mOutput->stream->pause();
5971 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005972 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005973 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005974 flushHw_l();
5975 }
5976 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005977 status_t result = mOutput->stream->resume();
5978 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005979 }
Eric Laurent81784c32012-11-19 14:55:58 -08005980 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005981 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005982
5983 return mixerStatus;
5984}
5985
5986void AudioFlinger::DirectOutputThread::threadLoop_mix()
5987{
Eric Laurent81784c32012-11-19 14:55:58 -08005988 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005989 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005990 // output audio to hardware
5991 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005992 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005993 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005994 status_t status = mActiveTrack->getNextBuffer(&buffer);
5995 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005996 // no need to pad with 0 for compressed audio
5997 if (audio_has_proportional_frames(mFormat)) {
5998 memset(curBuf, 0, frameCount * mFrameSize);
5999 }
Eric Laurent81784c32012-11-19 14:55:58 -08006000 break;
6001 }
6002 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6003 frameCount -= buffer.frameCount;
6004 curBuf += buffer.frameCount * mFrameSize;
6005 mActiveTrack->releaseBuffer(&buffer);
6006 }
Andy Hung2098f272014-02-27 14:00:06 -08006007 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006008 mSleepTimeUs = 0;
6009 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006010 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006011}
6012
6013void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6014{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006015 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006016 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006017 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006018 return;
6019 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006020 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006021 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07006022 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006023 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006024 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006025 }
Phil Burkfdb3c072016-02-09 10:47:02 -08006026 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08006027 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006028 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006029 }
6030}
6031
Eric Laurentd1f69b02014-12-15 14:33:13 -08006032void AudioFlinger::DirectOutputThread::threadLoop_exit()
6033{
6034 {
6035 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006036 for (size_t i = 0; i < mTracks.size(); i++) {
6037 if (mTracks[i]->isFlushPending()) {
6038 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006039 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006040 }
6041 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006042 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006043 flushHw_l();
6044 }
6045 }
6046 PlaybackThread::threadLoop_exit();
6047}
6048
6049// must be called with thread mutex locked
6050bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6051{
6052 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006053 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006054
vivek mehta9cd7ad12016-03-17 00:18:29 -07006055 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
6056 return !mStandby;
6057 }
6058
Eric Laurentd1f69b02014-12-15 14:33:13 -08006059 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6060 // after a timeout and we will enter standby then.
6061 if (mTracks.size() > 0) {
6062 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006063 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6064 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006065 }
6066
Eric Laurent5cff4032015-05-26 13:49:58 -07006067 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006068}
6069
Eric Laurent10351942014-05-08 18:49:52 -07006070// checkForNewParameter_l() must be called with ThreadBase::mLock held
6071bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6072 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006073{
6074 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08006075 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006076
Eric Laurent10351942014-05-08 18:49:52 -07006077 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006078
Eric Laurent10351942014-05-08 18:49:52 -07006079 AudioParameter param = AudioParameter(keyValuePair);
6080 int value;
6081 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006082 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006083 }
Eric Laurent10351942014-05-08 18:49:52 -07006084 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6085 // do not accept frame count changes if tracks are open as the track buffer
6086 // size depends on frame count and correct behavior would not be garantied
6087 // if frame count is changed after track creation
6088 if (!mTracks.isEmpty()) {
6089 status = INVALID_OPERATION;
6090 } else {
6091 reconfig = true;
6092 }
6093 }
6094 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006095 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006096 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006097 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07006098 mStandby = true;
6099 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006100 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006101 }
6102 if (status == NO_ERROR && reconfig) {
6103 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006104 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006105 }
6106 }
6107
Eric Laurent42537be2016-01-08 17:16:42 -08006108 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08006109}
6110
6111uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6112{
6113 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006114 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006115 time = PlaybackThread::activeSleepTimeUs();
6116 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006117 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006118 }
6119 return time;
6120}
6121
6122uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6123{
6124 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006125 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006126 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6127 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006128 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006129 }
6130 return time;
6131}
6132
6133uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6134{
6135 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006136 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006137 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6138 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006139 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006140 }
6141 return time;
6142}
6143
6144void AudioFlinger::DirectOutputThread::cacheParameters_l()
6145{
6146 PlaybackThread::cacheParameters_l();
6147
6148 // use shorter standby delay as on normal output to release
6149 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006150 // no delay on outputs with HW A/V sync
6151 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006152 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006153 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006154 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006155 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006156 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006157 }
Eric Laurent81784c32012-11-19 14:55:58 -08006158}
6159
Eric Laurente659ef42014-09-29 13:06:46 -07006160void AudioFlinger::DirectOutputThread::flushHw_l()
6161{
Phil Burk062e67a2015-02-11 13:40:50 -08006162 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006163 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006164 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07006165 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Sampath Shetty999f0e82020-01-15 10:19:06 +11006166 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006167}
6168
Andy Hung10cbff12017-02-21 17:30:14 -08006169int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6170 // If a VolumeShaper is active, we must wake up periodically to update volume.
6171 const int64_t NS_PER_MS = 1000000;
6172 return mVolumeShaperActive ?
6173 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6174}
6175
Eric Laurent81784c32012-11-19 14:55:58 -08006176// ----------------------------------------------------------------------------
6177
Eric Laurentbfb1b832013-01-07 09:53:42 -08006178AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006179 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006180 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006181 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006182 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006183 mDrainSequence(0),
6184 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006185{
6186}
6187
6188AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6189{
6190}
6191
6192void AudioFlinger::AsyncCallbackThread::onFirstRef()
6193{
6194 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6195}
6196
6197bool AudioFlinger::AsyncCallbackThread::threadLoop()
6198{
6199 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006200 uint32_t writeAckSequence;
6201 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006202 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006203
6204 {
6205 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006206 while (!((mWriteAckSequence & 1) ||
6207 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006208 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006209 exitPending())) {
6210 mWaitWorkCV.wait(mLock);
6211 }
6212
Eric Laurentbfb1b832013-01-07 09:53:42 -08006213 if (exitPending()) {
6214 break;
6215 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006216 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6217 mWriteAckSequence, mDrainSequence);
6218 writeAckSequence = mWriteAckSequence;
6219 mWriteAckSequence &= ~1;
6220 drainSequence = mDrainSequence;
6221 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006222 asyncError = mAsyncError;
6223 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006224 }
6225 {
Eric Laurent4de95592013-09-26 15:28:21 -07006226 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6227 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006228 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006229 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006230 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006231 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006232 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006233 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006234 if (asyncError) {
6235 playbackThread->onAsyncError();
6236 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006237 }
6238 }
6239 }
6240 return false;
6241}
6242
6243void AudioFlinger::AsyncCallbackThread::exit()
6244{
6245 ALOGV("AsyncCallbackThread::exit");
6246 Mutex::Autolock _l(mLock);
6247 requestExit();
6248 mWaitWorkCV.broadcast();
6249}
6250
Eric Laurent3b4529e2013-09-05 18:09:19 -07006251void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006252{
6253 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006254 // bit 0 is cleared
6255 mWriteAckSequence = sequence << 1;
6256}
6257
6258void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6259{
6260 Mutex::Autolock _l(mLock);
6261 // ignore unexpected callbacks
6262 if (mWriteAckSequence & 2) {
6263 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006264 mWaitWorkCV.signal();
6265 }
6266}
6267
Eric Laurent3b4529e2013-09-05 18:09:19 -07006268void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006269{
6270 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006271 // bit 0 is cleared
6272 mDrainSequence = sequence << 1;
6273}
6274
6275void AudioFlinger::AsyncCallbackThread::resetDraining()
6276{
6277 Mutex::Autolock _l(mLock);
6278 // ignore unexpected callbacks
6279 if (mDrainSequence & 2) {
6280 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006281 mWaitWorkCV.signal();
6282 }
6283}
6284
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006285void AudioFlinger::AsyncCallbackThread::setAsyncError()
6286{
6287 Mutex::Autolock _l(mLock);
6288 mAsyncError = true;
6289 mWaitWorkCV.signal();
6290}
6291
Eric Laurentbfb1b832013-01-07 09:53:42 -08006292
6293// ----------------------------------------------------------------------------
6294AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006295 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6296 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006297 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6298 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006299{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006300 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006301 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006302 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006303}
6304
Eric Laurentbfb1b832013-01-07 09:53:42 -08006305void AudioFlinger::OffloadThread::threadLoop_exit()
6306{
6307 if (mFlushPending || mHwPaused) {
6308 // If a flush is pending or track was paused, just discard buffered data
6309 flushHw_l();
6310 } else {
6311 mMixerStatus = MIXER_DRAIN_ALL;
6312 threadLoop_drain();
6313 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006314 if (mUseAsyncWrite) {
6315 ALOG_ASSERT(mCallbackThread != 0);
6316 mCallbackThread->exit();
6317 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006318 PlaybackThread::threadLoop_exit();
6319}
6320
6321AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6322 Vector< sp<Track> > *tracksToRemove
6323)
6324{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006325 size_t count = mActiveTracks.size();
6326
6327 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006328 bool doHwPause = false;
6329 bool doHwResume = false;
6330
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006331 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006332
Eric Laurentbfb1b832013-01-07 09:53:42 -08006333 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006334 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006335 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006336#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006337 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006338#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006339 // Only consider last track started for volume and mixer state control.
6340 // In theory an older track could underrun and restart after the new one starts
6341 // but as we only care about the transition phase between two tracks on a
6342 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006343 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006344 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006345
Haynes Mathew George7844f672014-01-15 12:32:55 -08006346 if (track->isInvalid()) {
6347 ALOGW("An invalidated track shouldn't be in active list");
6348 tracksToRemove->add(track);
6349 continue;
6350 }
6351
6352 if (track->mState == TrackBase::IDLE) {
6353 ALOGW("An idle track shouldn't be in active list");
6354 continue;
6355 }
6356
Eric Laurentbfb1b832013-01-07 09:53:42 -08006357 if (track->isPausing()) {
6358 track->setPaused();
6359 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006360 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006361 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006362 mHwPaused = true;
6363 }
6364 // If we were part way through writing the mixbuffer to
6365 // the HAL we must save this until we resume
6366 // BUG - this will be wrong if a different track is made active,
6367 // in that case we want to discard the pending data in the
6368 // mixbuffer and tell the client to present it again when the
6369 // track is resumed
6370 mPausedWriteLength = mCurrentWriteLength;
6371 mPausedBytesRemaining = mBytesRemaining;
6372 mBytesRemaining = 0; // stop writing
6373 }
6374 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006375 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006376 if (track->isStopping_1()) {
6377 track->mRetryCount = kMaxTrackStopRetriesOffload;
6378 } else {
6379 track->mRetryCount = kMaxTrackRetriesOffload;
6380 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006381 track->flushAck();
6382 if (last) {
6383 mFlushPending = true;
6384 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006385 } else if (track->isResumePending()){
6386 track->resumeAck();
6387 if (last) {
6388 if (mPausedBytesRemaining) {
6389 // Need to continue write that was interrupted
6390 mCurrentWriteLength = mPausedWriteLength;
6391 mBytesRemaining = mPausedBytesRemaining;
6392 mPausedBytesRemaining = 0;
6393 }
6394 if (mHwPaused) {
6395 doHwResume = true;
6396 mHwPaused = false;
6397 // threadLoop_mix() will handle the case that we need to
6398 // resume an interrupted write
6399 }
6400 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006401 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006402
Eric Laurent3df841a2016-07-15 15:15:40 -07006403 mLeftVolFloat = mRightVolFloat = -1.0;
6404
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006405 // Do not handle new data in this iteration even if track->framesReady()
6406 mixerStatus = MIXER_TRACKS_ENABLED;
6407 }
6408 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006409 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006410 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006411 if (track->mFillingUpStatus == Track::FS_FILLED) {
6412 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006413 if (last) {
6414 // make sure processVolume_l() will apply new volume even if 0
6415 mLeftVolFloat = mRightVolFloat = -1.0;
6416 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006417 }
6418
6419 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006420 sp<Track> previousTrack = mPreviousTrack.promote();
6421 if (previousTrack != 0) {
6422 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006423 // Flush any data still being written from last track
6424 mBytesRemaining = 0;
6425 if (mPausedBytesRemaining) {
6426 // Last track was paused so we also need to flush saved
6427 // mixbuffer state and invalidate track so that it will
6428 // re-submit that unwritten data when it is next resumed
6429 mPausedBytesRemaining = 0;
6430 // Invalidate is a bit drastic - would be more efficient
6431 // to have a flag to tell client that some of the
6432 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006433 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006434 }
6435 // flush data already sent to the DSP if changing audio session as audio
6436 // comes from a different source. Also invalidate previous track to force a
6437 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006438 if (previousTrack->sessionId() != track->sessionId()) {
6439 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006440 }
6441 }
6442 }
6443 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006444 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006445 if (track->isStopping_1()) {
6446 track->mRetryCount = kMaxTrackStopRetriesOffload;
6447 } else {
6448 track->mRetryCount = kMaxTrackRetriesOffload;
6449 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006450 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006451 mixerStatus = MIXER_TRACKS_READY;
6452 }
6453 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006454 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006455 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006456 if (--(track->mRetryCount) <= 0) {
6457 // Hardware buffer can hold a large amount of audio so we must
6458 // wait for all current track's data to drain before we say
6459 // that the track is stopped.
6460 if (mBytesRemaining == 0) {
6461 // Only start draining when all data in mixbuffer
6462 // has been written
6463 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6464 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6465 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6466 if (last && !mStandby) {
6467 // do not modify drain sequence if we are already draining. This happens
6468 // when resuming from pause after drain.
6469 if ((mDrainSequence & 1) == 0) {
6470 mSleepTimeUs = 0;
6471 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6472 mixerStatus = MIXER_DRAIN_TRACK;
6473 mDrainSequence += 2;
6474 }
6475 if (mHwPaused) {
6476 // It is possible to move from PAUSED to STOPPING_1 without
6477 // a resume so we must ensure hardware is running
6478 doHwResume = true;
6479 mHwPaused = false;
6480 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006481 }
6482 }
Eric Laurente93cc032016-05-05 10:15:10 -07006483 } else if (last) {
6484 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6485 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006486 }
6487 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006488 // Drain has completed or we are in standby, signal presentation complete
6489 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006490 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006491 uint32_t latency = 0;
6492 status_t result = mOutput->stream->getLatency(&latency);
6493 ALOGE_IF(result != OK,
6494 "Error when retrieving output stream latency: %d", result);
6495 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006496 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006497 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006498 track->presentationComplete(framesWritten, audioHALFrames);
6499 track->reset();
6500 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006501 // DIRECT and OFFLOADED stop resets frame counts.
6502 if (!mUseAsyncWrite) {
6503 // If we don't get explicit drain notification we must
6504 // register discontinuity regardless of whether this is
6505 // the previous (!last) or the upcoming (last) track
6506 // to avoid skipping the discontinuity.
6507 mTimestampVerifier.discontinuity();
6508 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006509 }
6510 } else {
6511 // No buffers for this track. Give it a few chances to
6512 // fill a buffer, then remove it from active list.
6513 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006514 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006515 uint64_t position = 0;
6516 struct timespec unused;
6517 // The running check restarts the retry counter at least once.
6518 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6519 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6520 running = true;
6521 mOffloadUnderrunPosition = position;
6522 }
6523 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006524 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6525 (long long)position, (long long)mOffloadUnderrunPosition);
6526 }
6527 if (running) { // still running, give us more time.
6528 track->mRetryCount = kMaxTrackRetriesOffload;
6529 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006530 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6531 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006532 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006533 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006534 // it will then automatically call start() when data is available
6535 track->disable();
6536 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006537 } else if (last){
6538 mixerStatus = MIXER_TRACKS_ENABLED;
6539 }
6540 }
6541 }
6542 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006543 if (track->isReady()) { // check ready to prevent premature start.
6544 processVolume_l(track, last);
6545 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006546 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006547
Eric Laurentea0fade2013-10-04 16:23:48 -07006548 // make sure the pause/flush/resume sequence is executed in the right order.
6549 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6550 // before flush and then resume HW. This can happen in case of pause/flush/resume
6551 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006552 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006553 status_t result = mOutput->stream->pause();
6554 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006555 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006556 if (mFlushPending) {
6557 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006558 }
Eric Laurentfd477972013-10-25 18:10:40 -07006559 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006560 status_t result = mOutput->stream->resume();
6561 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006562 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006563
Eric Laurentbfb1b832013-01-07 09:53:42 -08006564 // remove all the tracks that need to be...
6565 removeTracks_l(*tracksToRemove);
6566
6567 return mixerStatus;
6568}
6569
Eric Laurentbfb1b832013-01-07 09:53:42 -08006570// must be called with thread mutex locked
6571bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6572{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006573 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6574 mWriteAckSequence, mDrainSequence);
6575 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006576 return true;
6577 }
6578 return false;
6579}
6580
Eric Laurentbfb1b832013-01-07 09:53:42 -08006581bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6582{
6583 Mutex::Autolock _l(mLock);
6584 return waitingAsyncCallback_l();
6585}
6586
6587void AudioFlinger::OffloadThread::flushHw_l()
6588{
Eric Laurente659ef42014-09-29 13:06:46 -07006589 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006590 // Flush anything still waiting in the mixbuffer
6591 mCurrentWriteLength = 0;
6592 mBytesRemaining = 0;
6593 mPausedWriteLength = 0;
6594 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006595 // reset bytes written count to reflect that DSP buffers are empty after flush.
6596 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006597 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006598
Eric Laurentbfb1b832013-01-07 09:53:42 -08006599 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006600 // discard any pending drain or write ack by incrementing sequence
6601 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6602 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006603 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006604 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6605 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006606 }
6607}
6608
Haynes Mathew George05317d22016-05-03 16:34:26 -07006609void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6610{
6611 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006612 if (PlaybackThread::invalidateTracks_l(streamType)) {
6613 mFlushPending = true;
6614 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006615}
6616
Eric Laurentbfb1b832013-01-07 09:53:42 -08006617// ----------------------------------------------------------------------------
6618
Eric Laurent81784c32012-11-19 14:55:58 -08006619AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006620 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006621 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006622 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006623 mWaitTimeMs(UINT_MAX)
6624{
6625 addOutputTrack(mainThread);
6626}
6627
6628AudioFlinger::DuplicatingThread::~DuplicatingThread()
6629{
6630 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6631 mOutputTracks[i]->destroy();
6632 }
6633}
6634
6635void AudioFlinger::DuplicatingThread::threadLoop_mix()
6636{
6637 // mix buffers...
6638 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006639 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006640 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006641 if (mMixerBufferValid) {
6642 memset(mMixerBuffer, 0, mMixerBufferSize);
6643 } else {
6644 memset(mSinkBuffer, 0, mSinkBufferSize);
6645 }
Eric Laurent81784c32012-11-19 14:55:58 -08006646 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006647 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006648 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006649 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006650 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006651}
6652
6653void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6654{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006655 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006656 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006657 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006658 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006659 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006660 }
6661 } else if (mBytesWritten != 0) {
6662 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6663 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006664 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006665 } else {
6666 // flush remaining overflow buffers in output tracks
6667 writeFrames = 0;
6668 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006669 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006670 }
6671}
6672
Eric Laurentbfb1b832013-01-07 09:53:42 -08006673ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006674{
6675 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006676 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6677
6678 // Consider the first OutputTrack for timestamp and frame counting.
6679
6680 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6681 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6682 // we always claim success.
6683 if (i == 0) {
6684 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6685 ALOGD_IF(correction != 0 && writeFrames != 0,
6686 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6687 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6688 mFramesWritten -= correction;
6689 }
6690
6691 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006692 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006693 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006694 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006695}
6696
6697void AudioFlinger::DuplicatingThread::threadLoop_standby()
6698{
6699 // DuplicatingThread implements standby by stopping all tracks
6700 for (size_t i = 0; i < outputTracks.size(); i++) {
6701 outputTracks[i]->stop();
6702 }
6703}
6704
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006705void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006706{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006707 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006708
6709 std::stringstream ss;
6710 const size_t numTracks = mOutputTracks.size();
6711 ss << " " << numTracks << " OutputTracks";
6712 if (numTracks > 0) {
6713 ss << ":";
6714 for (const auto &track : mOutputTracks) {
6715 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006716 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006717 if (thread.get() != nullptr) {
6718 ss << thread.get() << ", " << thread->id();
6719 } else {
6720 ss << "null";
6721 }
6722 ss << ")";
6723 }
6724 }
6725 ss << "\n";
6726 std::string result = ss.str();
6727 write(fd, result.c_str(), result.size());
6728}
6729
Eric Laurent81784c32012-11-19 14:55:58 -08006730void AudioFlinger::DuplicatingThread::saveOutputTracks()
6731{
6732 outputTracks = mOutputTracks;
6733}
6734
6735void AudioFlinger::DuplicatingThread::clearOutputTracks()
6736{
6737 outputTracks.clear();
6738}
6739
6740void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6741{
6742 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006743 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6744 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6745 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6746 const size_t frameCount =
6747 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6748 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6749 // from different OutputTracks and their associated MixerThreads (e.g. one may
6750 // nearly empty and the other may be dropping data).
6751
6752 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006753 this,
6754 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006755 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006756 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006757 frameCount,
6758 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006759 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6760 if (status != NO_ERROR) {
6761 ALOGE("addOutputTrack() initCheck failed %d", status);
6762 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006763 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006764 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6765 mOutputTracks.add(outputTrack);
6766 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6767 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006768}
6769
6770void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6771{
6772 Mutex::Autolock _l(mLock);
6773 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6774 if (mOutputTracks[i]->thread() == thread) {
6775 mOutputTracks[i]->destroy();
6776 mOutputTracks.removeAt(i);
6777 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006778 if (thread->getOutput() == mOutput) {
6779 mOutput = NULL;
6780 }
Eric Laurent81784c32012-11-19 14:55:58 -08006781 return;
6782 }
6783 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006784 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006785}
6786
6787// caller must hold mLock
6788void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6789{
6790 mWaitTimeMs = UINT_MAX;
6791 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6792 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6793 if (strong != 0) {
6794 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6795 if (waitTimeMs < mWaitTimeMs) {
6796 mWaitTimeMs = waitTimeMs;
6797 }
6798 }
6799 }
6800}
6801
6802
6803bool AudioFlinger::DuplicatingThread::outputsReady(
6804 const SortedVector< sp<OutputTrack> > &outputTracks)
6805{
6806 for (size_t i = 0; i < outputTracks.size(); i++) {
6807 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6808 if (thread == 0) {
6809 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6810 outputTracks[i].get());
6811 return false;
6812 }
6813 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6814 // see note at standby() declaration
6815 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6816 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6817 thread.get());
6818 return false;
6819 }
6820 }
6821 return true;
6822}
6823
Kevin Rocard12381092018-04-11 09:19:59 -07006824void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6825 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006826{
Kevin Rocard12381092018-04-11 09:19:59 -07006827 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6828 outputTrack->setMetadatas(metadata.tracks);
6829 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006830}
6831
Eric Laurent81784c32012-11-19 14:55:58 -08006832uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6833{
6834 return (mWaitTimeMs * 1000) / 2;
6835}
6836
6837void AudioFlinger::DuplicatingThread::cacheParameters_l()
6838{
6839 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6840 updateWaitTime_l();
6841
6842 MixerThread::cacheParameters_l();
6843}
6844
Eric Laurent6acd1d42017-01-04 14:23:29 -08006845
Eric Laurent81784c32012-11-19 14:55:58 -08006846// ----------------------------------------------------------------------------
6847// Record
6848// ----------------------------------------------------------------------------
6849
6850AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6851 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006852 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006853 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006854 ) :
jiabinc52b1ff2019-10-31 17:20:42 -07006855 ThreadBase(audioFlinger, id, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006856 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006857 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006858 mActiveTracks(&this->mLocalLog),
6859 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006860 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006861 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006862 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6863 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006864 // mFastCapture below
6865 , mFastCaptureFutex(0)
6866 // mInputSource
6867 // mPipeSink
6868 // mPipeSource
6869 , mPipeFramesP2(0)
6870 // mPipeMemory
6871 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006872 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006873 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006874{
Glenn Kastend7dca052015-03-05 16:05:54 -08006875 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6876 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006877
Andy Hungc8fddf32018-08-08 18:32:37 -07006878 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6879 mIsMsdDevice = strcmp(
6880 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6881 }
6882
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006883 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006884
Andy Hungc8fddf32018-08-08 18:32:37 -07006885 // TODO: We may also match on address as well as device type for
6886 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07006887 // TODO: This property should be ensure that only contains one single device type.
6888 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6889 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006890 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6891 : AUDIO_DEVICE_NONE));
6892
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006893 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006894 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006895 size_t numCounterOffers = 0;
6896 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006897#if !LOG_NDEBUG
6898 ssize_t index =
6899#else
6900 (void)
6901#endif
6902 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006903 ALOG_ASSERT(index == 0);
6904
6905 // initialize fast capture depending on configuration
6906 bool initFastCapture;
6907 switch (kUseFastCapture) {
6908 case FastCapture_Never:
6909 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006910 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006911 break;
6912 case FastCapture_Always:
6913 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006914 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006915 break;
6916 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006917 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006918 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6919 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6920 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006921 break;
6922 // case FastCapture_Dynamic:
6923 }
6924
6925 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006926 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006927 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006928 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6929 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006930 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006931 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006932 const sp<MemoryDealer> roHeap(readOnlyHeap());
6933 sp<IMemory> pipeMemory;
6934 if ((roHeap == 0) ||
6935 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07006936 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006937 ALOGE("not enough memory for pipe buffer size=%zu; "
6938 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6939 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6940 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006941 goto failed;
6942 }
6943 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6944 memset(pipeBuffer, 0, pipeSize);
6945 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6946 const NBAIO_Format offers[1] = {format};
6947 size_t numCounterOffers = 0;
6948 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6949 ALOG_ASSERT(index == 0);
6950 mPipeSink = pipe;
6951 PipeReader *pipeReader = new PipeReader(*pipe);
6952 numCounterOffers = 0;
6953 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6954 ALOG_ASSERT(index == 0);
6955 mPipeSource = pipeReader;
6956 mPipeFramesP2 = pipeFramesP2;
6957 mPipeMemory = pipeMemory;
6958
6959 // create fast capture
6960 mFastCapture = new FastCapture();
6961 FastCaptureStateQueue *sq = mFastCapture->sq();
6962#ifdef STATE_QUEUE_DUMP
6963 // FIXME
6964#endif
6965 FastCaptureState *state = sq->begin();
6966 state->mCblk = NULL;
6967 state->mInputSource = mInputSource.get();
6968 state->mInputSourceGen++;
6969 state->mPipeSink = pipe;
6970 state->mPipeSinkGen++;
6971 state->mFrameCount = mFrameCount;
6972 state->mCommand = FastCaptureState::COLD_IDLE;
6973 // already done in constructor initialization list
6974 //mFastCaptureFutex = 0;
6975 state->mColdFutexAddr = &mFastCaptureFutex;
6976 state->mColdGen++;
6977 state->mDumpState = &mFastCaptureDumpState;
6978#ifdef TEE_SINK
6979 // FIXME
6980#endif
6981 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6982 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6983 sq->end();
6984 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6985
6986 // start the fast capture
6987 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6988 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006989 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006990 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006991#ifdef AUDIO_WATCHDOG
6992 // FIXME
6993#endif
6994
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006995 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006996 }
Andy Hung8946a282018-04-19 20:04:56 -07006997#ifdef TEE_SINK
6998 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6999 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7000#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007001failed: ;
7002
7003 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007004}
7005
Eric Laurent81784c32012-11-19 14:55:58 -08007006AudioFlinger::RecordThread::~RecordThread()
7007{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007008 if (mFastCapture != 0) {
7009 FastCaptureStateQueue *sq = mFastCapture->sq();
7010 FastCaptureState *state = sq->begin();
7011 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7012 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7013 if (old == -1) {
7014 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7015 }
7016 }
7017 state->mCommand = FastCaptureState::EXIT;
7018 sq->end();
7019 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7020 mFastCapture->join();
7021 mFastCapture.clear();
7022 }
7023 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007024 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007025 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007026}
7027
7028void AudioFlinger::RecordThread::onFirstRef()
7029{
Glenn Kastend7dca052015-03-05 16:05:54 -08007030 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007031}
7032
Eric Laurent555530a2017-02-07 18:17:24 -08007033void AudioFlinger::RecordThread::preExit()
7034{
7035 ALOGV(" preExit()");
7036 Mutex::Autolock _l(mLock);
7037 for (size_t i = 0; i < mTracks.size(); i++) {
7038 sp<RecordTrack> track = mTracks[i];
7039 track->invalidate();
7040 }
7041 mActiveTracks.clear();
7042 mStartStopCond.broadcast();
7043}
7044
Eric Laurent81784c32012-11-19 14:55:58 -08007045bool AudioFlinger::RecordThread::threadLoop()
7046{
Eric Laurent81784c32012-11-19 14:55:58 -08007047 nsecs_t lastWarning = 0;
7048
7049 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007050
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007051reacquire_wakelock:
7052 sp<RecordTrack> activeTrack;
7053 {
7054 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007055 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007056 }
7057
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007058 // used to request a deferred sleep, to be executed later while mutex is unlocked
7059 uint32_t sleepUs = 0;
7060
Andy Hung446f4df2019-02-21 12:26:41 -08007061 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7062
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007063 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007064 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007065 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007066
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007067 // activeTracks accumulates a copy of a subset of mActiveTracks
7068 Vector< sp<RecordTrack> > activeTracks;
7069
Glenn Kasten735f45f2014-08-18 15:51:59 -07007070 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007071 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007072
Glenn Kasten735f45f2014-08-18 15:51:59 -07007073 // reference to a fast track which is about to be removed
7074 sp<RecordTrack> fastTrackToRemove;
7075
Eric Laurent81784c32012-11-19 14:55:58 -08007076 { // scope for mLock
7077 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007078
Eric Laurent021cf962014-05-13 10:18:14 -07007079 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007080
Eric Laurent000a4192014-01-29 15:17:32 -08007081 // check exitPending here because checkForNewParameters_l() and
7082 // checkForNewParameters_l() can temporarily release mLock
7083 if (exitPending()) {
7084 break;
7085 }
7086
Eric Laurent5c25d562016-07-13 17:17:45 -07007087 // sleep with mutex unlocked
7088 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007089 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007090 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7091 ATRACE_END();
7092 sleepUs = 0;
7093 continue;
7094 }
7095
Glenn Kasten2b806402013-11-20 16:37:38 -08007096 // if no active track(s), then standby and release wakelock
7097 size_t size = mActiveTracks.size();
7098 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007099 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007100 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007101 releaseWakeLock_l();
7102 ALOGV("RecordThread: loop stopping");
7103 // go to sleep
7104 mWaitWorkCV.wait(mLock);
7105 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007106 goto reacquire_wakelock;
7107 }
7108
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007109 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007110 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007111 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007112
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007113 activeTrack = mActiveTracks[i];
7114 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007115 if (activeTrack->isFastTrack()) {
7116 ALOG_ASSERT(fastTrackToRemove == 0);
7117 fastTrackToRemove = activeTrack;
7118 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007119 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007120 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007121 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007122 continue;
7123 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007124
7125 TrackBase::track_state activeTrackState = activeTrack->mState;
7126 switch (activeTrackState) {
7127
7128 case TrackBase::PAUSING:
7129 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007130 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007131 doBroadcast = true;
7132 size--;
7133 continue;
7134
7135 case TrackBase::STARTING_1:
7136 sleepUs = 10000;
7137 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007138 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007139 continue;
7140
7141 case TrackBase::STARTING_2:
7142 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007143 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07007144 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007145 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007146 break;
7147
7148 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007149 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007150 break;
7151
Andy Hungce685402018-10-05 17:23:27 -07007152 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7153 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7154 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007155 default:
Andy Hungce685402018-10-05 17:23:27 -07007156 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7157 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007158 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007159
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007160 activeTracks.add(activeTrack);
7161 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07007162
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007163 if (activeTrack->isFastTrack()) {
7164 ALOG_ASSERT(!mFastTrackAvail);
7165 ALOG_ASSERT(fastTrack == 0);
7166 fastTrack = activeTrack;
7167 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007168 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007169
Andy Hungdae27702016-10-31 14:01:16 -07007170 mActiveTracks.updatePowerState(this);
7171
Kevin Rocard069c2712018-03-29 19:09:14 -07007172 updateMetadata_l();
7173
Eric Laurent5c25d562016-07-13 17:17:45 -07007174 if (allStopped) {
7175 standbyIfNotAlreadyInStandby();
7176 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007177 if (doBroadcast) {
7178 mStartStopCond.broadcast();
7179 }
7180
7181 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007182 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007183 if (sleepUs == 0) {
7184 sleepUs = kRecordThreadSleepUs;
7185 }
7186 continue;
7187 }
7188 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007189
Eric Laurent81784c32012-11-19 14:55:58 -08007190 lockEffectChains_l(effectChains);
7191 }
7192
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007193 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007194
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007195 size_t size = effectChains.size();
7196 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007197 // thread mutex is not locked, but effect chain is locked
7198 effectChains[i]->process_l();
7199 }
7200
Glenn Kasten735f45f2014-08-18 15:51:59 -07007201 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007202 if (mFastCapture != 0) {
7203 FastCaptureStateQueue *sq = mFastCapture->sq();
7204 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007205 bool didModify = false;
7206 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007207 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7208 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7209 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7210 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7211 if (old == -1) {
7212 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7213 }
7214 }
7215 state->mCommand = FastCaptureState::READ_WRITE;
7216#if 0 // FIXME
7217 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007218 FastThreadDumpState::kSamplingNforLowRamDevice :
7219 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007220#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007221 didModify = true;
7222 }
7223 audio_track_cblk_t *cblkOld = state->mCblk;
7224 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7225 if (cblkNew != cblkOld) {
7226 state->mCblk = cblkNew;
7227 // block until acked if removing a fast track
7228 if (cblkOld != NULL) {
7229 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7230 }
7231 didModify = true;
7232 }
jiabin01c8f562018-07-19 17:47:28 -07007233 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7234 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7235 if (state->mFastPatchRecordBufferProvider != abp) {
7236 state->mFastPatchRecordBufferProvider = abp;
7237 state->mFastPatchRecordFormat = fastTrack == 0 ?
7238 AUDIO_FORMAT_INVALID : fastTrack->format();
7239 didModify = true;
7240 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007241 sq->end(didModify);
7242 if (didModify) {
7243 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007244#if 0
7245 if (kUseFastCapture == FastCapture_Dynamic) {
7246 mNormalSource = mPipeSource;
7247 }
7248#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007249 }
7250 }
7251
Glenn Kasten735f45f2014-08-18 15:51:59 -07007252 // now run the fast track destructor with thread mutex unlocked
7253 fastTrackToRemove.clear();
7254
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007255 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7256 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7257 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7258 // If destination is non-contiguous, first read past the nominal end of buffer, then
7259 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007260
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007261 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007262 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007263 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007264
7265 // If an NBAIO source is present, use it to read the normal capture's data
7266 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007267 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007268
7269 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7270 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7271 // we immediately retry the read() to get data and prevent another overflow.
7272 for (int retries = 0; retries <= 2; ++retries) {
7273 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7274 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7275 framesToRead);
7276 if (framesRead != OVERRUN) break;
7277 }
7278
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007279 const ssize_t availableToRead = mPipeSource->availableToRead();
7280 if (availableToRead >= 0) {
7281 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
7282 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7283 "more frames to read than fifo size, %zd > %zu",
7284 availableToRead, mPipeFramesP2);
7285 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7286 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7287 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7288 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007289 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7290 }
7291 if (framesRead < 0) {
7292 status_t status = (status_t) framesRead;
7293 switch (status) {
7294 case OVERRUN:
7295 ALOGW("overrun on read from pipe");
7296 framesRead = 0;
7297 break;
7298 case NEGOTIATE:
7299 ALOGE("re-negotiation is needed");
7300 framesRead = -1; // Will cause an attempt to recover.
7301 break;
7302 default:
7303 ALOGE("unknown error %d on read from pipe", status);
7304 break;
7305 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007306 }
7307 // otherwise use the HAL / AudioStreamIn directly
7308 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007309 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007310 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007311 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007312 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007313 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007314 if (result < 0) {
7315 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007316 } else {
7317 framesRead = bytesRead / mFrameSize;
7318 }
7319 }
7320
Andy Hung446f4df2019-02-21 12:26:41 -08007321 const int64_t lastIoEndNs = systemTime(); // end IO timing
7322
Andy Hung3f0c9022016-01-15 17:49:46 -08007323 // Update server timestamp with server stats
7324 // systemTime() is optional if the hardware supports timestamps.
7325 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007326 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
Andy Hung3f0c9022016-01-15 17:49:46 -08007327
7328 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007329 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007330 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007331 if (mStandby) {
7332 mTimestampVerifier.discontinuity();
Mikhail Naganov2534b382019-09-25 13:05:02 -07007333 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007334 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7335
7336 mTimestampVerifier.add(position, time, mSampleRate);
7337
7338 // Correct timestamps
7339 if (isTimestampCorrectionEnabled()) {
7340 ALOGV("TS_BEFORE: %d %lld %lld",
7341 id(), (long long)time, (long long)position);
7342 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7343 position = correctedTimestamp.mFrames;
7344 time = correctedTimestamp.mTimeNs;
7345 ALOGV("TS_AFTER: %d %lld %lld",
7346 id(), (long long)time, (long long)position);
7347 }
7348
Andy Hung3f0c9022016-01-15 17:49:46 -08007349 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7350 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7351 // Note: In general record buffers should tend to be empty in
7352 // a properly running pipeline.
7353 //
7354 // Also, it is not advantageous to call get_presentation_position during the read
7355 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007356 } else {
7357 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007358 }
7359 }
Andy Hunge6c37112019-02-26 17:38:10 -08007360
7361 // From the timestamp, input read latency is negative output write latency.
7362 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7363 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7364 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7365 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7366 mLatencyMs.add(latencyMs);
7367 }
7368
Andy Hung3f0c9022016-01-15 17:49:46 -08007369 // Use this to track timestamp information
7370 // ALOGD("%s", mTimestamp.toString().c_str());
7371
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007372 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007373 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007374 // Force input into standby so that it tries to recover at next read attempt
7375 inputStandBy();
7376 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007377 }
7378 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007379 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007380 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007381 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007382 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007383
Andy Hung8946a282018-04-19 20:04:56 -07007384#ifdef TEE_SINK
7385 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7386#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007387 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007388 {
7389 size_t part1 = mRsmpInFramesP2 - rear;
7390 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007391 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007392 (framesRead - part1) * mFrameSize);
7393 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007394 }
7395 rear = mRsmpInRear += framesRead;
7396
7397 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007398
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007399 // loop over each active track
7400 for (size_t i = 0; i < size; i++) {
7401 activeTrack = activeTracks[i];
7402
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007403 // skip fast tracks, as those are handled directly by FastCapture
7404 if (activeTrack->isFastTrack()) {
7405 continue;
7406 }
7407
Andy Hung73c02e42015-03-29 01:13:58 -07007408 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007409 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7410
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007411 enum {
7412 OVERRUN_UNKNOWN,
7413 OVERRUN_TRUE,
7414 OVERRUN_FALSE
7415 } overrun = OVERRUN_UNKNOWN;
7416
7417 // loop over getNextBuffer to handle circular sink
7418 for (;;) {
7419
7420 activeTrack->mSink.frameCount = ~0;
7421 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7422 size_t framesOut = activeTrack->mSink.frameCount;
7423 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7424
Andy Hung73c02e42015-03-29 01:13:58 -07007425 // check available frames and handle overrun conditions
7426 // if the record track isn't draining fast enough.
7427 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007428 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007429 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7430 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007431 overrun = OVERRUN_TRUE;
7432 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007433 if (framesOut == 0 || framesIn == 0) {
7434 break;
7435 }
7436
Andy Hung6770c6f2015-04-07 13:43:36 -07007437 // Don't allow framesOut to be larger than what is possible with resampling
7438 // from framesIn.
7439 // This isn't strictly necessary but helps limit buffer resizing in
7440 // RecordBufferConverter. TODO: remove when no longer needed.
7441 framesOut = min(framesOut,
7442 destinationFramesPossible(
7443 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007444
7445 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007446 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007447 // straight from RecordThread buffer to RecordTrack buffer.
7448 AudioBufferProvider::Buffer buffer;
7449 buffer.frameCount = framesOut;
7450 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7451 if (status == OK && buffer.frameCount != 0) {
7452 ALOGV_IF(buffer.frameCount != framesOut,
7453 "%s() read less than expected (%zu vs %zu)",
7454 __func__, buffer.frameCount, framesOut);
7455 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007456 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007457 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7458 } else {
7459 framesOut = 0;
7460 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7461 __func__, status, buffer.frameCount);
7462 }
7463 } else {
7464 // process frames from the RecordThread buffer provider to the RecordTrack
7465 // buffer
7466 framesOut = activeTrack->mRecordBufferConverter->convert(
7467 activeTrack->mSink.raw,
7468 activeTrack->mResamplerBufferProvider,
7469 framesOut);
7470 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007471
7472 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7473 overrun = OVERRUN_FALSE;
7474 }
7475
7476 if (activeTrack->mFramesToDrop == 0) {
7477 if (framesOut > 0) {
7478 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007479 // Sanitize before releasing if the track has no access to the source data
7480 // An idle UID receives silence from non virtual devices until active
7481 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007482 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007483 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007484 activeTrack->releaseBuffer(&activeTrack->mSink);
7485 }
7486 } else {
7487 // FIXME could do a partial drop of framesOut
7488 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007489 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007490 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007491 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007492 }
7493 } else {
7494 activeTrack->mFramesToDrop += framesOut;
7495 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7496 activeTrack->mSyncStartEvent->isCancelled()) {
7497 ALOGW("Synced record %s, session %d, trigger session %d",
7498 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7499 activeTrack->sessionId(),
7500 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007501 activeTrack->mSyncStartEvent->triggerSession() :
7502 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007503 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007504 }
7505 }
7506 }
7507
7508 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007509 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007510 }
7511 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007512
7513 switch (overrun) {
7514 case OVERRUN_TRUE:
7515 // client isn't retrieving buffers fast enough
7516 if (!activeTrack->setOverflow()) {
7517 nsecs_t now = systemTime();
7518 // FIXME should lastWarning per track?
7519 if ((now - lastWarning) > kWarningThrottleNs) {
7520 ALOGW("RecordThread: buffer overflow");
7521 lastWarning = now;
7522 }
7523 }
7524 break;
7525 case OVERRUN_FALSE:
7526 activeTrack->clearOverflow();
7527 break;
7528 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007529 break;
7530 }
7531
Andy Hung3f0c9022016-01-15 17:49:46 -08007532 // update frame information and push timestamp out
7533 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007534 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007535 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7536 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007537 }
7538
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007539unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007540 // enable changes in effect chain
7541 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007542 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007543 if (audio_has_proportional_frames(mFormat)
7544 && loopCount == lastLoopCountRead + 1) {
7545 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7546 const double jitterMs =
7547 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7548 {framesRead, readPeriodNs},
7549 {0, 0} /* lastTimestamp */, mSampleRate);
7550 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7551
7552 Mutex::Autolock _l(mLock);
7553 mIoJitterMs.add(jitterMs);
7554 mProcessTimeMs.add(processMs);
7555 }
7556 // update timing info.
7557 mLastIoBeginNs = lastIoBeginNs;
7558 mLastIoEndNs = lastIoEndNs;
7559 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007560 }
7561
Glenn Kasten93e471f2013-08-19 08:40:07 -07007562 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007563
7564 {
7565 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007566 for (size_t i = 0; i < mTracks.size(); i++) {
7567 sp<RecordTrack> track = mTracks[i];
7568 track->invalidate();
7569 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007570 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007571 mStartStopCond.broadcast();
7572 }
7573
7574 releaseWakeLock();
7575
7576 ALOGV("RecordThread %p exiting", this);
7577 return false;
7578}
7579
Glenn Kasten93e471f2013-08-19 08:40:07 -07007580void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007581{
7582 if (!mStandby) {
7583 inputStandBy();
7584 mStandby = true;
7585 }
7586}
7587
7588void AudioFlinger::RecordThread::inputStandBy()
7589{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007590 // Idle the fast capture if it's currently running
7591 if (mFastCapture != 0) {
7592 FastCaptureStateQueue *sq = mFastCapture->sq();
7593 FastCaptureState *state = sq->begin();
7594 if (!(state->mCommand & FastCaptureState::IDLE)) {
7595 state->mCommand = FastCaptureState::COLD_IDLE;
7596 state->mColdFutexAddr = &mFastCaptureFutex;
7597 state->mColdGen++;
7598 mFastCaptureFutex = 0;
7599 sq->end();
7600 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7601 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7602#if 0
7603 if (kUseFastCapture == FastCapture_Dynamic) {
7604 // FIXME
7605 }
7606#endif
7607#ifdef AUDIO_WATCHDOG
7608 // FIXME
7609#endif
7610 } else {
7611 sq->end(false /*didModify*/);
7612 }
7613 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007614 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007615 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007616
7617 // If going into standby, flush the pipe source.
7618 if (mPipeSource.get() != nullptr) {
7619 const ssize_t flushed = mPipeSource->flush();
7620 if (flushed > 0) {
7621 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7622 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7623 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7624 }
7625 }
Eric Laurent81784c32012-11-19 14:55:58 -08007626}
7627
Glenn Kasten05997e22014-03-13 15:08:33 -07007628// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007629sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007630 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007631 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007632 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007633 audio_format_t format,
7634 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007635 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007636 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007637 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007638 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007639 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007640 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007641 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007642 status_t *status,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007643 audio_port_handle_t portId,
7644 const String16& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08007645{
Glenn Kasten74935e42013-12-19 08:56:45 -08007646 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007647 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007648 sp<RecordTrack> track;
7649 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007650 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007651 audio_input_flags_t requestedFlags = *flags;
7652 uint32_t sampleRate;
7653
7654 lStatus = initCheck();
7655 if (lStatus != NO_ERROR) {
7656 ALOGE("createRecordTrack_l() audio driver not initialized");
7657 goto Exit;
7658 }
7659
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007660 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7661 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7662 lStatus = BAD_VALUE;
7663 goto Exit;
7664 }
7665
Eric Laurentf14db3c2017-12-08 14:20:36 -08007666 if (*pSampleRate == 0) {
7667 *pSampleRate = mSampleRate;
7668 }
7669 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007670
7671 // special case for FAST flag considered OK if fast capture is present
7672 if (hasFastCapture()) {
7673 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7674 }
7675
Eric Laurentf14db3c2017-12-08 14:20:36 -08007676 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007677 if ((*flags & inputFlags) != *flags) {
7678 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7679 " input flags (%08x)",
7680 *flags, inputFlags);
7681 *flags = (audio_input_flags_t)(*flags & inputFlags);
7682 }
Eric Laurent81784c32012-11-19 14:55:58 -08007683
Glenn Kasten90e58b12013-07-31 16:16:02 -07007684 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007685 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007686 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007687 // we formerly checked for a callback handler (non-0 tid),
7688 // but that is no longer required for TRANSFER_OBTAIN mode
7689 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007690 // Frame count is not specified (0), or is less than or equal the pipe depth.
7691 // It is OK to provide a higher capacity than requested.
7692 // We will force it to mPipeFramesP2 below.
7693 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007694 // PCM data
7695 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007696 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007697 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007698 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007699 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007700 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007701 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007702 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007703 hasFastCapture() &&
7704 // there are sufficient fast track slots available
7705 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007706 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007707 // check compatibility with audio effects.
7708 Mutex::Autolock _l(mLock);
7709 // Do not accept FAST flag if the session has software effects
7710 sp<EffectChain> chain = getEffectChain_l(sessionId);
7711 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007712 audio_input_flags_t old = *flags;
7713 chain->checkInputFlagCompatibility(flags);
7714 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007715 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7716 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007717 }
7718 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007719 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007720 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7721 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007722 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007723 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7724 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007725 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007726 this, frameCount, mFrameCount, mPipeFramesP2,
7727 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007728 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007729 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007730 }
7731 }
7732
Eric Laurentf14db3c2017-12-08 14:20:36 -08007733 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7734 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7735 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7736 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7737 lStatus = BAD_TYPE;
7738 goto Exit;
7739 }
7740
Glenn Kasten74105912014-07-03 12:28:53 -07007741 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007742 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007743 // fast track: frame count is exactly the pipe depth
7744 frameCount = mPipeFramesP2;
7745 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007746 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007747 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007748 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7749 // or 20 ms if there is a fast capture
7750 // TODO This could be a roundupRatio inline, and const
7751 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7752 * sampleRate + mSampleRate - 1) / mSampleRate;
7753 // minimum number of notification periods is at least kMinNotifications,
7754 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7755 static const size_t kMinNotifications = 3;
7756 static const uint32_t kMinMs = 30;
7757 // TODO This could be a roundupRatio inline
7758 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7759 // TODO This could be a roundupRatio inline
7760 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7761 maxNotificationFrames;
7762 const size_t minFrameCount = maxNotificationFrames *
7763 max(kMinNotifications, minNotificationsByMs);
7764 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007765 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7766 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007767 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007768 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007769 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007770 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007771
7772 { // scope for mLock
7773 Mutex::Autolock _l(mLock);
7774
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007775 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007776 format, channelMask, frameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007777 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, uid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007778 *flags, TrackBase::TYPE_DEFAULT, opPackageName, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007779
Glenn Kasten03003332013-08-06 15:40:54 -07007780 lStatus = track->initCheck();
7781 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007782 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007783 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007784 goto Exit;
7785 }
7786 mTracks.add(track);
7787
Eric Laurent05067782016-06-01 18:27:28 -07007788 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007789 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7790 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7791 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007792 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007793 }
Eric Laurent81784c32012-11-19 14:55:58 -08007794 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007795
Eric Laurent81784c32012-11-19 14:55:58 -08007796 lStatus = NO_ERROR;
7797
7798Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007799 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007800 return track;
7801}
7802
7803status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7804 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007805 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007806{
7807 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7808 sp<ThreadBase> strongMe = this;
7809 status_t status = NO_ERROR;
7810
7811 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007812 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007813 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007814 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007815 triggerSession,
7816 recordTrack->sessionId(),
7817 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007818 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007819 // Sync event can be cancelled by the trigger session if the track is not in a
7820 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007821 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007822 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007823 } else {
7824 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007825 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007826 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007827 }
7828 }
7829
7830 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007831 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007832 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007833 if (recordTrack->isInvalid()) {
7834 recordTrack->clearSyncStartEvent();
7835 return INVALID_OPERATION;
7836 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007837 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7838 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007839 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7840 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007841 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007842 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007843 } else {
7844 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007845 }
7846 return status;
7847 }
7848
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007849 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7850 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7851 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007852 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007853 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007854 status_t status = NO_ERROR;
7855 if (recordTrack->isExternalTrack()) {
7856 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007857 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007858 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007859 if (recordTrack->isInvalid()) {
7860 recordTrack->clearSyncStartEvent();
7861 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7862 recordTrack->mState = TrackBase::STARTING_2;
7863 // STARTING_2 forces destroy to call stopInput.
7864 }
7865 return INVALID_OPERATION;
7866 }
7867 if (recordTrack->mState != TrackBase::STARTING_1) {
7868 ALOGW("%s(%d): unsynchronized mState:%d change",
7869 __func__, recordTrack->id(), recordTrack->mState);
7870 // Someone else has changed state, let them take over,
7871 // leave mState in the new state.
7872 recordTrack->clearSyncStartEvent();
7873 return INVALID_OPERATION;
7874 }
7875 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007876 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007877 ALOGW("%s(%d): startInput failed, status %d",
7878 __func__, recordTrack->id(), status);
7879 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7880 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007881 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007882 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007883 return status;
7884 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07007885 sendIoConfigEvent_l(
7886 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08007887 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07007888
7889 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
7890
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007891 // Catch up with current buffer indices if thread is already running.
7892 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7893 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7894 // see previously buffered data before it called start(), but with greater risk of overrun.
7895
Andy Hung73c02e42015-03-29 01:13:58 -07007896 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007897 if (!recordTrack->isDirect()) {
7898 // clear any converter state as new data will be discontinuous
7899 recordTrack->mRecordBufferConverter->reset();
7900 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007901 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007902 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007903 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007904 return status;
7905 }
Eric Laurent81784c32012-11-19 14:55:58 -08007906}
7907
Eric Laurent81784c32012-11-19 14:55:58 -08007908void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7909{
7910 sp<SyncEvent> strongEvent = event.promote();
7911
7912 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007913 sp<RefBase> ptr = strongEvent->cookie().promote();
7914 if (ptr != 0) {
7915 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7916 recordTrack->handleSyncStartEvent(strongEvent);
7917 }
Eric Laurent81784c32012-11-19 14:55:58 -08007918 }
7919}
7920
Glenn Kastena8356f62013-07-25 14:37:52 -07007921bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007922 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007923 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007924 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007925 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007926 return false;
7927 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007928 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007929 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007930
Andy Hungabfab202019-03-07 19:45:54 -08007931 // NOTE: Waiting here is important to keep stop synchronous.
7932 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07007933 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7934 mWaitWorkCV.broadcast(); // signal thread to stop
7935 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007936 }
Andy Hungce685402018-10-05 17:23:27 -07007937
7938 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007939 ALOGV("Record stopped OK");
7940 return true;
7941 }
Andy Hungce685402018-10-05 17:23:27 -07007942
7943 // don't handle anything - we've been invalidated or restarted and in a different state
7944 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7945 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007946 return false;
7947}
7948
Glenn Kasten0f11b512014-01-31 16:18:54 -08007949bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007950{
7951 return false;
7952}
7953
Glenn Kasten0f11b512014-01-31 16:18:54 -08007954status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007955{
7956#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7957 if (!isValidSyncEvent(event)) {
7958 return BAD_VALUE;
7959 }
7960
Glenn Kastend848eb42016-03-08 13:42:11 -08007961 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007962 status_t ret = NAME_NOT_FOUND;
7963
7964 Mutex::Autolock _l(mLock);
7965
7966 for (size_t i = 0; i < mTracks.size(); i++) {
7967 sp<RecordTrack> track = mTracks[i];
7968 if (eventSession == track->sessionId()) {
7969 (void) track->setSyncEvent(event);
7970 ret = NO_ERROR;
7971 }
7972 }
7973 return ret;
7974#else
7975 return BAD_VALUE;
7976#endif
7977}
7978
jiabin653cc0a2018-01-17 17:54:10 -08007979status_t AudioFlinger::RecordThread::getActiveMicrophones(
7980 std::vector<media::MicrophoneInfo>* activeMicrophones)
7981{
7982 ALOGV("RecordThread::getActiveMicrophones");
7983 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007984 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7985 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007986}
7987
Paul McLean12340082019-03-19 09:35:05 -06007988status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
7989 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007990{
Paul McLean12340082019-03-19 09:35:05 -06007991 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007992 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007993 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007994}
7995
Paul McLean12340082019-03-19 09:35:05 -06007996status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007997{
Paul McLean12340082019-03-19 09:35:05 -06007998 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007999 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008000 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008001}
8002
Kevin Rocard069c2712018-03-29 19:09:14 -07008003void AudioFlinger::RecordThread::updateMetadata_l()
8004{
8005 if (mInput == nullptr || mInput->stream == nullptr ||
8006 !mActiveTracks.readAndClearHasChanged()) {
8007 return;
8008 }
8009 StreamInHalInterface::SinkMetadata metadata;
8010 for (const sp<RecordTrack> &track : mActiveTracks) {
8011 // No track is invalid as this is called after prepareTrack_l in the same critical section
8012 metadata.tracks.push_back({
8013 .source = track->attributes().source,
8014 .gain = 1, // capture tracks do not have volumes
8015 });
8016 }
8017 mInput->stream->updateSinkMetadata(metadata);
8018}
8019
Eric Laurent81784c32012-11-19 14:55:58 -08008020// destroyTrack_l() must be called with ThreadBase::mLock held
8021void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8022{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008023 track->terminate();
8024 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08008025 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008026 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008027 removeTrack_l(track);
8028 }
8029}
8030
8031void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8032{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008033 String8 result;
8034 track->appendDump(result, false /* active */);
8035 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8036
Eric Laurent81784c32012-11-19 14:55:58 -08008037 mTracks.remove(track);
8038 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008039 if (track->isFastTrack()) {
8040 ALOG_ASSERT(!mFastTrackAvail);
8041 mFastTrackAvail = true;
8042 }
Eric Laurent81784c32012-11-19 14:55:58 -08008043}
8044
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008045void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008046{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008047 AudioStreamIn *input = mInput;
8048 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8049 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008050 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008051 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008052 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008053 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008054 }
Andy Hungbfa64962017-06-12 14:43:19 -07008055
8056 if (input != nullptr) {
8057 dprintf(fd, " Hal stream dump:\n");
8058 (void)input->stream->dump(fd);
8059 }
8060
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008061 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008062 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008063
Glenn Kasten2f90c512015-12-02 11:40:09 -08008064 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8065 // while we are dumping it. It may be inconsistent, but it won't mutate!
8066 // This is a large object so we place it on the heap.
8067 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008068 const std::unique_ptr<FastCaptureDumpState> copy =
8069 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008070 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008071}
8072
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008073void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008074{
Eric Laurent81784c32012-11-19 14:55:58 -08008075 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008076 size_t numtracks = mTracks.size();
8077 size_t numactive = mActiveTracks.size();
8078 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008079 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008080 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008081 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008082 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008083 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008084 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008085 for (size_t i = 0; i < numtracks ; ++i) {
8086 sp<RecordTrack> track = mTracks[i];
8087 if (track != 0) {
8088 bool active = mActiveTracks.indexOf(track) >= 0;
8089 if (active) {
8090 numactiveseen++;
8091 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008092 result.append(prefix);
8093 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008094 }
Eric Laurent81784c32012-11-19 14:55:58 -08008095 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008096 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008097 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008098 }
8099
Marco Nelissenb2208842014-02-07 14:00:50 -08008100 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008101 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008102 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008103 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008104 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008105 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008106 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008107 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008108 result.append(prefix);
8109 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008110 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008111 }
Eric Laurent81784c32012-11-19 14:55:58 -08008112
8113 }
8114 write(fd, result.string(), result.size());
8115}
8116
Eric Laurent5ada82e2019-08-29 17:53:54 -07008117void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008118{
8119 Mutex::Autolock _l(mLock);
8120 for (size_t i = 0; i < mTracks.size() ; i++) {
8121 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008122 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008123 track->setSilenced(silenced);
8124 }
8125 }
8126}
Andy Hung73c02e42015-03-29 01:13:58 -07008127
8128void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8129{
8130 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8131 RecordThread *recordThread = (RecordThread *) threadBase.get();
8132 mRsmpInFront = recordThread->mRsmpInRear;
8133 mRsmpInUnrel = 0;
8134}
8135
8136void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8137 size_t *framesAvailable, bool *hasOverrun)
8138{
8139 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8140 RecordThread *recordThread = (RecordThread *) threadBase.get();
8141 const int32_t rear = recordThread->mRsmpInRear;
8142 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008143 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008144
8145 size_t framesIn;
8146 bool overrun = false;
8147 if (filled < 0) {
8148 // should not happen, but treat like a massive overrun and re-sync
8149 framesIn = 0;
8150 mRsmpInFront = rear;
8151 overrun = true;
8152 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8153 framesIn = (size_t) filled;
8154 } else {
8155 // client is not keeping up with server, but give it latest data
8156 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008157 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8158 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008159 overrun = true;
8160 }
8161 if (framesAvailable != NULL) {
8162 *framesAvailable = framesIn;
8163 }
8164 if (hasOverrun != NULL) {
8165 *hasOverrun = overrun;
8166 }
8167}
8168
Eric Laurent81784c32012-11-19 14:55:58 -08008169// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008170status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008171 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008172{
Andy Hung73c02e42015-03-29 01:13:58 -07008173 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008174 if (threadBase == 0) {
8175 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008176 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008177 return NOT_ENOUGH_DATA;
8178 }
8179 RecordThread *recordThread = (RecordThread *) threadBase.get();
8180 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008181 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008182 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008183 // FIXME should not be P2 (don't want to increase latency)
8184 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008185 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008186 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008187 front &= recordThread->mRsmpInFramesP2 - 1;
8188 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008189 if (part1 > (size_t) filled) {
8190 part1 = filled;
8191 }
8192 size_t ask = buffer->frameCount;
8193 ALOG_ASSERT(ask > 0);
8194 if (part1 > ask) {
8195 part1 = ask;
8196 }
8197 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008198 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008199 buffer->raw = NULL;
8200 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008201 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008202 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008203 }
8204
Andy Hung57446612015-04-19 23:56:46 -07008205 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008206 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008207 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008208 return NO_ERROR;
8209}
8210
8211// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008212void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8213 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008214{
Hongwei Wang95e37682019-04-12 11:13:36 -07008215 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008216 if (stepCount == 0) {
8217 return;
8218 }
Andy Hung73c02e42015-03-29 01:13:58 -07008219 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8220 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008221 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008222 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008223 buffer->frameCount = 0;
8224}
8225
Eric Laurentd8365c52017-07-16 15:27:05 -07008226void AudioFlinger::RecordThread::checkBtNrec()
8227{
8228 Mutex::Autolock _l(mLock);
8229 checkBtNrec_l();
8230}
8231
8232void AudioFlinger::RecordThread::checkBtNrec_l()
8233{
8234 // disable AEC and NS if the device is a BT SCO headset supporting those
8235 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008236 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008237 mAudioFlinger->btNrecIsOff();
8238 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8239 for (size_t i = 0; i < mEffectChains.size(); i++) {
8240 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8241 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8242 }
8243 }
8244}
8245
Andy Hung97a893e2015-03-29 01:03:07 -07008246
Eric Laurent10351942014-05-08 18:49:52 -07008247bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8248 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008249{
8250 bool reconfig = false;
8251
Eric Laurent10351942014-05-08 18:49:52 -07008252 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008253
Eric Laurent10351942014-05-08 18:49:52 -07008254 audio_format_t reqFormat = mFormat;
8255 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008256 // 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 -07008257 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8258
8259 AudioParameter param = AudioParameter(keyValuePair);
8260 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008261
8262 // scope for AutoPark extends to end of method
8263 AutoPark<FastCapture> park(mFastCapture);
8264
Eric Laurent10351942014-05-08 18:49:52 -07008265 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8266 // channel count change can be requested. Do we mandate the first client defines the
8267 // HAL sampling rate and channel count or do we allow changes on the fly?
8268 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8269 samplingRate = value;
8270 reconfig = true;
8271 }
8272 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008273 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008274 status = BAD_VALUE;
8275 } else {
8276 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008277 reconfig = true;
8278 }
Eric Laurent10351942014-05-08 18:49:52 -07008279 }
8280 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8281 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008282 if (!audio_is_input_channel(mask) ||
8283 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008284 status = BAD_VALUE;
8285 } else {
8286 channelMask = mask;
8287 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008288 }
Eric Laurent10351942014-05-08 18:49:52 -07008289 }
8290 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8291 // do not accept frame count changes if tracks are open as the track buffer
8292 // size depends on frame count and correct behavior would not be guaranteed
8293 // if frame count is changed after track creation
8294 if (mActiveTracks.size() > 0) {
8295 status = INVALID_OPERATION;
8296 } else {
8297 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008298 }
Eric Laurent10351942014-05-08 18:49:52 -07008299 }
8300 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008301 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008302 }
8303 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8304 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008305 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008306 }
Glenn Kastene198c362013-08-13 09:13:36 -07008307
Eric Laurent10351942014-05-08 18:49:52 -07008308 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008309 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008310 if (status == INVALID_OPERATION) {
8311 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008312 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008313 }
8314 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008315 if (status == BAD_VALUE) {
8316 uint32_t sRate;
8317 audio_channel_mask_t channelMask;
8318 audio_format_t format;
8319 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8320 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8321 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8322 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8323 status = NO_ERROR;
8324 }
Eric Laurent81784c32012-11-19 14:55:58 -08008325 }
Eric Laurent10351942014-05-08 18:49:52 -07008326 if (status == NO_ERROR) {
8327 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008328 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008329 }
8330 }
Eric Laurent81784c32012-11-19 14:55:58 -08008331 }
Eric Laurent10351942014-05-08 18:49:52 -07008332
Eric Laurent81784c32012-11-19 14:55:58 -08008333 return reconfig;
8334}
8335
8336String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8337{
Eric Laurent81784c32012-11-19 14:55:58 -08008338 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008339 if (initCheck() == NO_ERROR) {
8340 String8 out_s8;
8341 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8342 return out_s8;
8343 }
Eric Laurent81784c32012-11-19 14:55:58 -08008344 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008345 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008346}
8347
Eric Laurent09f1ed22019-04-24 17:45:17 -07008348void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8349 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008350 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8351
8352 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008353
8354 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008355 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008356 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008357 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008358 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008359 desc->mChannelMask = mChannelMask;
8360 desc->mSamplingRate = mSampleRate;
8361 desc->mFormat = mFormat;
8362 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008363 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008364 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008365 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008366 case AUDIO_CLIENT_STARTED:
8367 desc->mPatch = mPatch;
8368 desc->mPortId = portId;
8369 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008370 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008371 default:
8372 break;
8373 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008374 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008375}
8376
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008377void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008378{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008379 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8380 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008381 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008382 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8383 if (audio_is_linear_pcm(mFormat)) {
8384 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8385 mChannelCount, FCC_8);
8386 } else {
8387 // Can have more that FCC_8 channels in encoded streams.
8388 ALOGI("HAL format %#x is not linear pcm", mFormat);
8389 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008390 result = mInput->stream->getFrameSize(&mFrameSize);
8391 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8392 result = mInput->stream->getBufferSize(&mBufferSize);
8393 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008394 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008395 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
8396 "mBufferSize=%lld, mFrameCount=%lld",
8397 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
8398 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008399 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008400 // 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 -07008401 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008402 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008403 // A larger value should allow more old data to be read after a track calls start(),
8404 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008405 //
8406 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008407 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008408 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008409 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008410 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008411
8412 // TODO optimize audio capture buffer sizes ...
8413 // Here we calculate the size of the sliding buffer used as a source
8414 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8415 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8416 // be better to have it derived from the pipe depth in the long term.
8417 // The current value is higher than necessary. However it should not add to latency.
8418
Glenn Kasten85948432013-08-19 12:09:05 -07008419 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008420 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8421 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008422 // if posix_memalign fails, will segv here.
8423 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008424
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008425 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8426 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08008427}
8428
Glenn Kasten5f972c02014-01-13 09:59:31 -08008429uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008430{
8431 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008432 uint32_t result;
8433 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8434 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008435 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008436 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008437}
8438
Glenn Kastend848eb42016-03-08 13:42:11 -08008439KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008440{
Glenn Kastend848eb42016-03-08 13:42:11 -08008441 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008442 Mutex::Autolock _l(mLock);
8443 for (size_t j = 0; j < mTracks.size(); ++j) {
8444 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008445 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008446 if (ids.indexOfKey(sessionId) < 0) {
8447 ids.add(sessionId, true);
8448 }
8449 }
8450 return ids;
8451}
8452
8453AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8454{
8455 Mutex::Autolock _l(mLock);
8456 AudioStreamIn *input = mInput;
8457 mInput = NULL;
8458 return input;
8459}
8460
8461// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008462sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008463{
8464 if (mInput == NULL) {
8465 return NULL;
8466 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008467 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008468}
8469
8470status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8471{
Eric Laurent81784c32012-11-19 14:55:58 -08008472 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008473 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008474 chain->setInBuffer(NULL);
8475 chain->setOutBuffer(NULL);
8476
8477 checkSuspendOnAddEffectChain_l(chain);
8478
Eric Laurent1b928682014-10-02 19:41:47 -07008479 // make sure enabled pre processing effects state is communicated to the HAL as we
8480 // just moved them to a new input stream.
8481 chain->syncHalEffectsState();
8482
Eric Laurent81784c32012-11-19 14:55:58 -08008483 mEffectChains.add(chain);
8484
8485 return NO_ERROR;
8486}
8487
8488size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8489{
8490 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008491
8492 for (size_t i = 0; i < mEffectChains.size(); i++) {
8493 if (chain == mEffectChains[i]) {
8494 mEffectChains.removeAt(i);
8495 break;
8496 }
Eric Laurent81784c32012-11-19 14:55:58 -08008497 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008498 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008499}
8500
Eric Laurent1c333e22014-05-20 10:48:17 -07008501status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8502 audio_patch_handle_t *handle)
8503{
8504 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008505
8506 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008507 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8508 mInDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
François Gaffie0c280aa2018-07-25 10:02:15 +02008509 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008510 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008511 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008512 }
8513
Eric Laurentd8365c52017-07-16 15:27:05 -07008514 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008515
8516 // store new source and send to effects
8517 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8518 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008519 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008520 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008521 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008522 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008523
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008524 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008525 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8526 status = hwDevice->createAudioPatch(patch->num_sources,
8527 patch->sources,
8528 patch->num_sinks,
8529 patch->sinks,
8530 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008531 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008532 char *address;
8533 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8534 address = audio_device_address_to_parameter(
8535 patch->sources[0].ext.device.type,
8536 patch->sources[0].ext.device.address);
8537 } else {
8538 address = (char *)calloc(1, 1);
8539 }
8540 AudioParameter param = AudioParameter(String8(address));
8541 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008542 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008543 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008544 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008545 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008546 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008547 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008548 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008549
jiabinc52b1ff2019-10-31 17:20:42 -07008550 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008551 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008552 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008553 }
Eric Laurent296fb132015-05-01 11:38:42 -07008554
Andy Hungc2b11cb2020-04-22 09:04:01 -07008555 const std::string pathSourcesAsString = patchSourcesToString(patch);
8556 mediametrics::LogItem item(mMetricsId);
8557 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATEAUDIOPATCH)
8558 .set(AMEDIAMETRICS_PROP_INPUTDEVICES, pathSourcesAsString.c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08008559 .set(AMEDIAMETRICS_PROP_SOURCE, toString(mAudioSource).c_str())
8560 .record();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008561 // also dispatch to active AudioRecords
8562 for (const auto &track : mActiveTracks) {
8563 track->logEndInterval();
8564 track->logBeginInterval(pathSourcesAsString);
8565 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008566 return status;
8567}
8568
8569status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8570{
8571 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008572
jiabinc52b1ff2019-10-31 17:20:42 -07008573 mPatch = audio_patch{};
8574 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008575
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008576 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008577 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8578 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008579 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008580 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008581 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008582 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008583 }
8584 return status;
8585}
8586
jiabinc52b1ff2019-10-31 17:20:42 -07008587void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8588{
8589 mOutDevices = outDevices;
8590 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8591 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008592 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008593 }
8594}
8595
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008596void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008597{
8598 Mutex::Autolock _l(mLock);
8599 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008600 if (record->getSource()) {
8601 mSource = record->getSource();
8602 }
Eric Laurent83b88082014-06-20 18:31:16 -07008603}
8604
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008605void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008606{
8607 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008608 if (mSource == record->getSource()) {
8609 mSource = mInput;
8610 }
Eric Laurent83b88082014-06-20 18:31:16 -07008611 destroyTrack_l(record);
8612}
8613
Mikhail Naganovdc769682018-05-04 15:34:08 -07008614void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008615{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008616 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008617 config->role = AUDIO_PORT_ROLE_SINK;
8618 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8619 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008620 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8621 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8622 config->flags.input = mInput->flags;
8623 }
Eric Laurent83b88082014-06-20 18:31:16 -07008624}
Eric Laurent1c333e22014-05-20 10:48:17 -07008625
Eric Laurent6acd1d42017-01-04 14:23:29 -08008626// ----------------------------------------------------------------------------
8627// Mmap
8628// ----------------------------------------------------------------------------
8629
8630AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8631 : mThread(thread)
8632{
Phil Burk9fabbf82017-08-03 12:02:00 -07008633 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008634}
8635
8636AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8637{
Phil Burk9fabbf82017-08-03 12:02:00 -07008638 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008639}
8640
8641status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8642 struct audio_mmap_buffer_info *info)
8643{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008644 return mThread->createMmapBuffer(minSizeFrames, info);
8645}
8646
8647status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8648{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008649 return mThread->getMmapPosition(position);
8650}
8651
Eric Laurenta54f1282017-07-01 19:39:32 -07008652status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008653 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008654
8655{
jiabind1f1cb62020-03-24 11:57:57 -07008656 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008657}
8658
8659status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8660{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008661 return mThread->stop(handle);
8662}
8663
Eric Laurent18b57012017-02-13 16:23:52 -08008664status_t AudioFlinger::MmapThreadHandle::standby()
8665{
Eric Laurent18b57012017-02-13 16:23:52 -08008666 return mThread->standby();
8667}
8668
Eric Laurent6acd1d42017-01-04 14:23:29 -08008669
8670AudioFlinger::MmapThread::MmapThread(
8671 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07008672 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady)
8673 : ThreadBase(audioFlinger, id, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008674 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008675 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008676 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008677 mActiveTracks(&this->mLocalLog),
8678 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8679 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008680{
Eric Laurent18b57012017-02-13 16:23:52 -08008681 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008682 readHalParameters_l();
8683}
8684
8685AudioFlinger::MmapThread::~MmapThread()
8686{
Eric Laurent18b57012017-02-13 16:23:52 -08008687 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008688}
8689
8690void AudioFlinger::MmapThread::onFirstRef()
8691{
8692 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8693}
8694
8695void AudioFlinger::MmapThread::disconnect()
8696{
Eric Laurent331679c2018-04-16 17:03:16 -07008697 ActiveTracks<MmapTrack> activeTracks;
8698 {
8699 Mutex::Autolock _l(mLock);
8700 for (const sp<MmapTrack> &t : mActiveTracks) {
8701 activeTracks.add(t);
8702 }
8703 }
8704 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008705 stop(t->portId());
8706 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008707 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008708 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008709 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008710 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008711 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008712 }
8713}
8714
8715
8716void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8717 audio_stream_type_t streamType __unused,
8718 audio_session_t sessionId,
8719 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008720 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008721 audio_port_handle_t portId)
8722{
8723 mAttr = *attr;
8724 mSessionId = sessionId;
8725 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008726 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008727 mPortId = portId;
8728}
8729
8730status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8731 struct audio_mmap_buffer_info *info)
8732{
8733 if (mHalStream == 0) {
8734 return NO_INIT;
8735 }
Eric Laurent18b57012017-02-13 16:23:52 -08008736 mStandby = true;
8737 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008738 return mHalStream->createMmapBuffer(minSizeFrames, info);
8739}
8740
8741status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8742{
8743 if (mHalStream == 0) {
8744 return NO_INIT;
8745 }
8746 return mHalStream->getMmapPosition(position);
8747}
8748
Eric Laurent331679c2018-04-16 17:03:16 -07008749status_t AudioFlinger::MmapThread::exitStandby()
8750{
8751 status_t ret = mHalStream->start();
8752 if (ret != NO_ERROR) {
8753 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8754 return ret;
8755 }
8756 mStandby = false;
8757 return NO_ERROR;
8758}
8759
Eric Laurenta54f1282017-07-01 19:39:32 -07008760status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008761 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008762 audio_port_handle_t *handle)
8763{
Eric Laurenta54f1282017-07-01 19:39:32 -07008764 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8765 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008766 if (mHalStream == 0) {
8767 return NO_INIT;
8768 }
8769
8770 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008771
Eric Laurenta54f1282017-07-01 19:39:32 -07008772 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008773 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008774 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008775 }
8776
8777 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8778
8779 audio_io_handle_t io = mId;
8780 if (isOutput()) {
8781 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8782 config.sample_rate = mSampleRate;
8783 config.channel_mask = mChannelMask;
8784 config.format = mFormat;
8785 audio_stream_type_t stream = streamType();
8786 audio_output_flags_t flags =
8787 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008788 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008789 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008790 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8791 mSessionId,
8792 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008793 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008794 client.clientUid,
8795 &config,
8796 flags,
8797 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008798 &portId,
8799 &secondaryOutputs);
8800 ALOGD_IF(!secondaryOutputs.empty(),
8801 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008802 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008803 audio_config_base_t config;
8804 config.sample_rate = mSampleRate;
8805 config.channel_mask = mChannelMask;
8806 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008807 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008808 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07008809 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07008810 mSessionId,
8811 client.clientPid,
8812 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008813 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008814 &config,
8815 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8816 &deviceId,
8817 &portId);
8818 }
8819 // APM should not chose a different input or output stream for the same set of attributes
8820 // and audo configuration
8821 if (ret != NO_ERROR || io != mId) {
8822 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8823 __FUNCTION__, ret, io, mId);
8824 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008825 }
8826
8827 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008828 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008829 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008830 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008831 }
8832
Eric Laurent331679c2018-04-16 17:03:16 -07008833 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008834 // abort if start is rejected by audio policy manager
8835 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008836 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008837 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008838 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008839 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008840 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008841 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008842 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008843 }
Eric Laurent331679c2018-04-16 17:03:16 -07008844 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008845 } else {
8846 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008847 }
8848 return PERMISSION_DENIED;
8849 }
8850
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008851 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07008852 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
8853 mChannelMask, mSessionId, isOutput(), client.clientUid,
8854 client.clientPid, IPCThreadState::self()->getCallingPid(),
8855 portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008856
Eric Laurent4eb58f12018-12-07 16:41:02 -08008857 if (isOutput()) {
8858 // force volume update when a new track is added
8859 mHalVolFloat = -1.0f;
8860 } else if (!track->isSilenced_l()) {
8861 for (const sp<MmapTrack> &t : mActiveTracks) {
8862 if (t->isSilenced_l() && t->uid() != client.clientUid)
8863 t->invalidate();
8864 }
8865 }
8866
8867
Eric Laurent6acd1d42017-01-04 14:23:29 -08008868 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008869 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008870 if (chain != 0) {
8871 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8872 chain->incTrackCnt();
8873 chain->incActiveTrackCnt();
8874 }
8875
Andy Hungc2b11cb2020-04-22 09:04:01 -07008876 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08008877 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008878 broadcast_l();
8879
Eric Laurenta54f1282017-07-01 19:39:32 -07008880 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008881
8882 return NO_ERROR;
8883}
8884
8885status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8886{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008887 ALOGV("%s handle %d", __FUNCTION__, handle);
8888
8889 if (mHalStream == 0) {
8890 return NO_INIT;
8891 }
8892
Eric Laurenta54f1282017-07-01 19:39:32 -07008893 if (handle == mPortId) {
8894 mHalStream->stop();
8895 return NO_ERROR;
8896 }
8897
Eric Laurent331679c2018-04-16 17:03:16 -07008898 Mutex::Autolock _l(mLock);
8899
Eric Laurent6acd1d42017-01-04 14:23:29 -08008900 sp<MmapTrack> track;
8901 for (const sp<MmapTrack> &t : mActiveTracks) {
8902 if (handle == t->portId()) {
8903 track = t;
8904 break;
8905 }
8906 }
8907 if (track == 0) {
8908 return BAD_VALUE;
8909 }
8910
8911 mActiveTracks.remove(track);
8912
Eric Laurent331679c2018-04-16 17:03:16 -07008913 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008914 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008915 AudioSystem::stopOutput(track->portId());
8916 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008917 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008918 AudioSystem::stopInput(track->portId());
8919 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008920 }
Eric Laurent331679c2018-04-16 17:03:16 -07008921 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008922
8923 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8924 if (chain != 0) {
8925 chain->decActiveTrackCnt();
8926 chain->decTrackCnt();
8927 }
8928
8929 broadcast_l();
8930
Eric Laurent6acd1d42017-01-04 14:23:29 -08008931 return NO_ERROR;
8932}
8933
Eric Laurent18b57012017-02-13 16:23:52 -08008934status_t AudioFlinger::MmapThread::standby()
8935{
8936 ALOGV("%s", __FUNCTION__);
8937
8938 if (mHalStream == 0) {
8939 return NO_INIT;
8940 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008941 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008942 return INVALID_OPERATION;
8943 }
8944 mHalStream->standby();
8945 mStandby = true;
8946 releaseWakeLock();
8947 return NO_ERROR;
8948}
8949
Eric Laurent6acd1d42017-01-04 14:23:29 -08008950
8951void AudioFlinger::MmapThread::readHalParameters_l()
8952{
8953 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8954 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8955 mFormat = mHALFormat;
8956 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8957 result = mHalStream->getFrameSize(&mFrameSize);
8958 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8959 result = mHalStream->getBufferSize(&mBufferSize);
8960 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8961 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07008962
8963 mediametrics::LogItem item(mMetricsId);
8964 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8965 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8966 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8967 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8968 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8969 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8970 /*
8971 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8972 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
8973 (int32_t)mHapticChannelMask)
8974 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
8975 (int32_t)mHapticChannelCount)
8976 */
8977 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
8978 formatToString(mHALFormat).c_str())
8979 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
8980 (int32_t)mFrameCount) // sic - added HAL
8981 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008982}
8983
8984bool AudioFlinger::MmapThread::threadLoop()
8985{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008986 checkSilentMode_l();
8987
8988 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8989
8990 while (!exitPending())
8991 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008992 Vector< sp<EffectChain> > effectChains;
8993
Andy Hung13850be2019-03-14 11:33:09 -07008994 { // under Thread lock
8995 Mutex::Autolock _l(mLock);
8996
Eric Laurent6acd1d42017-01-04 14:23:29 -08008997 if (mSignalPending) {
8998 // A signal was raised while we were unlocked
8999 mSignalPending = false;
9000 } else {
9001 if (mConfigEvents.isEmpty()) {
9002 // we're about to wait, flush the binder command buffer
9003 IPCThreadState::self()->flushCommands();
9004
9005 if (exitPending()) {
9006 break;
9007 }
9008
Eric Laurent6acd1d42017-01-04 14:23:29 -08009009 // wait until we have something to do...
9010 ALOGV("%s going to sleep", myName.string());
9011 mWaitWorkCV.wait(mLock);
9012 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009013
9014 checkSilentMode_l();
9015
9016 continue;
9017 }
9018 }
9019
9020 processConfigEvents_l();
9021
9022 processVolume_l();
9023
9024 checkInvalidTracks_l();
9025
9026 mActiveTracks.updatePowerState(this);
9027
Kevin Rocard069c2712018-03-29 19:09:14 -07009028 updateMetadata_l();
9029
Eric Laurent6acd1d42017-01-04 14:23:29 -08009030 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009031 } // release Thread lock
9032
Eric Laurent6acd1d42017-01-04 14:23:29 -08009033 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009034 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009035 }
Andy Hung13850be2019-03-14 11:33:09 -07009036
9037 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009038 unlockEffectChains(effectChains);
9039 // Effect chains will be actually deleted here if they were removed from
9040 // mEffectChains list during mixing or effects processing
9041 }
9042
9043 threadLoop_exit();
9044
9045 if (!mStandby) {
9046 threadLoop_standby();
9047 mStandby = true;
9048 }
9049
Eric Laurent6acd1d42017-01-04 14:23:29 -08009050 ALOGV("Thread %p type %d exiting", this, mType);
9051 return false;
9052}
9053
9054// checkForNewParameter_l() must be called with ThreadBase::mLock held
9055bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9056 status_t& status)
9057{
9058 AudioParameter param = AudioParameter(keyValuePair);
9059 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009060 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009061 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009062 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009063 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009064 if (sendToHal) {
9065 status = mHalStream->setParameters(keyValuePair);
9066 } else {
9067 status = NO_ERROR;
9068 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009069
9070 return false;
9071}
9072
9073String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9074{
9075 Mutex::Autolock _l(mLock);
9076 String8 out_s8;
9077 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9078 return out_s8;
9079 }
9080 return String8();
9081}
9082
Eric Laurent09f1ed22019-04-24 17:45:17 -07009083void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9084 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009085 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9086
9087 desc->mIoHandle = mId;
9088
9089 switch (event) {
9090 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009091 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009092 case AUDIO_INPUT_CONFIG_CHANGED:
9093 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009094 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009095 case AUDIO_OUTPUT_CONFIG_CHANGED:
9096 desc->mPatch = mPatch;
9097 desc->mChannelMask = mChannelMask;
9098 desc->mSamplingRate = mSampleRate;
9099 desc->mFormat = mFormat;
9100 desc->mFrameCount = mFrameCount;
9101 desc->mFrameCountHAL = mFrameCount;
9102 desc->mLatency = 0;
9103 break;
9104
9105 case AUDIO_INPUT_CLOSED:
9106 case AUDIO_OUTPUT_CLOSED:
9107 default:
9108 break;
9109 }
9110 mAudioFlinger->ioConfigChanged(event, desc, pid);
9111}
9112
9113status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9114 audio_patch_handle_t *handle)
9115{
9116 status_t status = NO_ERROR;
9117
9118 // store new device and send to effects
9119 audio_devices_t type = AUDIO_DEVICE_NONE;
9120 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009121 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9122 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9123 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009124 if (isOutput()) {
9125 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009126 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9127 && !mAudioHwDev->supportsAudioPatches(),
9128 "Enumerated device type(%#x) must not be used "
9129 "as it does not support audio patches",
9130 patch->sinks[i].ext.device.type);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009131 type |= patch->sinks[i].ext.device.type;
jiabinc52b1ff2019-10-31 17:20:42 -07009132 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9133 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009134 }
9135 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009136 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009137 } else {
9138 type = patch->sources[0].ext.device.type;
9139 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009140 numDevices = mPatch.num_sources;
9141 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
9142 sourceDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009143 }
9144
9145 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009146 if (isOutput()) {
9147 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9148 } else {
9149 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9150 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009151 }
9152
jiabinc52b1ff2019-10-31 17:20:42 -07009153 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009154 // store new source and send to effects
9155 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9156 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9157 for (size_t i = 0; i < mEffectChains.size(); i++) {
9158 mEffectChains[i]->setAudioSource_l(mAudioSource);
9159 }
9160 }
9161 }
9162
9163 if (mAudioHwDev->supportsAudioPatches()) {
9164 status = mHalDevice->createAudioPatch(patch->num_sources,
9165 patch->sources,
9166 patch->num_sinks,
9167 patch->sinks,
9168 handle);
9169 } else {
9170 char *address;
9171 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9172 //FIXME: we only support address on first sink with HAL version < 3.0
9173 address = audio_device_address_to_parameter(
9174 patch->sinks[0].ext.device.type,
9175 patch->sinks[0].ext.device.address);
9176 } else {
9177 address = (char *)calloc(1, 1);
9178 }
9179 AudioParameter param = AudioParameter(String8(address));
9180 free(address);
9181 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9182 if (!isOutput()) {
9183 param.addInt(String8(AudioParameter::keyInputSource),
9184 (int)patch->sinks[0].ext.mix.usecase.source);
9185 }
9186 status = mHalStream->setParameters(param.toString());
9187 *handle = AUDIO_PATCH_HANDLE_NONE;
9188 }
9189
jiabinc52b1ff2019-10-31 17:20:42 -07009190 if (numDevices == 0 || mDeviceId != deviceId) {
9191 if (isOutput()) {
9192 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9193 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009194 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009195 } else {
9196 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9197 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9198 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009199 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009200 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009201 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009202 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009203 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009204 }
jiabinc52b1ff2019-10-31 17:20:42 -07009205 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009206 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009207 }
9208 return status;
9209}
9210
9211status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9212{
9213 status_t status = NO_ERROR;
9214
jiabinc52b1ff2019-10-31 17:20:42 -07009215 mPatch = audio_patch{};
9216 mOutDeviceTypeAddrs.clear();
9217 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009218
9219 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9220 supportsAudioPatches : false;
9221
9222 if (supportsAudioPatches) {
9223 status = mHalDevice->releaseAudioPatch(handle);
9224 } else {
9225 AudioParameter param;
9226 param.addInt(String8(AudioParameter::keyRouting), 0);
9227 status = mHalStream->setParameters(param.toString());
9228 }
9229 return status;
9230}
9231
Mikhail Naganovdc769682018-05-04 15:34:08 -07009232void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009233{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009234 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009235 if (isOutput()) {
9236 config->role = AUDIO_PORT_ROLE_SOURCE;
9237 config->ext.mix.hw_module = mAudioHwDev->handle();
9238 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9239 } else {
9240 config->role = AUDIO_PORT_ROLE_SINK;
9241 config->ext.mix.hw_module = mAudioHwDev->handle();
9242 config->ext.mix.usecase.source = mAudioSource;
9243 }
9244}
9245
9246status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9247{
9248 audio_session_t session = chain->sessionId();
9249
9250 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9251 // Attach all tracks with same session ID to this chain.
9252 // indicate all active tracks in the chain
9253 for (const sp<MmapTrack> &track : mActiveTracks) {
9254 if (session == track->sessionId()) {
9255 chain->incTrackCnt();
9256 chain->incActiveTrackCnt();
9257 }
9258 }
9259
9260 chain->setThread(this);
9261 chain->setInBuffer(nullptr);
9262 chain->setOutBuffer(nullptr);
9263 chain->syncHalEffectsState();
9264
9265 mEffectChains.add(chain);
9266 checkSuspendOnAddEffectChain_l(chain);
9267 return NO_ERROR;
9268}
9269
9270size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9271{
9272 audio_session_t session = chain->sessionId();
9273
9274 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9275
9276 for (size_t i = 0; i < mEffectChains.size(); i++) {
9277 if (chain == mEffectChains[i]) {
9278 mEffectChains.removeAt(i);
9279 // detach all active tracks from the chain
9280 // detach all tracks with same session ID from this chain
9281 for (const sp<MmapTrack> &track : mActiveTracks) {
9282 if (session == track->sessionId()) {
9283 chain->decActiveTrackCnt();
9284 chain->decTrackCnt();
9285 }
9286 }
9287 break;
9288 }
9289 }
9290 return mEffectChains.size();
9291}
9292
Eric Laurent6acd1d42017-01-04 14:23:29 -08009293void AudioFlinger::MmapThread::threadLoop_standby()
9294{
9295 mHalStream->standby();
9296}
9297
9298void AudioFlinger::MmapThread::threadLoop_exit()
9299{
Phil Burk7dce7282017-09-27 13:51:41 -07009300 // Do not call callback->onTearDown() because it is redundant for thread exit
9301 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009302}
9303
9304status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9305{
9306 return BAD_VALUE;
9307}
9308
9309bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9310{
9311 return false;
9312}
9313
9314status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9315 const effect_descriptor_t *desc, audio_session_t sessionId)
9316{
9317 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009318 if (audio_is_global_session(sessionId)) {
9319 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009320 desc->name, mThreadName);
9321 return BAD_VALUE;
9322 }
9323
9324 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9325 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9326 desc->name);
9327 return BAD_VALUE;
9328 }
9329 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009330 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9331 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009332 return BAD_VALUE;
9333 }
9334
9335 // Only allow effects without processing load or latency
9336 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9337 return BAD_VALUE;
9338 }
9339
9340 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009341}
9342
9343void AudioFlinger::MmapThread::checkInvalidTracks_l()
9344{
9345 for (const sp<MmapTrack> &track : mActiveTracks) {
9346 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009347 sp<MmapStreamCallback> callback = mCallback.promote();
9348 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009349 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009350 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009351 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009352 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9353 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9354 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009355 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009356 }
9357 }
9358}
9359
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009360void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009361{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009362 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9363 mAttr.content_type, mAttr.usage, mAttr.source);
9364 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009365 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009366 dprintf(fd, " No active clients\n");
9367 }
9368}
9369
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009370void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009371{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009372 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009373 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009374 dprintf(fd, " %zu Tracks\n", numtracks);
9375 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009376 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009377 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009378 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009379 for (size_t i = 0; i < numtracks ; ++i) {
9380 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009381 result.append(prefix);
9382 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009383 }
9384 } else {
9385 dprintf(fd, "\n");
9386 }
9387 write(fd, result.string(), result.size());
9388}
9389
9390AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9391 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009392 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
9393 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009394 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009395 mStreamVolume(1.0),
9396 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009397 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009398{
9399 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9400 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9401 mMasterVolume = audioFlinger->masterVolume_l();
9402 mMasterMute = audioFlinger->masterMute_l();
9403 if (mAudioHwDev) {
9404 if (mAudioHwDev->canSetMasterVolume()) {
9405 mMasterVolume = 1.0;
9406 }
9407
9408 if (mAudioHwDev->canSetMasterMute()) {
9409 mMasterMute = false;
9410 }
9411 }
9412}
9413
9414void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9415 audio_stream_type_t streamType,
9416 audio_session_t sessionId,
9417 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009418 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009419 audio_port_handle_t portId)
9420{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009421 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009422 mStreamType = streamType;
9423}
9424
9425AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9426{
9427 Mutex::Autolock _l(mLock);
9428 AudioStreamOut *output = mOutput;
9429 mOutput = NULL;
9430 return output;
9431}
9432
9433void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9434{
9435 Mutex::Autolock _l(mLock);
9436 // Don't apply master volume in SW if our HAL can do it for us.
9437 if (mAudioHwDev &&
9438 mAudioHwDev->canSetMasterVolume()) {
9439 mMasterVolume = 1.0;
9440 } else {
9441 mMasterVolume = value;
9442 }
9443}
9444
9445void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9446{
9447 Mutex::Autolock _l(mLock);
9448 // Don't apply master mute in SW if our HAL can do it for us.
9449 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9450 mMasterMute = false;
9451 } else {
9452 mMasterMute = muted;
9453 }
9454}
9455
9456void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9457{
9458 Mutex::Autolock _l(mLock);
9459 if (stream == mStreamType) {
9460 mStreamVolume = value;
9461 broadcast_l();
9462 }
9463}
9464
9465float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9466{
9467 Mutex::Autolock _l(mLock);
9468 if (stream == mStreamType) {
9469 return mStreamVolume;
9470 }
9471 return 0.0f;
9472}
9473
9474void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9475{
9476 Mutex::Autolock _l(mLock);
9477 if (stream == mStreamType) {
9478 mStreamMute= muted;
9479 broadcast_l();
9480 }
9481}
9482
9483void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9484{
9485 Mutex::Autolock _l(mLock);
9486 if (streamType == mStreamType) {
9487 for (const sp<MmapTrack> &track : mActiveTracks) {
9488 track->invalidate();
9489 }
9490 broadcast_l();
9491 }
9492}
9493
9494void AudioFlinger::MmapPlaybackThread::processVolume_l()
9495{
9496 float volume;
9497
9498 if (mMasterMute || mStreamMute) {
9499 volume = 0;
9500 } else {
9501 volume = mMasterVolume * mStreamVolume;
9502 }
9503
9504 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009505
9506 // Convert volumes from float to 8.24
9507 uint32_t vol = (uint32_t)(volume * (1 << 24));
9508
9509 // Delegate volume control to effect in track effect chain if needed
9510 // only one effect chain can be present on DirectOutputThread, so if
9511 // there is one, the track is connected to it
9512 if (!mEffectChains.isEmpty()) {
9513 mEffectChains[0]->setVolume_l(&vol, &vol);
9514 volume = (float)vol / (1 << 24);
9515 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009516 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009517 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9518 mHalVolFloat = volume; // HW volume control worked, so update value.
9519 mNoCallbackWarningCount = 0;
9520 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009521 sp<MmapStreamCallback> callback = mCallback.promote();
9522 if (callback != 0) {
9523 int channelCount;
9524 if (isOutput()) {
9525 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9526 } else {
9527 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9528 }
9529 Vector<float> values;
9530 for (int i = 0; i < channelCount; i++) {
9531 values.add(volume);
9532 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009533 mHalVolFloat = volume; // SW volume control worked, so update value.
9534 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009535 mLock.unlock();
9536 callback->onVolumeChanged(mChannelMask, values);
9537 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009538 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009539 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9540 ALOGW("Could not set MMAP stream volume: no volume callback!");
9541 mNoCallbackWarningCount++;
9542 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009543 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009544 }
9545 }
9546}
9547
Kevin Rocard069c2712018-03-29 19:09:14 -07009548void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9549{
9550 if (mOutput == nullptr || mOutput->stream == nullptr ||
9551 !mActiveTracks.readAndClearHasChanged()) {
9552 return;
9553 }
9554 StreamOutHalInterface::SourceMetadata metadata;
9555 for (const sp<MmapTrack> &track : mActiveTracks) {
9556 // No track is invalid as this is called after prepareTrack_l in the same critical section
9557 metadata.tracks.push_back({
9558 .usage = track->attributes().usage,
9559 .content_type = track->attributes().content_type,
9560 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9561 });
9562 }
9563 mOutput->stream->updateSourceMetadata(metadata);
9564}
9565
Eric Laurent6acd1d42017-01-04 14:23:29 -08009566void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9567{
9568 if (!mMasterMute) {
9569 char value[PROPERTY_VALUE_MAX];
9570 if (property_get("ro.audio.silent", value, "0") > 0) {
9571 char *endptr;
9572 unsigned long ul = strtoul(value, &endptr, 0);
9573 if (*endptr == '\0' && ul != 0) {
9574 ALOGD("Silence is golden");
9575 // The setprop command will not allow a property to be changed after
9576 // the first time it is set, so we don't have to worry about un-muting.
9577 setMasterMute_l(true);
9578 }
9579 }
9580 }
9581}
9582
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009583void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9584{
9585 MmapThread::toAudioPortConfig(config);
9586 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9587 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9588 config->flags.output = mOutput->flags;
9589 }
9590}
9591
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009592void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009593{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009594 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009595
Glenn Kastend3bb6452016-12-05 18:14:37 -08009596 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9597 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009598 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9599}
9600
9601AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9602 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009603 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
9604 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009605 mInput(input)
9606{
9607 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9608 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9609}
9610
Eric Laurent331679c2018-04-16 17:03:16 -07009611status_t AudioFlinger::MmapCaptureThread::exitStandby()
9612{
Phil Burkf054fc32018-12-06 09:45:59 -08009613 {
9614 // mInput might have been cleared by clearInput()
9615 Mutex::Autolock _l(mLock);
9616 if (mInput != nullptr && mInput->stream != nullptr) {
9617 mInput->stream->setGain(1.0f);
9618 }
9619 }
Eric Laurent331679c2018-04-16 17:03:16 -07009620 return MmapThread::exitStandby();
9621}
9622
Eric Laurent6acd1d42017-01-04 14:23:29 -08009623AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9624{
9625 Mutex::Autolock _l(mLock);
9626 AudioStreamIn *input = mInput;
9627 mInput = NULL;
9628 return input;
9629}
Kevin Rocard069c2712018-03-29 19:09:14 -07009630
Eric Laurent331679c2018-04-16 17:03:16 -07009631
9632void AudioFlinger::MmapCaptureThread::processVolume_l()
9633{
9634 bool changed = false;
9635 bool silenced = false;
9636
9637 sp<MmapStreamCallback> callback = mCallback.promote();
9638 if (callback == 0) {
9639 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9640 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9641 mNoCallbackWarningCount++;
9642 }
9643 }
9644
9645 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9646 // track is silenced and unmute otherwise
9647 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9648 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9649 changed = true;
9650 silenced = mActiveTracks[i]->isSilenced_l();
9651 }
9652 }
9653
9654 if (changed) {
9655 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9656 }
9657}
9658
Kevin Rocard069c2712018-03-29 19:09:14 -07009659void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9660{
9661 if (mInput == nullptr || mInput->stream == nullptr ||
9662 !mActiveTracks.readAndClearHasChanged()) {
9663 return;
9664 }
9665 StreamInHalInterface::SinkMetadata 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
9668 metadata.tracks.push_back({
9669 .source = track->attributes().source,
9670 .gain = 1, // capture tracks do not have volumes
9671 });
9672 }
9673 mInput->stream->updateSinkMetadata(metadata);
9674}
9675
Eric Laurent5ada82e2019-08-29 17:53:54 -07009676void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -07009677{
9678 Mutex::Autolock _l(mLock);
9679 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07009680 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -07009681 mActiveTracks[i]->setSilenced_l(silenced);
9682 broadcast_l();
9683 }
9684 }
9685}
9686
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009687void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9688{
9689 MmapThread::toAudioPortConfig(config);
9690 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9691 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9692 config->flags.input = mInput->flags;
9693 }
9694}
9695
Glenn Kasten63238ef2015-03-02 15:50:29 -08009696} // namespace android