blob: 92f18c1b63772c6636b92dde2dc63d657c816d75 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
jiabinc52b1ff2019-10-31 17:20:42 -070034#include <media/AudioContainers.h>
35#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070036#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070037#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080038#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080041#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070044#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010045#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080046#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080047#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080048#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080050#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070051#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070052#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_ns.h>
54#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070055#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070058#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080059#include <media/nbaio/AudioStreamOutSink.h>
60#include <media/nbaio/MonoPipe.h>
61#include <media/nbaio/MonoPipeReader.h>
62#include <media/nbaio/Pipe.h>
63#include <media/nbaio/PipeReader.h>
64#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080065#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080066
Mikhail Naganov2996f672019-04-18 12:29:59 -070067#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080068#include <powermanager/PowerManager.h>
69
Kevin Rocard7588ff42018-01-08 11:11:30 -080070#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070071#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080072
Eric Laurent81784c32012-11-19 14:55:58 -080073#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080074#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070075#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070076#include <mediautils/SchedulingPolicyService.h>
77#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080078
Eric Laurent81784c32012-11-19 14:55:58 -080079#ifdef ADD_BATTERY_DATA
80#include <media/IMediaPlayerService.h>
81#include <media/IMediaDeathNotifier.h>
82#endif
83
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070085#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080086#include <cpustats/ThreadCpuUsage.h>
87#endif
88
Glenn Kastenc05b8d72016-03-24 09:48:17 -070089#include "AutoPark.h"
90
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080091#include <pthread.h>
92#include "TypedLogger.h"
93
Eric Laurent81784c32012-11-19 14:55:58 -080094// ----------------------------------------------------------------------------
95
96// Note: the following macro is used for extremely verbose logging message. In
97// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
98// 0; but one side effect of this is to turn all LOGV's as well. Some messages
99// are so verbose that we want to suppress them even when we have ALOG_ASSERT
100// turned on. Do not uncomment the #def below unless you really know what you
101// are doing and want to see all of the extremely verbose messages.
102//#define VERY_VERY_VERBOSE_LOGGING
103#ifdef VERY_VERY_VERBOSE_LOGGING
104#define ALOGVV ALOGV
105#else
106#define ALOGVV(a...) do { } while(0)
107#endif
108
Andy Hung6770c6f2015-04-07 13:43:36 -0700109// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700110#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700111template <typename T>
112static inline T min(const T& a, const T& b)
113{
114 return a < b ? a : b;
115}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700116
Eric Laurent81784c32012-11-19 14:55:58 -0800117namespace android {
118
119// retry counts for buffer fill timeout
120// 50 * ~20msecs = 1 second
121static const int8_t kMaxTrackRetries = 50;
122static const int8_t kMaxTrackStartupRetries = 50;
123// allow less retry attempts on direct output thread.
124// direct outputs can be a scarce resource in audio hardware and should
125// be released as quickly as possible.
126static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700127
Eric Laurent51716182016-02-29 18:00:56 -0800128
Eric Laurent81784c32012-11-19 14:55:58 -0800129
130// don't warn about blocked writes or record buffer overflows more often than this
131static const nsecs_t kWarningThrottleNs = seconds(5);
132
133// RecordThread loop sleep time upon application overrun or audio HAL read error
134static const int kRecordThreadSleepUs = 5000;
135
Eric Laurent10351942014-05-08 18:49:52 -0700136// maximum time to wait in sendConfigEvent_l() for a status to be received
137static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800138
139// minimum sleep time for the mixer thread loop when tracks are active but in underrun
140static const uint32_t kMinThreadSleepTimeUs = 5000;
141// maximum divider applied to the active sleep time in the mixer thread loop
142static const uint32_t kMaxThreadSleepTimeShift = 2;
143
Andy Hung09a50072014-02-27 14:30:47 -0800144// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700145// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800146static const uint32_t kMinNormalSinkBufferSizeMs = 20;
147// maximum normal sink buffer size
148static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800149
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700150// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
151// FIXME This should be based on experimentally observed scheduling jitter
152static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
153
Eric Laurent972a1732013-09-04 09:42:59 -0700154// Offloaded output thread standby delay: allows track transition without going to standby
155static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
156
Eric Laurent51716182016-02-29 18:00:56 -0800157// Direct output thread minimum sleep time in idle or active(underrun) state
158static const nsecs_t kDirectMinSleepTimeUs = 10000;
159
Glenn Kasten1b291842016-07-18 14:55:21 -0700160// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
161// balance between power consumption and latency, and allows threads to be scheduled reliably
162// by the CFS scheduler.
163// FIXME Express other hardcoded references to 20ms with references to this constant and move
164// it appropriately.
165#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800166
Eric Laurent81784c32012-11-19 14:55:58 -0800167// Whether to use fast mixer
168static const enum {
169 FastMixer_Never, // never initialize or use: for debugging only
170 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
171 // normal mixer multiplier is 1
172 FastMixer_Static, // initialize if needed, then use all the time if initialized,
173 // multiplier is calculated based on min & max normal mixer buffer size
174 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
175 // multiplier is calculated based on min & max normal mixer buffer size
176 // FIXME for FastMixer_Dynamic:
177 // Supporting this option will require fixing HALs that can't handle large writes.
178 // For example, one HAL implementation returns an error from a large write,
179 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
180 // We could either fix the HAL implementations, or provide a wrapper that breaks
181 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
182} kUseFastMixer = FastMixer_Static;
183
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700184// Whether to use fast capture
185static const enum {
186 FastCapture_Never, // never initialize or use: for debugging only
187 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
188 FastCapture_Static, // initialize if needed, then use all the time if initialized
189} kUseFastCapture = FastCapture_Static;
190
Eric Laurent81784c32012-11-19 14:55:58 -0800191// Priorities for requestPriority
192static const int kPriorityAudioApp = 2;
193static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700194static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800195
Glenn Kastenea38ee72016-04-18 11:08:01 -0700196// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
197// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
198// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700199
200// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800201static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800202
Glenn Kasten03490092014-05-27 12:30:54 -0700203// The minimum and maximum allowed values
204static const int kFastTrackMultiplierMin = 1;
205static const int kFastTrackMultiplierMax = 2;
206
207// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
208static int sFastTrackMultiplier = kFastTrackMultiplier;
209
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700210// See Thread::readOnlyHeap().
211// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
212// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
213// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700214static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700215
Eric Laurent81784c32012-11-19 14:55:58 -0800216// ----------------------------------------------------------------------------
217
Andy Hungb68f5eb2019-12-03 16:49:17 -0800218// TODO: move all toString helpers to audio.h
219// under #ifdef __cplusplus #endif
220static std::string patchSinksToString(const struct audio_patch *patch)
221{
222 std::stringstream ss;
223 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700224 if (i > 0) {
225 ss << "|";
226 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800227 ss << "(" << toString(patch->sinks[i].ext.device.type)
228 << ", " << patch->sinks[i].ext.device.address << ")";
229 }
230 return ss.str();
231}
232
233static std::string patchSourcesToString(const struct audio_patch *patch)
234{
235 std::stringstream ss;
236 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700237 if (i > 0) {
238 ss << "|";
239 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800240 ss << "(" << toString(patch->sources[i].ext.device.type)
241 << ", " << patch->sources[i].ext.device.address << ")";
242 }
243 return ss.str();
244}
245
Glenn Kasten03490092014-05-27 12:30:54 -0700246static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
247
248static void sFastTrackMultiplierInit()
249{
250 char value[PROPERTY_VALUE_MAX];
251 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
252 char *endptr;
253 unsigned long ul = strtoul(value, &endptr, 0);
254 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
255 sFastTrackMultiplier = (int) ul;
256 }
257 }
258}
259
260// ----------------------------------------------------------------------------
261
Eric Laurent81784c32012-11-19 14:55:58 -0800262#ifdef ADD_BATTERY_DATA
263// To collect the amplifier usage
264static void addBatteryData(uint32_t params) {
265 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
266 if (service == NULL) {
267 // it already logged
268 return;
269 }
270
271 service->addBatteryData(params);
272}
273#endif
274
Andy Hung3f0c9022016-01-15 17:49:46 -0800275// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
276struct {
277 // call when you acquire a partial wakelock
278 void acquire(const sp<IBinder> &wakeLockToken) {
279 pthread_mutex_lock(&mLock);
280 if (wakeLockToken.get() == nullptr) {
281 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
282 } else {
283 if (mCount == 0) {
284 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
285 }
286 ++mCount;
287 }
288 pthread_mutex_unlock(&mLock);
289 }
290
291 // call when you release a partial wakelock.
292 void release(const sp<IBinder> &wakeLockToken) {
293 if (wakeLockToken.get() == nullptr) {
294 return;
295 }
296 pthread_mutex_lock(&mLock);
297 if (--mCount < 0) {
298 ALOGE("negative wakelock count");
299 mCount = 0;
300 }
301 pthread_mutex_unlock(&mLock);
302 }
303
304 // retrieves the boottime timebase offset from monotonic.
305 int64_t getBoottimeOffset() {
306 pthread_mutex_lock(&mLock);
307 int64_t boottimeOffset = mBoottimeOffset;
308 pthread_mutex_unlock(&mLock);
309 return boottimeOffset;
310 }
311
312 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
313 // and the selected timebase.
314 // Currently only TIMEBASE_BOOTTIME is allowed.
315 //
316 // This only needs to be called upon acquiring the first partial wakelock
317 // after all other partial wakelocks are released.
318 //
319 // We do an empirical measurement of the offset rather than parsing
320 // /proc/timer_list since the latter is not a formal kernel ABI.
321 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
322 int clockbase;
323 switch (timebase) {
324 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
325 clockbase = SYSTEM_TIME_BOOTTIME;
326 break;
327 default:
328 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
329 break;
330 }
331 // try three times to get the clock offset, choose the one
332 // with the minimum gap in measurements.
333 const int tries = 3;
334 nsecs_t bestGap, measured;
335 for (int i = 0; i < tries; ++i) {
336 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
337 const nsecs_t tbase = systemTime(clockbase);
338 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
339 const nsecs_t gap = tmono2 - tmono;
340 if (i == 0 || gap < bestGap) {
341 bestGap = gap;
342 measured = tbase - ((tmono + tmono2) >> 1);
343 }
344 }
345
346 // to avoid micro-adjusting, we don't change the timebase
347 // unless it is significantly different.
348 //
349 // Assumption: It probably takes more than toleranceNs to
350 // suspend and resume the device.
351 static int64_t toleranceNs = 10000; // 10 us
352 if (llabs(*offset - measured) > toleranceNs) {
353 ALOGV("Adjusting timebase offset old: %lld new: %lld",
354 (long long)*offset, (long long)measured);
355 *offset = measured;
356 }
357 }
358
359 pthread_mutex_t mLock;
360 int32_t mCount;
361 int64_t mBoottimeOffset;
362} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800363
364// ----------------------------------------------------------------------------
365// CPU Stats
366// ----------------------------------------------------------------------------
367
368class CpuStats {
369public:
370 CpuStats();
371 void sample(const String8 &title);
372#ifdef DEBUG_CPU_USAGE
373private:
374 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700375 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800376
Andy Hung16698b82018-08-01 10:48:38 -0700377 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800378
379 int mCpuNum; // thread's current CPU number
380 int mCpukHz; // frequency of thread's current CPU in kHz
381#endif
382};
383
384CpuStats::CpuStats()
385#ifdef DEBUG_CPU_USAGE
386 : mCpuNum(-1), mCpukHz(-1)
387#endif
388{
389}
390
Glenn Kasten0f11b512014-01-31 16:18:54 -0800391void CpuStats::sample(const String8 &title
392#ifndef DEBUG_CPU_USAGE
393 __unused
394#endif
395 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800396#ifdef DEBUG_CPU_USAGE
397 // get current thread's delta CPU time in wall clock ns
398 double wcNs;
399 bool valid = mCpuUsage.sampleAndEnable(wcNs);
400
401 // record sample for wall clock statistics
402 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700403 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800404 }
405
406 // get the current CPU number
407 int cpuNum = sched_getcpu();
408
409 // get the current CPU frequency in kHz
410 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
411
412 // check if either CPU number or frequency changed
413 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
414 mCpuNum = cpuNum;
415 mCpukHz = cpukHz;
416 // ignore sample for purposes of cycles
417 valid = false;
418 }
419
420 // if no change in CPU number or frequency, then record sample for cycle statistics
421 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700422 const double cycles = wcNs * cpukHz * 0.000001;
423 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800424 }
425
Eric Tan5b13ff82018-07-27 11:20:17 -0700426 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800427 // mCpuUsage.elapsed() is expensive, so don't call it every loop
428 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700429 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800430 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700431 const double perLoop = elapsed / (double) n;
432 const double perLoop100 = perLoop * 0.01;
433 const double perLoop1k = perLoop * 0.001;
434 const double mean = mWcStats.getMean();
435 const double stddev = mWcStats.getStdDev();
436 const double minimum = mWcStats.getMin();
437 const double maximum = mWcStats.getMax();
438 const double meanCycles = mHzStats.getMean();
439 const double stddevCycles = mHzStats.getStdDev();
440 const double minCycles = mHzStats.getMin();
441 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800442 mCpuUsage.resetElapsed();
443 mWcStats.reset();
444 mHzStats.reset();
445 ALOGD("CPU usage for %s over past %.1f secs\n"
446 " (%u mixer loops at %.1f mean ms per loop):\n"
447 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
448 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
449 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
450 title.string(),
451 elapsed * .000000001, n, perLoop * .000001,
452 mean * .001,
453 stddev * .001,
454 minimum * .001,
455 maximum * .001,
456 mean / perLoop100,
457 stddev / perLoop100,
458 minimum / perLoop100,
459 maximum / perLoop100,
460 meanCycles / perLoop1k,
461 stddevCycles / perLoop1k,
462 minCycles / perLoop1k,
463 maxCycles / perLoop1k);
464
465 }
466 }
467#endif
468};
469
470// ----------------------------------------------------------------------------
471// ThreadBase
472// ----------------------------------------------------------------------------
473
Glenn Kasten97b7b752014-09-28 13:04:24 -0700474// static
475const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
476{
477 switch (type) {
478 case MIXER:
479 return "MIXER";
480 case DIRECT:
481 return "DIRECT";
482 case DUPLICATING:
483 return "DUPLICATING";
484 case RECORD:
485 return "RECORD";
486 case OFFLOAD:
487 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700488 case MMAP_PLAYBACK:
489 return "MMAP_PLAYBACK";
490 case MMAP_CAPTURE:
491 return "MMAP_CAPTURE";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700492 default:
493 return "unknown";
494 }
495}
496
Eric Laurent81784c32012-11-19 14:55:58 -0800497AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700498 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800499 : Thread(false /*canCallJava*/),
500 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700501 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700502 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
503 isOut),
504 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700505 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800506 // are set by PlaybackThread::readOutputParameters_l() or
507 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700508 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700509 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700510 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800511 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700512 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800513 mSystemReady(systemReady),
514 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800515{
Andy Hungcf10d742020-04-28 15:38:24 -0700516 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700517 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800518}
519
520AudioFlinger::ThreadBase::~ThreadBase()
521{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700522 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700523 mConfigEvents.clear();
524
Eric Laurent81784c32012-11-19 14:55:58 -0800525 // do not lock the mutex in destructor
526 releaseWakeLock_l();
527 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800528 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800529 binder->unlinkToDeath(mDeathRecipient);
530 }
Andy Hungd0979812019-02-21 15:51:44 -0800531
532 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800533}
534
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700535status_t AudioFlinger::ThreadBase::readyToRun()
536{
537 status_t status = initCheck();
538 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800539 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700540 } else {
541 ALOGE("No working audio driver found.");
542 }
543 return status;
544}
545
Eric Laurent81784c32012-11-19 14:55:58 -0800546void AudioFlinger::ThreadBase::exit()
547{
548 ALOGV("ThreadBase::exit");
549 // do any cleanup required for exit to succeed
550 preExit();
551 {
552 // This lock prevents the following race in thread (uniprocessor for illustration):
553 // if (!exitPending()) {
554 // // context switch from here to exit()
555 // // exit() calls requestExit(), what exitPending() observes
556 // // exit() calls signal(), which is dropped since no waiters
557 // // context switch back from exit() to here
558 // mWaitWorkCV.wait(...);
559 // // now thread is hung
560 // }
561 AutoMutex lock(mLock);
562 requestExit();
563 mWaitWorkCV.broadcast();
564 }
565 // When Thread::requestExitAndWait is made virtual and this method is renamed to
566 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
567 requestExitAndWait();
568}
569
570status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
571{
Eric Laurent81784c32012-11-19 14:55:58 -0800572 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
573 Mutex::Autolock _l(mLock);
574
Eric Laurent10351942014-05-08 18:49:52 -0700575 return sendSetParameterConfigEvent_l(keyValuePairs);
576}
577
578// sendConfigEvent_l() must be called with ThreadBase::mLock held
579// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
580status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
581{
582 status_t status = NO_ERROR;
583
Eric Laurent72e3f392015-05-20 14:43:50 -0700584 if (event->mRequiresSystemReady && !mSystemReady) {
585 event->mWaitStatus = false;
586 mPendingConfigEvents.add(event);
587 return status;
588 }
Eric Laurent10351942014-05-08 18:49:52 -0700589 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700590 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800591 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700592 mLock.unlock();
593 {
594 Mutex::Autolock _l(event->mLock);
595 while (event->mWaitStatus) {
596 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
597 event->mStatus = TIMED_OUT;
598 event->mWaitStatus = false;
599 }
600 }
601 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800602 }
Eric Laurent10351942014-05-08 18:49:52 -0700603 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800604 return status;
605}
606
Eric Laurent09f1ed22019-04-24 17:45:17 -0700607void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
608 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800609{
610 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700611 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800612}
613
614// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700615void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
616 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800617{
Andy Hungd0979812019-02-21 15:51:44 -0800618 // The audio statistics history is exponentially weighted to forget events
619 // about five or more seconds in the past. In order to have
620 // crisper statistics for mediametrics, we reset the statistics on
621 // an IoConfigEvent, to reflect different properties for a new device.
622 mIoJitterMs.reset();
623 mLatencyMs.reset();
624 mProcessTimeMs.reset();
625 mTimestampVerifier.discontinuity();
626
Eric Laurent09f1ed22019-04-24 17:45:17 -0700627 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700628 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800629}
630
Mikhail Naganov83f04272017-02-07 10:45:09 -0800631void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700632{
633 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800634 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700635}
636
Eric Laurent81784c32012-11-19 14:55:58 -0800637// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800638void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
639 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800640{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800641 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700642 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800643}
644
Eric Laurent10351942014-05-08 18:49:52 -0700645// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
646status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800647{
Andy Hung2ddee192015-12-18 17:34:44 -0800648 sp<ConfigEvent> configEvent;
649 AudioParameter param(keyValuePair);
650 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700651 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800652 setMasterMono_l(value != 0);
653 if (param.size() == 1) {
654 return NO_ERROR; // should be a solo parameter - we don't pass down
655 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700656 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800657 configEvent = new SetParameterConfigEvent(param.toString());
658 } else {
659 configEvent = new SetParameterConfigEvent(keyValuePair);
660 }
Eric Laurent10351942014-05-08 18:49:52 -0700661 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700662}
663
Eric Laurent1c333e22014-05-20 10:48:17 -0700664status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
665 const struct audio_patch *patch,
666 audio_patch_handle_t *handle)
667{
668 Mutex::Autolock _l(mLock);
669 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
670 status_t status = sendConfigEvent_l(configEvent);
671 if (status == NO_ERROR) {
672 CreateAudioPatchConfigEventData *data =
673 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
674 *handle = data->mHandle;
675 }
676 return status;
677}
678
679status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
680 const audio_patch_handle_t handle)
681{
682 Mutex::Autolock _l(mLock);
683 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
684 return sendConfigEvent_l(configEvent);
685}
686
jiabinc52b1ff2019-10-31 17:20:42 -0700687status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
688 const DeviceDescriptorBaseVector& outDevices)
689{
690 if (type() != RECORD) {
691 // The update out device operation is only for record thread.
692 return INVALID_OPERATION;
693 }
694 Mutex::Autolock _l(mLock);
695 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
696 return sendConfigEvent_l(configEvent);
697}
698
Eric Laurent1c333e22014-05-20 10:48:17 -0700699
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700700// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700701void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700702{
Eric Laurent10351942014-05-08 18:49:52 -0700703 bool configChanged = false;
704
Eric Laurent81784c32012-11-19 14:55:58 -0800705 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700706 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700707 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800708 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700709 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700710 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700711 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
712 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800713 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700714 true /*asynchronous*/);
715 if (err != 0) {
716 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700717 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700718 }
719 } break;
720 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700721 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700722 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700723 } break;
724 case CFG_EVENT_SET_PARAMETER: {
725 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
726 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
727 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700728 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
729 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700730 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700731 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700732 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700733 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700734 CreateAudioPatchConfigEventData *data =
735 (CreateAudioPatchConfigEventData *)event->mData.get();
736 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700737 const DeviceTypeSet newDevices = getDeviceTypes();
738 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
739 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
740 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700741 } break;
742 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700743 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700744 ReleaseAudioPatchConfigEventData *data =
745 (ReleaseAudioPatchConfigEventData *)event->mData.get();
746 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700747 const DeviceTypeSet newDevices = getDeviceTypes();
748 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
749 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
750 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
751 } break;
752 case CFG_EVENT_UPDATE_OUT_DEVICE: {
753 UpdateOutDevicesConfigEventData *data =
754 (UpdateOutDevicesConfigEventData *)event->mData.get();
755 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700756 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700757 default:
Eric Laurent10351942014-05-08 18:49:52 -0700758 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700759 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800760 }
Eric Laurent10351942014-05-08 18:49:52 -0700761 {
762 Mutex::Autolock _l(event->mLock);
763 if (event->mWaitStatus) {
764 event->mWaitStatus = false;
765 event->mCond.signal();
766 }
767 }
768 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
769 }
770
771 if (configChanged) {
772 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800773 }
Eric Laurent81784c32012-11-19 14:55:58 -0800774}
775
Marco Nelissenb2208842014-02-07 14:00:50 -0800776String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
777 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700778 const audio_channel_representation_t representation =
779 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700780
781 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800782 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700783 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
784 if (output) {
785 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
786 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
787 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
788 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
789 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
790 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
791 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
792 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
793 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
794 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
795 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
796 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
797 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
798 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
799 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
800 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
801 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
802 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700803 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
804 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800805 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
806 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700807 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
808 } else {
809 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
810 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
811 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
812 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
813 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
814 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
815 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
816 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
817 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
818 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
819 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
820 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700821 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
822 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
823 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
824 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
825 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
826 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700827 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
828 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
829 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
830 }
831 const int len = s.length();
832 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700833 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700834 s.unlockBuffer(len - 2); // remove trailing ", "
835 }
836 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700838 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
839 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
840 return s;
841 default:
842 s.appendFormat("unknown mask, representation:%d bits:%#x",
843 representation, audio_channel_mask_get_bits(mask));
844 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800845 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800846}
847
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700848void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800849{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800850 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
851 this, mThreadName, getTid(), type(), threadTypeToString(type()));
852
Eric Laurent81784c32012-11-19 14:55:58 -0800853 bool locked = AudioFlinger::dumpTryLock(mLock);
854 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800855 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800856 }
857
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700858 dumpBase_l(fd, args);
859 dumpInternals_l(fd, args);
860 dumpTracks_l(fd, args);
861 dumpEffectChains_l(fd, args);
862
863 if (locked) {
864 mLock.unlock();
865 }
866
867 dprintf(fd, " Local log:\n");
868 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
869}
870
871void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
872{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700873 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700874 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700875 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700876 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700877 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700878 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700879 dprintf(fd, " Channel count: %u\n", mChannelCount);
880 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800881 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700882 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700883 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700884 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800885 size_t numConfig = mConfigEvents.size();
886 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700887 const size_t SIZE = 256;
888 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800889 for (size_t i = 0; i < numConfig; i++) {
890 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700891 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800892 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700893 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800894 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700895 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800896 }
Andy Hung293558a2017-03-21 12:19:20 -0700897 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700898 dprintf(fd, " Output devices: %s (%s)\n",
899 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
900 dprintf(fd, " Input device: %#x (%s)\n",
901 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800902 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800903
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700904 // Dump timestamp statistics for the Thread types that support it.
905 if (mType == RECORD
906 || mType == MIXER
907 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700908 || mType == DIRECT
909 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700910 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700911 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700912 }
913
Andy Hung446f4df2019-02-21 12:26:41 -0800914 if (mLastIoBeginNs > 0) { // MMAP may not set this
915 dprintf(fd, " Last %s occurred (msecs): %lld\n",
916 isOutput() ? "write" : "read",
917 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
918 }
919
920 if (mProcessTimeMs.getN() > 0) {
921 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
922 }
923
924 if (mIoJitterMs.getN() > 0) {
925 dprintf(fd, " Hal %s jitter ms stats: %s\n",
926 isOutput() ? "write" : "read",
927 mIoJitterMs.toString().c_str());
928 }
929
Andy Hunge6c37112019-02-26 17:38:10 -0800930 if (mLatencyMs.getN() > 0) {
931 dprintf(fd, " Threadloop %s latency stats: %s\n",
932 isOutput() ? "write" : "read",
933 mLatencyMs.toString().c_str());
934 }
Eric Laurent81784c32012-11-19 14:55:58 -0800935}
936
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700937void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800938{
939 const size_t SIZE = 256;
940 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800941
Marco Nelissenb2208842014-02-07 14:00:50 -0800942 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000943 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800944 write(fd, buffer, strlen(buffer));
945
Marco Nelissenb2208842014-02-07 14:00:50 -0800946 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800947 sp<EffectChain> chain = mEffectChains[i];
948 if (chain != 0) {
949 chain->dump(fd, args);
950 }
951 }
952}
953
Andy Hungdae27702016-10-31 14:01:16 -0700954void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800955{
956 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700957 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800958}
959
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100960String16 AudioFlinger::ThreadBase::getWakeLockTag()
961{
962 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800963 case MIXER:
964 return String16("AudioMix");
965 case DIRECT:
966 return String16("AudioDirectOut");
967 case DUPLICATING:
968 return String16("AudioDup");
969 case RECORD:
970 return String16("AudioIn");
971 case OFFLOAD:
972 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -0700973 case MMAP_PLAYBACK:
974 return String16("MmapPlayback");
975 case MMAP_CAPTURE:
976 return String16("MmapCapture");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800977 default:
978 ALOG_ASSERT(false);
979 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100980 }
981}
982
Andy Hungdae27702016-10-31 14:01:16 -0700983void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800984{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800985 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800986 if (mPowerManager != 0) {
987 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700988 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -0800989 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
990 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100991 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700992 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -0800993 {} /* workSource */,
994 {} /* historyTag */);
995 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800996 mWakeLockToken = binder;
997 }
Chris Ye6597d732020-02-28 22:38:25 -0800998 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -0800999 }
Wei Jia3f273d12015-11-24 09:06:49 -08001000
Andy Hung3f0c9022016-01-15 17:49:46 -08001001 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001002 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1003 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001004}
1005
1006void AudioFlinger::ThreadBase::releaseWakeLock()
1007{
1008 Mutex::Autolock _l(mLock);
1009 releaseWakeLock_l();
1010}
1011
1012void AudioFlinger::ThreadBase::releaseWakeLock_l()
1013{
Andy Hung3f0c9022016-01-15 17:49:46 -08001014 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001015 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001016 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001017 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001018 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001019 }
1020 mWakeLockToken.clear();
1021 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001022}
1023
1024void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001025 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001026 // use checkService() to avoid blocking if power service is not up yet
1027 sp<IBinder> binder =
1028 defaultServiceManager()->checkService(String16("power"));
1029 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001030 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001031 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001032 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001033 binder->linkToDeath(mDeathRecipient);
1034 }
1035 }
1036}
1037
Andy Hungd01b0f12016-11-07 16:10:30 -08001038void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001039 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001040
1041#if !LOG_NDEBUG
1042 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001043 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001044 s << uid << " ";
1045 }
1046 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1047#endif
1048
Andy Hung438e7572015-12-14 15:51:17 -08001049 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1050 if (mSystemReady) {
1051 ALOGE("no wake lock to update, but system ready!");
1052 } else {
1053 ALOGW("no wake lock to update, system not ready yet");
1054 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001055 return;
1056 }
1057 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001058 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001059 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1060 mWakeLockToken, uidsAsInt);
1061 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001062 }
1063}
1064
Eric Laurent81784c32012-11-19 14:55:58 -08001065void AudioFlinger::ThreadBase::clearPowerManager()
1066{
1067 Mutex::Autolock _l(mLock);
1068 releaseWakeLock_l();
1069 mPowerManager.clear();
1070}
1071
jiabinc52b1ff2019-10-31 17:20:42 -07001072void AudioFlinger::ThreadBase::updateOutDevices(
1073 const DeviceDescriptorBaseVector& outDevices __unused)
1074{
1075 ALOGE("%s should only be called in RecordThread", __func__);
1076}
1077
Glenn Kasten0f11b512014-01-31 16:18:54 -08001078void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001079{
1080 sp<ThreadBase> thread = mThread.promote();
1081 if (thread != 0) {
1082 thread->clearPowerManager();
1083 }
1084 ALOGW("power manager service died !!!");
1085}
1086
Eric Laurent81784c32012-11-19 14:55:58 -08001087void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001088 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001089{
1090 sp<EffectChain> chain = getEffectChain_l(sessionId);
1091 if (chain != 0) {
1092 if (type != NULL) {
1093 chain->setEffectSuspended_l(type, suspend);
1094 } else {
1095 chain->setEffectSuspendedAll_l(suspend);
1096 }
1097 }
1098
1099 updateSuspendedSessions_l(type, suspend, sessionId);
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1103{
1104 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1105 if (index < 0) {
1106 return;
1107 }
1108
1109 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1110 mSuspendedSessions.valueAt(index);
1111
1112 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001113 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001114 for (int j = 0; j < desc->mRefCount; j++) {
1115 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1116 chain->setEffectSuspendedAll_l(true);
1117 } else {
1118 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1119 desc->mType.timeLow);
1120 chain->setEffectSuspended_l(&desc->mType, true);
1121 }
1122 }
1123 }
1124}
1125
1126void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1127 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001128 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001129{
1130 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1131
1132 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1133
1134 if (suspend) {
1135 if (index >= 0) {
1136 sessionEffects = mSuspendedSessions.valueAt(index);
1137 } else {
1138 mSuspendedSessions.add(sessionId, sessionEffects);
1139 }
1140 } else {
1141 if (index < 0) {
1142 return;
1143 }
1144 sessionEffects = mSuspendedSessions.valueAt(index);
1145 }
1146
1147
1148 int key = EffectChain::kKeyForSuspendAll;
1149 if (type != NULL) {
1150 key = type->timeLow;
1151 }
1152 index = sessionEffects.indexOfKey(key);
1153
1154 sp<SuspendedSessionDesc> desc;
1155 if (suspend) {
1156 if (index >= 0) {
1157 desc = sessionEffects.valueAt(index);
1158 } else {
1159 desc = new SuspendedSessionDesc();
1160 if (type != NULL) {
1161 desc->mType = *type;
1162 }
1163 sessionEffects.add(key, desc);
1164 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1165 }
1166 desc->mRefCount++;
1167 } else {
1168 if (index < 0) {
1169 return;
1170 }
1171 desc = sessionEffects.valueAt(index);
1172 if (--desc->mRefCount == 0) {
1173 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1174 sessionEffects.removeItemsAt(index);
1175 if (sessionEffects.isEmpty()) {
1176 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1177 sessionId);
1178 mSuspendedSessions.removeItem(sessionId);
1179 }
1180 }
1181 }
1182 if (!sessionEffects.isEmpty()) {
1183 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1184 }
1185}
1186
Eric Laurent6b446ce2019-12-13 10:56:31 -08001187void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1188 audio_session_t sessionId,
1189 bool threadLocked) {
1190 if (!threadLocked) {
1191 mLock.lock();
1192 }
Eric Laurent81784c32012-11-19 14:55:58 -08001193
Eric Laurent81784c32012-11-19 14:55:58 -08001194 if (mType != RECORD) {
1195 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1196 // another session. This gives the priority to well behaved effect control panels
1197 // and applications not using global effects.
1198 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1199 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001200 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001201 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1202 }
1203 }
1204
Eric Laurent6b446ce2019-12-13 10:56:31 -08001205 if (!threadLocked) {
1206 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001207 }
1208}
1209
Eric Laurent4c415062016-06-17 16:14:16 -07001210// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1211status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1212 const effect_descriptor_t *desc, audio_session_t sessionId)
1213{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001214 // No global output effect sessions on record threads
1215 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1216 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001217 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1218 desc->name, mThreadName);
1219 return BAD_VALUE;
1220 }
1221 // only pre processing effects on record thread
1222 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1223 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1224 desc->name, mThreadName);
1225 return BAD_VALUE;
1226 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001227
1228 // always allow effects without processing load or latency
1229 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1230 return NO_ERROR;
1231 }
1232
Eric Laurent4c415062016-06-17 16:14:16 -07001233 audio_input_flags_t flags = mInput->flags;
1234 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1235 if (flags & AUDIO_INPUT_FLAG_RAW) {
1236 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1237 desc->name, mThreadName);
1238 return BAD_VALUE;
1239 }
1240 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1241 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1242 desc->name, mThreadName);
1243 return BAD_VALUE;
1244 }
1245 }
jiabineb3bda02020-06-30 14:07:03 -07001246
1247 if (EffectModule::isHapticGenerator(&desc->type)) {
1248 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1249 return BAD_VALUE;
1250 }
Eric Laurent4c415062016-06-17 16:14:16 -07001251 return NO_ERROR;
1252}
1253
1254// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1255status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1256 const effect_descriptor_t *desc, audio_session_t sessionId)
1257{
1258 // no preprocessing on playback threads
1259 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1260 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1261 " thread %s", desc->name, mThreadName);
1262 return BAD_VALUE;
1263 }
1264
Eric Laurent3e4de772017-07-16 16:55:08 -07001265 // always allow effects without processing load or latency
1266 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1267 return NO_ERROR;
1268 }
1269
jiabineb3bda02020-06-30 14:07:03 -07001270 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1271 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1272 __func__);
1273 return BAD_VALUE;
1274 }
1275
Eric Laurent4c415062016-06-17 16:14:16 -07001276 switch (mType) {
1277 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001278#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001279 // Reject any effect on mixer multichannel sinks.
1280 // TODO: fix both format and multichannel issues with effects.
1281 if (mChannelCount != FCC_2) {
1282 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1283 " thread %s", desc->name, mChannelCount, mThreadName);
1284 return BAD_VALUE;
1285 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001286#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001287 audio_output_flags_t flags = mOutput->flags;
1288 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1289 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1290 // global effects are applied only to non fast tracks if they are SW
1291 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1292 break;
1293 }
1294 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
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 output stage session", desc->name);
1299 return BAD_VALUE;
1300 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001301 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1302 // only post processing on output stage session
1303 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1304 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1305 " on device session", desc->name);
1306 return BAD_VALUE;
1307 }
Eric Laurent4c415062016-06-17 16:14:16 -07001308 } else {
1309 // no restriction on effects applied on non fast tracks
1310 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1311 break;
1312 }
1313 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001314
Eric Laurent4c415062016-06-17 16:14:16 -07001315 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1316 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1317 desc->name);
1318 return BAD_VALUE;
1319 }
1320 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1321 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1322 " in fast mode", desc->name);
1323 return BAD_VALUE;
1324 }
1325 }
1326 } break;
1327 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001328 // nothing actionable on offload threads, if the effect:
1329 // - is offloadable: the effect can be created
1330 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1331 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001332 break;
1333 case DIRECT:
1334 // Reject any effect on Direct output threads for now, since the format of
1335 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1336 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1337 desc->name, mThreadName);
1338 return BAD_VALUE;
1339 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001340#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001341 // Reject any effect on mixer multichannel sinks.
1342 // TODO: fix both format and multichannel issues with effects.
1343 if (mChannelCount != FCC_2) {
1344 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1345 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1346 return BAD_VALUE;
1347 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001348#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001349 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001350 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1351 " thread %s", desc->name, mThreadName);
1352 return BAD_VALUE;
1353 }
1354 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1355 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1356 " DUPLICATING thread %s", desc->name, mThreadName);
1357 return BAD_VALUE;
1358 }
1359 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1360 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1361 " DUPLICATING thread %s", desc->name, mThreadName);
1362 return BAD_VALUE;
1363 }
1364 break;
1365 default:
1366 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1367 }
1368
1369 return NO_ERROR;
1370}
1371
Eric Laurent81784c32012-11-19 14:55:58 -08001372// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1373sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1374 const sp<AudioFlinger::Client>& client,
1375 const sp<IEffectClient>& effectClient,
1376 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001377 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001378 effect_descriptor_t *desc,
1379 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001380 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001381 bool pinned,
1382 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001383{
1384 sp<EffectModule> effect;
1385 sp<EffectHandle> handle;
1386 status_t lStatus;
1387 sp<EffectChain> chain;
1388 bool chainCreated = false;
1389 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001390 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001391
1392 lStatus = initCheck();
1393 if (lStatus != NO_ERROR) {
1394 ALOGW("createEffect_l() Audio driver not initialized.");
1395 goto Exit;
1396 }
1397
Eric Laurent81784c32012-11-19 14:55:58 -08001398 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1399
1400 { // scope for mLock
1401 Mutex::Autolock _l(mLock);
1402
Eric Laurent4c415062016-06-17 16:14:16 -07001403 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001404 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001405 goto Exit;
1406 }
1407
Eric Laurent81784c32012-11-19 14:55:58 -08001408 // check for existing effect chain with the requested audio session
1409 chain = getEffectChain_l(sessionId);
1410 if (chain == 0) {
1411 // create a new chain for this session
1412 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1413 chain = new EffectChain(this, sessionId);
1414 addEffectChain_l(chain);
1415 chain->setStrategy(getStrategyForSession_l(sessionId));
1416 chainCreated = true;
1417 } else {
1418 effect = chain->getEffectFromDesc_l(desc);
1419 }
1420
1421 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1422
1423 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001424 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001425 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001426 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001427 if (lStatus != NO_ERROR) {
1428 goto Exit;
1429 }
1430 effectCreated = true;
1431
jiabinc52b1ff2019-10-31 17:20:42 -07001432 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001433 effect->setDevices(outDeviceTypeAddrs());
1434 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001435 effect->setMode(mAudioFlinger->getMode());
1436 effect->setAudioSource(mAudioSource);
1437 }
1438 // create effect handle and connect it to effect module
1439 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001440 lStatus = handle->initCheck();
1441 if (lStatus == OK) {
1442 lStatus = effect->addHandle(handle.get());
1443 }
Eric Laurent81784c32012-11-19 14:55:58 -08001444 if (enabled != NULL) {
1445 *enabled = (int)effect->isEnabled();
1446 }
1447 }
1448
1449Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001450 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001451 Mutex::Autolock _l(mLock);
1452 if (effectCreated) {
1453 chain->removeEffect_l(effect);
1454 }
Eric Laurent81784c32012-11-19 14:55:58 -08001455 if (chainCreated) {
1456 removeEffectChain_l(chain);
1457 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001458 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001459 }
1460
Glenn Kasten9156ef32013-08-06 15:39:08 -07001461 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001462 return handle;
1463}
1464
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001465void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1466 bool unpinIfLast)
1467{
1468 bool remove = false;
1469 sp<EffectModule> effect;
1470 {
1471 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001472 sp<EffectBase> effectBase = handle->effect().promote();
1473 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001474 return;
1475 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001476 effect = effectBase->asEffectModule();
1477 if (effect == nullptr) {
1478 return;
1479 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001480 // restore suspended effects if the disconnected handle was enabled and the last one.
1481 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1482 if (remove) {
1483 removeEffect_l(effect, true);
1484 }
1485 }
1486 if (remove) {
1487 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001488 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001489 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001490 }
1491 }
1492}
1493
Eric Laurent6b446ce2019-12-13 10:56:31 -08001494void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001495 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001496 Mutex::Autolock _l(mLock);
1497 broadcast_l();
1498 }
1499 if (!effect->isOffloadable()) {
1500 if (mType == ThreadBase::OFFLOAD) {
1501 PlaybackThread *t = (PlaybackThread *)this;
1502 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1503 }
1504 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1505 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1506 }
1507 }
1508}
1509
1510void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001511 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001512 Mutex::Autolock _l(mLock);
1513 broadcast_l();
1514 }
1515}
1516
Glenn Kastend848eb42016-03-08 13:42:11 -08001517sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1518 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001519{
1520 Mutex::Autolock _l(mLock);
1521 return getEffect_l(sessionId, effectId);
1522}
1523
Glenn Kastend848eb42016-03-08 13:42:11 -08001524sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1525 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001526{
1527 sp<EffectChain> chain = getEffectChain_l(sessionId);
1528 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1529}
1530
Eric Laurent6c796322019-04-09 14:13:17 -07001531std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1532{
1533 sp<EffectChain> chain = getEffectChain_l(sessionId);
1534 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1535}
1536
Eric Laurent81784c32012-11-19 14:55:58 -08001537// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1538// PlaybackThread::mLock held
1539status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1540{
1541 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001542 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001543 sp<EffectChain> chain = getEffectChain_l(sessionId);
1544 bool chainCreated = false;
1545
Eric Laurent5baf2af2013-09-12 17:37:00 -07001546 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001547 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001548 this, effect->desc().name, effect->desc().flags);
1549
Eric Laurent81784c32012-11-19 14:55:58 -08001550 if (chain == 0) {
1551 // create a new chain for this session
1552 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1553 chain = new EffectChain(this, sessionId);
1554 addEffectChain_l(chain);
1555 chain->setStrategy(getStrategyForSession_l(sessionId));
1556 chainCreated = true;
1557 }
1558 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1559
1560 if (chain->getEffectFromId_l(effect->id()) != 0) {
1561 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1562 this, effect->desc().name, chain.get());
1563 return BAD_VALUE;
1564 }
1565
Eric Laurent5baf2af2013-09-12 17:37:00 -07001566 effect->setOffloaded(mType == OFFLOAD, mId);
1567
Eric Laurent81784c32012-11-19 14:55:58 -08001568 status_t status = chain->addEffect_l(effect);
1569 if (status != NO_ERROR) {
1570 if (chainCreated) {
1571 removeEffectChain_l(chain);
1572 }
1573 return status;
1574 }
1575
jiabin8f278ee2019-11-11 12:16:27 -08001576 effect->setDevices(outDeviceTypeAddrs());
1577 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001578 effect->setMode(mAudioFlinger->getMode());
1579 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001580
Eric Laurent81784c32012-11-19 14:55:58 -08001581 return NO_ERROR;
1582}
1583
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001584void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001585
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001586 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001587 effect_descriptor_t desc = effect->desc();
1588 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1589 detachAuxEffect_l(effect->id());
1590 }
1591
Eric Laurent6b446ce2019-12-13 10:56:31 -08001592 sp<EffectChain> chain = effect->callback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001593 if (chain != 0) {
1594 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001595 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001596 removeEffectChain_l(chain);
1597 }
1598 } else {
1599 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1600 }
1601}
1602
1603void AudioFlinger::ThreadBase::lockEffectChains_l(
1604 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1605{
1606 effectChains = mEffectChains;
1607 for (size_t i = 0; i < mEffectChains.size(); i++) {
1608 mEffectChains[i]->lock();
1609 }
1610}
1611
1612void AudioFlinger::ThreadBase::unlockEffectChains(
1613 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1614{
1615 for (size_t i = 0; i < effectChains.size(); i++) {
1616 effectChains[i]->unlock();
1617 }
1618}
1619
Glenn Kastend848eb42016-03-08 13:42:11 -08001620sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001621{
1622 Mutex::Autolock _l(mLock);
1623 return getEffectChain_l(sessionId);
1624}
1625
Glenn Kastend848eb42016-03-08 13:42:11 -08001626sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1627 const
Eric Laurent81784c32012-11-19 14:55:58 -08001628{
1629 size_t size = mEffectChains.size();
1630 for (size_t i = 0; i < size; i++) {
1631 if (mEffectChains[i]->sessionId() == sessionId) {
1632 return mEffectChains[i];
1633 }
1634 }
1635 return 0;
1636}
1637
1638void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1639{
1640 Mutex::Autolock _l(mLock);
1641 size_t size = mEffectChains.size();
1642 for (size_t i = 0; i < size; i++) {
1643 mEffectChains[i]->setMode_l(mode);
1644 }
1645}
1646
Mikhail Naganovdc769682018-05-04 15:34:08 -07001647void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001648{
1649 config->type = AUDIO_PORT_TYPE_MIX;
1650 config->ext.mix.handle = mId;
1651 config->sample_rate = mSampleRate;
1652 config->format = mFormat;
1653 config->channel_mask = mChannelMask;
1654 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1655 AUDIO_PORT_CONFIG_FORMAT;
1656}
1657
Eric Laurent72e3f392015-05-20 14:43:50 -07001658void AudioFlinger::ThreadBase::systemReady()
1659{
1660 Mutex::Autolock _l(mLock);
1661 if (mSystemReady) {
1662 return;
1663 }
1664 mSystemReady = true;
1665
1666 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1667 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1668 }
1669 mPendingConfigEvents.clear();
1670}
1671
Andy Hungdae27702016-10-31 14:01:16 -07001672template <typename T>
1673ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1674 ssize_t index = mActiveTracks.indexOf(track);
1675 if (index >= 0) {
1676 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1677 return index;
1678 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001679 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001680 mActiveTracksGeneration++;
1681 mLatestActiveTrack = track;
1682 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001683 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001684 return mActiveTracks.add(track);
1685}
1686
1687template <typename T>
1688ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1689 ssize_t index = mActiveTracks.remove(track);
1690 if (index < 0) {
1691 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1692 return index;
1693 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001694 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001695 mActiveTracksGeneration++;
1696 --mBatteryCounter[track->uid()].second;
1697 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001698 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001699#ifdef TEE_SINK
1700 track->dumpTee(-1 /* fd */, "_REMOVE");
1701#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001702 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001703 return index;
1704}
1705
1706template <typename T>
1707void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1708 for (const sp<T> &track : mActiveTracks) {
1709 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001710 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001711 }
1712 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001713 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001714 mActiveTracks.clear();
1715 mLatestActiveTrack.clear();
1716 mBatteryCounter.clear();
1717}
1718
1719template <typename T>
1720void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1721 sp<ThreadBase> thread, bool force) {
1722 // Updates ActiveTracks client uids to the thread wakelock.
1723 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1724 thread->updateWakeLockUids_l(getWakeLockUids());
1725 mLastActiveTracksGeneration = mActiveTracksGeneration;
1726 }
1727
1728 // Updates BatteryNotifier uids
1729 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1730 const uid_t uid = it->first;
1731 ssize_t &previous = it->second.first;
1732 ssize_t &current = it->second.second;
1733 if (current > 0) {
1734 if (previous == 0) {
1735 BatteryNotifier::getInstance().noteStartAudio(uid);
1736 }
1737 previous = current;
1738 ++it;
1739 } else if (current == 0) {
1740 if (previous > 0) {
1741 BatteryNotifier::getInstance().noteStopAudio(uid);
1742 }
1743 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1744 } else /* (current < 0) */ {
1745 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1746 }
1747 }
1748}
Eric Laurent83b88082014-06-20 18:31:16 -07001749
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001750template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001751bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1752 const bool hasChanged = mHasChanged;
1753 mHasChanged = false;
1754 return hasChanged;
1755}
1756
1757template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001758void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1759 const char *funcName, const sp<T> &track) const {
1760 if (mLocalLog != nullptr) {
1761 String8 result;
1762 track->appendDump(result, false /* active */);
1763 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1764 }
1765}
1766
Eric Laurent6acd1d42017-01-04 14:23:29 -08001767void AudioFlinger::ThreadBase::broadcast_l()
1768{
1769 // Thread could be blocked waiting for async
1770 // so signal it to handle state changes immediately
1771 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1772 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1773 mSignalPending = true;
1774 mWaitWorkCV.broadcast();
1775}
1776
Andy Hungd0979812019-02-21 15:51:44 -08001777// Call only from threadLoop() or when it is idle.
1778// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1779void AudioFlinger::ThreadBase::sendStatistics(bool force)
1780{
1781 // Do not log if we have no stats.
1782 // We choose the timestamp verifier because it is the most likely item to be present.
1783 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1784 if (nstats == 0) {
1785 return;
1786 }
1787
1788 // Don't log more frequently than once per 12 hours.
1789 // We use BOOTTIME to include suspend time.
1790 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1791 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1792 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1793 return;
1794 }
1795
1796 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1797 mLastRecordedTimeNs = timeNs;
1798
Ray Essickf27e9872019-12-07 06:28:46 -08001799 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001800
1801#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1802
1803 // thread configuration
1804 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1805 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1806 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1807 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1808 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1809 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1810 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001811 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1812 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001813
1814 // thread statistics
1815 if (mIoJitterMs.getN() > 0) {
1816 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1817 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1818 }
1819 if (mProcessTimeMs.getN() > 0) {
1820 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1821 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1822 }
1823 const auto tsjitter = mTimestampVerifier.getJitterMs();
1824 if (tsjitter.getN() > 0) {
1825 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1826 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1827 }
1828 if (mLatencyMs.getN() > 0) {
1829 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1830 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1831 }
1832
1833 item->selfrecord();
1834}
1835
Eric Laurent81784c32012-11-19 14:55:58 -08001836// ----------------------------------------------------------------------------
1837// Playback
1838// ----------------------------------------------------------------------------
1839
1840AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1841 AudioStreamOut* output,
1842 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001843 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001844 bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07001845 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001846 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001847 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001848 mMixerBuffer(NULL),
1849 mMixerBufferSize(0),
1850 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1851 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001852 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001853 mEffectBuffer(NULL),
1854 mEffectBufferSize(0),
1855 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1856 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001857 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001858 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001859 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001860 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001861 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001862 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001863 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001864 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001865 mMixerStatus(MIXER_IDLE),
1866 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001867 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001868 mBytesRemaining(0),
1869 mCurrentWriteLength(0),
1870 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001871 mWriteAckSequence(0),
1872 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001873 mScreenState(AudioFlinger::mScreenState),
1874 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001875 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001876 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1877 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001878{
Glenn Kastend7dca052015-03-05 16:05:54 -08001879 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1880 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001881
1882 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1883 // it would be safer to explicitly pass initial masterVolume/masterMute as
1884 // parameter.
1885 //
1886 // If the HAL we are using has support for master volume or master mute,
1887 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1888 // and the mute set to false).
1889 mMasterVolume = audioFlinger->masterVolume_l();
1890 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001891 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001892 if (mOutput->audioHwDev->canSetMasterVolume()) {
1893 mMasterVolume = 1.0;
1894 }
1895
1896 if (mOutput->audioHwDev->canSetMasterMute()) {
1897 mMasterMute = false;
1898 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001899 mIsMsdDevice = strcmp(
1900 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001901 }
1902
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001903 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001904
Andy Hungc8fddf32018-08-08 18:32:37 -07001905 // TODO: We may also match on address as well as device type for
1906 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001907 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001908 // TODO: This property should be ensure that only contains one single device type.
1909 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1910 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001911 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1912 : AUDIO_DEVICE_NONE));
1913 }
1914
Eric Laurent223fd5c2014-11-11 13:43:36 -08001915 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001916 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001917 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001918 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001919 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1920 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001921 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08001922 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1923 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08001924 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1925 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001926}
1927
1928AudioFlinger::PlaybackThread::~PlaybackThread()
1929{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001930 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001931 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001932 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001933 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001934}
1935
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001936// Thread virtuals
1937
1938void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001939{
jiabinf6eb4c32020-02-25 14:06:25 -08001940 if (mOutput == nullptr || mOutput->stream == nullptr) {
1941 ALOGE("The stream is not open yet"); // This should not happen.
1942 } else {
1943 // setEventCallback will need a strong pointer as a parameter. Calling it
1944 // here instead of constructor of PlaybackThread so that the onFirstRef
1945 // callback would not be made on an incompletely constructed object.
1946 if (mOutput->stream->setEventCallback(this) != OK) {
1947 ALOGE("Failed to add event callback");
1948 }
1949 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001950 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001951}
1952
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001953// ThreadBase virtuals
1954void AudioFlinger::PlaybackThread::preExit()
1955{
1956 ALOGV(" preExit()");
1957 // FIXME this is using hard-coded strings but in the future, this functionality will be
1958 // converted to use audio HAL extensions required to support tunneling
1959 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1960 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1961}
1962
1963void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001964{
Eric Laurent81784c32012-11-19 14:55:58 -08001965 String8 result;
1966
Marco Nelissenb2208842014-02-07 14:00:50 -08001967 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001968 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1969 const stream_type_t *st = &mStreamTypes[i];
1970 if (i > 0) {
1971 result.appendFormat(", ");
1972 }
1973 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1974 if (st->mute) {
1975 result.append("M");
1976 }
1977 }
1978 result.append("\n");
1979 write(fd, result.string(), result.length());
1980 result.clear();
1981
Eric Laurent81784c32012-11-19 14:55:58 -08001982 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1983 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001984 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001985 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001986
1987 size_t numtracks = mTracks.size();
1988 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001989 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001990 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001991 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001992 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001993 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001994 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001995 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001996 for (size_t i = 0; i < numtracks; ++i) {
1997 sp<Track> track = mTracks[i];
1998 if (track != 0) {
1999 bool active = mActiveTracks.indexOf(track) >= 0;
2000 if (active) {
2001 numactiveseen++;
2002 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002003 result.append(prefix);
2004 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002005 }
2006 }
2007 } else {
2008 result.append("\n");
2009 }
2010 if (numactiveseen != numactive) {
2011 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002012 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002013 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002014 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002015 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002016 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002017 sp<Track> track = mActiveTracks[i];
2018 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002019 result.append(prefix);
2020 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002021 }
2022 }
2023 }
2024
2025 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002026}
2027
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002028void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002029{
Andy Hung04cb8f72020-03-20 13:44:33 -07002030 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002031 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08002032 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2033 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2034 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2035 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002036 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002037 dprintf(fd, " Total writes: %d\n", mNumWrites);
2038 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2039 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2040 dprintf(fd, " Suspend count: %d\n", mSuspended);
2041 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2042 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2043 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2044 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002045 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002046 AudioStreamOut *output = mOutput;
2047 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002048 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002049 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002050 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2051 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2052 if (mPipeSink.get() != nullptr) {
2053 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2054 }
2055 if (output != nullptr) {
2056 dprintf(fd, " Hal stream dump:\n");
2057 (void)output->stream->dump(fd);
2058 }
Eric Laurent81784c32012-11-19 14:55:58 -08002059}
2060
Eric Laurent81784c32012-11-19 14:55:58 -08002061// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2062sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2063 const sp<AudioFlinger::Client>& client,
2064 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002065 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002066 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002067 audio_format_t format,
2068 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002069 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002070 size_t *pNotificationFrameCount,
2071 uint32_t notificationsPerBuffer,
2072 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002073 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002074 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002075 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002076 pid_t creatorPid,
Eric Laurent81784c32012-11-19 14:55:58 -08002077 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08002078 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002079 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002080 audio_port_handle_t portId,
2081 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002082{
Glenn Kasten74935e42013-12-19 08:56:45 -08002083 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002084 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002085 sp<Track> track;
2086 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002087 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002088 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002089 uint32_t sampleRate;
2090
2091 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2092 lStatus = BAD_VALUE;
2093 goto Exit;
2094 }
Eric Laurent21da6472017-11-09 16:29:26 -08002095
2096 if (*pSampleRate == 0) {
2097 *pSampleRate = mSampleRate;
2098 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002099 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002100
2101 // special case for FAST flag considered OK if fast mixer is present
2102 if (hasFastMixer()) {
2103 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2104 }
2105
2106 // Check if requested flags are compatible with output stream flags
2107 if ((*flags & outputFlags) != *flags) {
2108 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2109 *flags, outputFlags);
2110 *flags = (audio_output_flags_t)(*flags & outputFlags);
2111 }
Eric Laurent81784c32012-11-19 14:55:58 -08002112
Eric Laurent81784c32012-11-19 14:55:58 -08002113 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002114 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002115 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002116 // PCM data
2117 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002118 // TODO: extract as a data library function that checks that a computationally
2119 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002120 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002121 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2122 (channelMask == AUDIO_CHANNEL_OUT_MONO
2123 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002124 // hardware sample rate
2125 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002126 // normal mixer has an associated fast mixer
2127 hasFastMixer() &&
2128 // there are sufficient fast track slots available
2129 (mFastTrackAvailMask != 0)
2130 // FIXME test that MixerThread for this fast track has a capable output HAL
2131 // FIXME add a permission test also?
2132 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002133 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2134 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002135 // read the fast track multiplier property the first time it is needed
2136 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2137 if (ok != 0) {
2138 ALOGE("%s pthread_once failed: %d", __func__, ok);
2139 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002140 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002141 }
Eric Laurent4c415062016-06-17 16:14:16 -07002142
2143 // check compatibility with audio effects.
2144 { // scope for mLock
2145 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002146 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002147 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002148 AUDIO_SESSION_OUTPUT_STAGE,
2149 AUDIO_SESSION_OUTPUT_MIX,
2150 sessionId,
2151 }) {
2152 sp<EffectChain> chain = getEffectChain_l(session);
2153 if (chain.get() != nullptr) {
2154 audio_output_flags_t old = *flags;
2155 chain->checkOutputFlagCompatibility(flags);
2156 if (old != *flags) {
2157 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2158 (int)session, (int)old, (int)*flags);
2159 }
Eric Laurent4c415062016-06-17 16:14:16 -07002160 }
2161 }
2162 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002163 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002164 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2165 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002166 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002167 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2168 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002169 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002170 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002171 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002172 audio_is_linear_pcm(format),
2173 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002174 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002175 }
2176 }
Eric Laurent21da6472017-11-09 16:29:26 -08002177
2178 if (!audio_has_proportional_frames(format)) {
2179 if (sharedBuffer != 0) {
2180 // Same comment as below about ignoring frameCount parameter for set()
2181 frameCount = sharedBuffer->size();
2182 } else if (frameCount == 0) {
2183 frameCount = mNormalFrameCount;
2184 }
2185 if (notificationFrameCount != frameCount) {
2186 notificationFrameCount = frameCount;
2187 }
2188 } else if (sharedBuffer != 0) {
2189 // FIXME: Ensure client side memory buffers need
2190 // not have additional alignment beyond sample
2191 // (e.g. 16 bit stereo accessed as 32 bit frame).
2192 size_t alignment = audio_bytes_per_sample(format);
2193 if (alignment & 1) {
2194 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2195 alignment = 1;
2196 }
2197 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2198 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2199 if (channelCount > 1) {
2200 // More than 2 channels does not require stronger alignment than stereo
2201 alignment <<= 1;
2202 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002203 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002204 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002205 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002206 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002207 goto Exit;
2208 }
Eric Laurent21da6472017-11-09 16:29:26 -08002209
2210 // When initializing a shared buffer AudioTrack via constructors,
2211 // there's no frameCount parameter.
2212 // But when initializing a shared buffer AudioTrack via set(),
2213 // there _is_ a frameCount parameter. We silently ignore it.
2214 frameCount = sharedBuffer->size() / frameSize;
2215 } else {
2216 size_t minFrameCount = 0;
2217 // For fast tracks we try to respect the application's request for notifications per buffer.
2218 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2219 if (notificationsPerBuffer > 0) {
2220 // Avoid possible arithmetic overflow during multiplication.
2221 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2222 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2223 notificationsPerBuffer, mFrameCount);
2224 } else {
2225 minFrameCount = mFrameCount * notificationsPerBuffer;
2226 }
2227 }
2228 } else {
2229 // For normal PCM streaming tracks, update minimum frame count.
2230 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2231 // cover audio hardware latency.
2232 // This is probably too conservative, but legacy application code may depend on it.
2233 // If you change this calculation, also review the start threshold which is related.
2234 uint32_t latencyMs = latency_l();
2235 if (latencyMs == 0) {
2236 ALOGE("Error when retrieving output stream latency");
2237 lStatus = UNKNOWN_ERROR;
2238 goto Exit;
2239 }
2240
2241 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2242 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2243
Eric Laurent81784c32012-11-19 14:55:58 -08002244 }
Eric Laurent21da6472017-11-09 16:29:26 -08002245 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002246 frameCount = minFrameCount;
2247 }
Eric Laurent81784c32012-11-19 14:55:58 -08002248 }
Eric Laurent21da6472017-11-09 16:29:26 -08002249
2250 // Make sure that application is notified with sufficient margin before underrun.
2251 // The client can divide the AudioTrack buffer into sub-buffers,
2252 // and expresses its desire to server as the notification frame count.
2253 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2254 size_t maxNotificationFrames;
2255 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2256 // notify every HAL buffer, regardless of the size of the track buffer
2257 maxNotificationFrames = mFrameCount;
2258 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002259 // Triple buffer the notification period for a triple buffered mixer period;
2260 // otherwise, double buffering for the notification period is fine.
2261 //
2262 // TODO: This should be moved to AudioTrack to modify the notification period
2263 // on AudioTrack::setBufferSizeInFrames() changes.
2264 const int nBuffering =
2265 (uint64_t{frameCount} * mSampleRate)
2266 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2267
Eric Laurent21da6472017-11-09 16:29:26 -08002268 maxNotificationFrames = frameCount / nBuffering;
2269 // If client requested a fast track but this was denied, then use the smaller maximum.
2270 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2271 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2272 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2273 maxNotificationFrames = maxNotificationFramesFastDenied;
2274 }
2275 }
2276 }
2277 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2278 if (notificationFrameCount == 0) {
2279 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2280 maxNotificationFrames, frameCount);
2281 } else {
2282 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2283 notificationFrameCount, maxNotificationFrames, frameCount);
2284 }
2285 notificationFrameCount = maxNotificationFrames;
2286 }
2287 }
2288
Glenn Kasten74935e42013-12-19 08:56:45 -08002289 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002290 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002291
Glenn Kastenc3df8382014-03-13 15:05:25 -07002292 switch (mType) {
2293
2294 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002295 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002296 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002297 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2298 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002299 sampleRate, format, channelMask, mOutput, mFormat);
2300 lStatus = BAD_VALUE;
2301 goto Exit;
2302 }
2303 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002304 break;
2305
2306 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002307 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002308 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2309 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002310 sampleRate, format, channelMask, mOutput, mFormat);
2311 lStatus = BAD_VALUE;
2312 goto Exit;
2313 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002314 break;
2315
2316 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002317 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002318 ALOGE("createTrack_l() Bad parameter: format %#x \""
2319 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002320 format, mOutput, mFormat);
2321 lStatus = BAD_VALUE;
2322 goto Exit;
2323 }
Andy Hungcd044842014-08-07 11:04:34 -07002324 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002325 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2326 lStatus = BAD_VALUE;
2327 goto Exit;
2328 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002329 break;
2330
Eric Laurent81784c32012-11-19 14:55:58 -08002331 }
2332
2333 lStatus = initCheck();
2334 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002335 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002336 goto Exit;
2337 }
2338
2339 { // scope for mLock
2340 Mutex::Autolock _l(mLock);
2341
2342 // all tracks in same audio session must share the same routing strategy otherwise
2343 // conflicts will happen when tracks are moved from one output to another by audio policy
2344 // manager
2345 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2346 for (size_t i = 0; i < mTracks.size(); ++i) {
2347 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002348 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002349 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2350 if (sessionId == t->sessionId() && strategy != actual) {
2351 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2352 strategy, actual);
2353 lStatus = BAD_VALUE;
2354 goto Exit;
2355 }
2356 }
2357 }
2358
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002359 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002360 channelMask, frameCount,
2361 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002362 sessionId, creatorPid, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002363
Glenn Kasten03003332013-08-06 15:40:54 -07002364 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2365 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002366 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002367 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002368 goto Exit;
2369 }
2370 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002371 {
2372 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2373 if (callback.get() != nullptr) {
2374 mAudioTrackCallbacks.emplace(callback);
2375 }
2376 }
Eric Laurent81784c32012-11-19 14:55:58 -08002377
2378 sp<EffectChain> chain = getEffectChain_l(sessionId);
2379 if (chain != 0) {
2380 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2381 track->setMainBuffer(chain->inBuffer());
2382 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2383 chain->incTrackCnt();
2384 }
2385
Eric Laurent05067782016-06-01 18:27:28 -07002386 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002387 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2388 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2389 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002390 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002391 }
2392 }
2393
2394 lStatus = NO_ERROR;
2395
2396Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002397 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002398 return track;
2399}
2400
Andy Hung1bc088a2018-02-09 15:57:31 -08002401template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002402ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2403{
Andy Hungc0691382018-09-12 18:01:57 -07002404 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002405 const ssize_t index = mTracks.remove(track);
2406 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002407 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002408 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002409 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002410 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002411 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002412 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002413 }
2414 return index;
2415}
2416
Eric Laurent81784c32012-11-19 14:55:58 -08002417uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2418{
2419 return latency;
2420}
2421
2422uint32_t AudioFlinger::PlaybackThread::latency() const
2423{
2424 Mutex::Autolock _l(mLock);
2425 return latency_l();
2426}
2427uint32_t AudioFlinger::PlaybackThread::latency_l() const
2428{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002429 uint32_t latency;
2430 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2431 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002432 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002433 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002434}
2435
2436void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2437{
2438 Mutex::Autolock _l(mLock);
2439 // Don't apply master volume in SW if our HAL can do it for us.
2440 if (mOutput && mOutput->audioHwDev &&
2441 mOutput->audioHwDev->canSetMasterVolume()) {
2442 mMasterVolume = 1.0;
2443 } else {
2444 mMasterVolume = value;
2445 }
2446}
2447
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002448void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2449{
2450 mMasterBalance.store(balance);
2451}
2452
Eric Laurent81784c32012-11-19 14:55:58 -08002453void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2454{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002455 if (isDuplicating()) {
2456 return;
2457 }
Eric Laurent81784c32012-11-19 14:55:58 -08002458 Mutex::Autolock _l(mLock);
2459 // Don't apply master mute in SW if our HAL can do it for us.
2460 if (mOutput && mOutput->audioHwDev &&
2461 mOutput->audioHwDev->canSetMasterMute()) {
2462 mMasterMute = false;
2463 } else {
2464 mMasterMute = muted;
2465 }
2466}
2467
2468void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2469{
2470 Mutex::Autolock _l(mLock);
2471 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002472 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002473}
2474
2475void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2476{
2477 Mutex::Autolock _l(mLock);
2478 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002479 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002480}
2481
2482float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2483{
2484 Mutex::Autolock _l(mLock);
2485 return mStreamTypes[stream].volume;
2486}
2487
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002488void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2489{
2490 mOutput->stream->setVolume(left, right);
2491}
2492
Eric Laurent81784c32012-11-19 14:55:58 -08002493// addTrack_l() must be called with ThreadBase::mLock held
2494status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2495{
2496 status_t status = ALREADY_EXISTS;
2497
Eric Laurent81784c32012-11-19 14:55:58 -08002498 if (mActiveTracks.indexOf(track) < 0) {
2499 // the track is newly added, make sure it fills up all its
2500 // buffers before playing. This is to ensure the client will
2501 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002502 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002503 TrackBase::track_state state = track->mState;
2504 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002505 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002506 mLock.lock();
2507 // abort track was stopped/paused while we released the lock
2508 if (state != track->mState) {
2509 if (status == NO_ERROR) {
2510 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002511 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002512 mLock.lock();
2513 }
2514 return INVALID_OPERATION;
2515 }
2516 // abort if start is rejected by audio policy manager
2517 if (status != NO_ERROR) {
2518 return PERMISSION_DENIED;
2519 }
2520#ifdef ADD_BATTERY_DATA
2521 // to track the speaker usage
2522 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2523#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002524 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002525 }
2526
Eric Laurent51716182016-02-29 18:00:56 -08002527 // set retry count for buffer fill
2528 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002529 if (track->isStopping_1()) {
2530 track->mRetryCount = kMaxTrackStopRetriesOffload;
2531 } else {
2532 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2533 }
2534 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002535 } else {
2536 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002537 track->mFillingUpStatus =
2538 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002539 }
2540
jiabineb3bda02020-06-30 14:07:03 -07002541 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2542 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2543 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2544 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002545 // Unlock due to VibratorService will lock for this call and will
2546 // call Tracks.mute/unmute which also require thread's lock.
2547 mLock.unlock();
2548 const int intensity = AudioFlinger::onExternalVibrationStart(
2549 track->getExternalVibration());
2550 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002551 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002552 // Haptic playback should be enabled by vibrator service.
2553 if (track->getHapticPlaybackEnabled()) {
2554 // Disable haptic playback of all active track to ensure only
2555 // one track playing haptic if current track should play haptic.
2556 for (const auto &t : mActiveTracks) {
2557 t->setHapticPlaybackEnabled(false);
2558 }
jiabin245cdd92018-12-07 17:55:15 -08002559 }
jiabine70bc7f2020-06-30 22:07:55 -07002560
2561 // Set haptic intensity for effect
2562 if (chain != nullptr) {
2563 chain->setHapticIntensity_l(track->id(), intensity);
2564 }
jiabin245cdd92018-12-07 17:55:15 -08002565 }
2566
Eric Laurent81784c32012-11-19 14:55:58 -08002567 track->mResetDone = false;
2568 track->mPresentationCompleteFrames = 0;
2569 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002570 if (chain != 0) {
2571 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2572 track->sessionId());
2573 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002574 }
2575
Andy Hungc2b11cb2020-04-22 09:04:01 -07002576 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002577 status = NO_ERROR;
2578 }
2579
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002580 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002581 return status;
2582}
2583
Eric Laurentbfb1b832013-01-07 09:53:42 -08002584bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002585{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002586 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002587 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002588 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2589 track->mState = TrackBase::STOPPED;
2590 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002591 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002592 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002593 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002594 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595
2596 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002597}
2598
2599void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2600{
2601 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002602
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002603 String8 result;
2604 track->appendDump(result, false /* active */);
2605 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002606
Eric Laurent81784c32012-11-19 14:55:58 -08002607 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002608 if (track->isFastTrack()) {
2609 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002610 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002611 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2612 mFastTrackAvailMask |= 1 << index;
2613 // redundant as track is about to be destroyed, for dumpsys only
2614 track->mFastIndex = -1;
2615 }
2616 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2617 if (chain != 0) {
2618 chain->decTrackCnt();
2619 }
2620}
2621
2622String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2623{
Eric Laurent81784c32012-11-19 14:55:58 -08002624 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002625 String8 out_s8;
2626 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2627 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002628 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002629 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002630}
2631
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002632status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2633 Mutex::Autolock _l(mLock);
2634 if (mOutput == nullptr || mOutput->stream == nullptr) {
2635 return NO_INIT;
2636 }
2637 return mOutput->stream->selectPresentation(presentationId, programId);
2638}
2639
Eric Laurent09f1ed22019-04-24 17:45:17 -07002640void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2641 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002642 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2643 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002644
Eric Laurent73e26b62015-04-27 16:55:58 -07002645 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002646
2647 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002648 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002649 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002650 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002651 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002652 desc->mChannelMask = mChannelMask;
2653 desc->mSamplingRate = mSampleRate;
2654 desc->mFormat = mFormat;
2655 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002656 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002657 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002658 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002659 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002660 case AUDIO_CLIENT_STARTED:
2661 desc->mPatch = mPatch;
2662 desc->mPortId = portId;
2663 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002664 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002665 default:
2666 break;
2667 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002668 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002669}
2670
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002671void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002672{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002673 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674}
2675
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002676void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002678 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002679}
2680
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002681void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002682{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002683 mCallbackThread->setAsyncError();
2684}
2685
jiabinf6eb4c32020-02-25 14:06:25 -08002686void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2687 const std::basic_string<uint8_t>& metadataBs)
2688{
2689 std::thread([this, metadataBs]() {
2690 audio_utils::metadata::Data metadata =
2691 audio_utils::metadata::dataFromByteString(metadataBs);
2692 if (metadata.empty()) {
2693 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2694 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2695 (int)metadataBs.size());
2696 return;
2697 }
2698
2699 audio_utils::metadata::ByteString metaDataStr =
2700 audio_utils::metadata::byteStringFromData(metadata);
2701 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2702 Mutex::Autolock _l(mAudioTrackCbLock);
2703 for (const auto& callback : mAudioTrackCallbacks) {
2704 callback->onCodecFormatChanged(metadataVec);
2705 }
2706 }).detach();
2707}
2708
Eric Laurent3b4529e2013-09-05 18:09:19 -07002709void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002710{
2711 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002712 // reject out of sequence requests
2713 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2714 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002715 mWaitWorkCV.signal();
2716 }
2717}
2718
Eric Laurent3b4529e2013-09-05 18:09:19 -07002719void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002720{
2721 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002722 // reject out of sequence requests
2723 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002724 // Register discontinuity when HW drain is completed because that can cause
2725 // the timestamp frame position to reset to 0 for direct and offload threads.
2726 // (Out of sequence requests are ignored, since the discontinuity would be handled
2727 // elsewhere, e.g. in flush).
2728 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002729 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002730 mWaitWorkCV.signal();
2731 }
2732}
2733
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002734void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002735{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002736 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002737 mSampleRate = mOutput->getSampleRate();
2738 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002739 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002740 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002741 }
Andy Hung9a592762014-07-21 21:56:01 -07002742 if ((mType == MIXER || mType == DUPLICATING)
2743 && !isValidPcmSinkChannelMask(mChannelMask)) {
2744 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2745 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002746 }
Andy Hunge5412692014-05-16 11:25:07 -07002747 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002748 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002749
2750 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002751 status_t result = mOutput->stream->getFormat(&mHALFormat);
2752 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002753 // Get format from the shim, which will be different than the HAL format
2754 // if playing compressed audio over HDMI passthrough.
2755 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002756 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002757 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002758 }
Andy Hung6146c082014-03-18 11:56:15 -07002759 if ((mType == MIXER || mType == DUPLICATING)
2760 && !isValidPcmSinkFormat(mFormat)) {
2761 LOG_FATAL("HAL format %#x not supported for mixed output",
2762 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002763 }
Phil Burk062e67a2015-02-11 13:40:50 -08002764 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002765 result = mOutput->stream->getBufferSize(&mBufferSize);
2766 LOG_ALWAYS_FATAL_IF(result != OK,
2767 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002768 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002769 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002770 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002771 mFrameCount);
2772 }
2773
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002774 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2775 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002776 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002777 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002778 }
2779 }
2780
Eric Laurentd1f69b02014-12-15 14:33:13 -08002781 mHwSupportsPause = false;
2782 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002783 bool supportsPause = false, supportsResume = false;
2784 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2785 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002786 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002787 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002788 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002789 } else if (supportsResume) {
2790 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002791 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002792 }
2793 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002794 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2795 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2796 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002797
Andy Hungfbfc3952015-01-15 13:33:51 -08002798 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2799 // For best precision, we use float instead of the associated output
2800 // device format (typically PCM 16 bit).
2801
2802 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2803 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2804 mBufferSize = mFrameSize * mFrameCount;
2805
2806 // TODO: We currently use the associated output device channel mask and sample rate.
2807 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2808 // (if a valid mask) to avoid premature downmix.
2809 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2810 // instead of the output device sample rate to avoid loss of high frequency information.
2811 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2812 }
2813
Andy Hung09a50072014-02-27 14:30:47 -08002814 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002815 double multiplier = 1.0;
2816 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2817 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002818 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2819 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002820
Eric Laurent81784c32012-11-19 14:55:58 -08002821 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2822 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2823 maxNormalFrameCount = maxNormalFrameCount & ~15;
2824 if (maxNormalFrameCount < minNormalFrameCount) {
2825 maxNormalFrameCount = minNormalFrameCount;
2826 }
2827 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2828 if (multiplier <= 1.0) {
2829 multiplier = 1.0;
2830 } else if (multiplier <= 2.0) {
2831 if (2 * mFrameCount <= maxNormalFrameCount) {
2832 multiplier = 2.0;
2833 } else {
2834 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2835 }
2836 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002837 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002838 }
2839 }
2840 mNormalFrameCount = multiplier * mFrameCount;
2841 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002842 if (mType == MIXER || mType == DUPLICATING) {
2843 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2844 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002845 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002846 mNormalFrameCount);
2847
Andy Hung08fb1742015-05-31 23:22:10 -07002848 // Check if we want to throttle the processing to no more than 2x normal rate
2849 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002850 mThreadThrottleTimeMs = 0;
2851 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002852 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2853
Andy Hung010a1a12014-03-13 13:57:33 -07002854 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2855 // Originally this was int16_t[] array, need to remove legacy implications.
2856 free(mSinkBuffer);
2857 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002858 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2859 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2860 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002861 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002862
Andy Hung69aed5f2014-02-25 17:24:40 -08002863 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2864 // drives the output.
2865 free(mMixerBuffer);
2866 mMixerBuffer = NULL;
2867 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002868 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002869 mMixerBufferSize = mNormalFrameCount * mChannelCount
2870 * audio_bytes_per_sample(mMixerBufferFormat);
2871 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2872 }
Andy Hung98ef9782014-03-04 14:46:50 -08002873 free(mEffectBuffer);
2874 mEffectBuffer = NULL;
2875 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002876 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002877 mEffectBufferSize = mNormalFrameCount * mChannelCount
2878 * audio_bytes_per_sample(mEffectBufferFormat);
2879 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2880 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002881
jiabin245cdd92018-12-07 17:55:15 -08002882 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2883 mChannelMask &= ~mHapticChannelMask;
2884 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2885 mChannelCount -= mHapticChannelCount;
2886
Eric Laurent81784c32012-11-19 14:55:58 -08002887 // force reconfiguration of effect chains and engines to take new buffer size and audio
2888 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002889 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002890 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2891 // matter.
2892 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2893 Vector< sp<EffectChain> > effectChains = mEffectChains;
2894 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002895 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2896 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002897 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002898
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002899 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002900 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002901 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2902 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2903 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2904 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2905 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2906 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2907 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2908 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2909 (int32_t)mHapticChannelMask)
2910 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2911 (int32_t)mHapticChannelCount)
2912 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2913 formatToString(mHALFormat).c_str())
2914 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2915 (int32_t)mFrameCount) // sic - added HAL
2916 ;
2917 uint32_t latencyMs;
2918 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2919 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2920 }
2921 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08002922}
2923
Kevin Rocard069c2712018-03-29 19:09:14 -07002924void AudioFlinger::PlaybackThread::updateMetadata_l()
2925{
Kevin Rocard12381092018-04-11 09:19:59 -07002926 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2927 return; // That should not happen
2928 }
2929 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2930 for (const sp<Track> &track : mActiveTracks) {
2931 // Do not short-circuit as all hasChanged states must be reset
2932 // as all the metadata are going to be sent
2933 hasChanged |= track->readAndClearHasChanged();
2934 }
2935 if (!hasChanged) {
2936 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002937 }
2938 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002939 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002940 for (const sp<Track> &track : mActiveTracks) {
2941 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002942 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002943 }
Kevin Rocard12381092018-04-11 09:19:59 -07002944 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002945}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002946
Kevin Rocard12381092018-04-11 09:19:59 -07002947void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2948 const StreamOutHalInterface::SourceMetadata& metadata)
2949{
2950 mOutput->stream->updateSourceMetadata(metadata);
2951};
2952
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002953status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002954{
2955 if (halFrames == NULL || dspFrames == NULL) {
2956 return BAD_VALUE;
2957 }
2958 Mutex::Autolock _l(mLock);
2959 if (initCheck() != NO_ERROR) {
2960 return INVALID_OPERATION;
2961 }
Andy Hung818e7a32016-02-16 18:08:07 -08002962 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002963 *halFrames = framesWritten;
2964
2965 if (isSuspended()) {
2966 // return an estimation of rendered frames when the output is suspended
2967 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002968 *dspFrames = (uint32_t)
2969 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002970 return NO_ERROR;
2971 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002972 status_t status;
2973 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002974 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002975 *dspFrames = (size_t)frames;
2976 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002977 }
2978}
2979
Glenn Kastend848eb42016-03-08 13:42:11 -08002980uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002981{
2982 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2983 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2984 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2985 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2986 }
2987 for (size_t i = 0; i < mTracks.size(); i++) {
2988 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002989 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002990 return AudioSystem::getStrategyForStream(track->streamType());
2991 }
2992 }
2993 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2994}
2995
2996
Phil Burk062e67a2015-02-11 13:40:50 -08002997AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002998{
2999 Mutex::Autolock _l(mLock);
3000 return mOutput;
3001}
3002
Phil Burk062e67a2015-02-11 13:40:50 -08003003AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003004{
3005 Mutex::Autolock _l(mLock);
3006 AudioStreamOut *output = mOutput;
3007 mOutput = NULL;
3008 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3009 // must push a NULL and wait for ack
3010 mOutputSink.clear();
3011 mPipeSink.clear();
3012 mNormalSink.clear();
3013 return output;
3014}
3015
3016// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003017sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003018{
3019 if (mOutput == NULL) {
3020 return NULL;
3021 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003022 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003023}
3024
3025uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3026{
3027 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3028}
3029
3030status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3031{
3032 if (!isValidSyncEvent(event)) {
3033 return BAD_VALUE;
3034 }
3035
3036 Mutex::Autolock _l(mLock);
3037
3038 for (size_t i = 0; i < mTracks.size(); ++i) {
3039 sp<Track> track = mTracks[i];
3040 if (event->triggerSession() == track->sessionId()) {
3041 (void) track->setSyncEvent(event);
3042 return NO_ERROR;
3043 }
3044 }
3045
3046 return NAME_NOT_FOUND;
3047}
3048
3049bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3050{
3051 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3052}
3053
3054void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3055 const Vector< sp<Track> >& tracksToRemove)
3056{
Andy Hungfe726a62018-09-27 15:17:25 -07003057 // Miscellaneous track cleanup when removed from the active list,
3058 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003059#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003060 for (const auto& track : tracksToRemove) {
3061 if (track->isExternalTrack()) {
3062 // to track the speaker usage
3063 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003064 }
3065 }
Andy Hungfe726a62018-09-27 15:17:25 -07003066#else
3067 (void)tracksToRemove; // suppress unused warning
3068#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003069}
3070
3071void AudioFlinger::PlaybackThread::checkSilentMode_l()
3072{
3073 if (!mMasterMute) {
3074 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003075 if (mOutDeviceTypeAddrs.empty()) {
3076 ALOGD("ro.audio.silent is ignored since no output device is set");
3077 return;
3078 }
jiabinc52b1ff2019-10-31 17:20:42 -07003079 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003080 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3081 return;
3082 }
Eric Laurent81784c32012-11-19 14:55:58 -08003083 if (property_get("ro.audio.silent", value, "0") > 0) {
3084 char *endptr;
3085 unsigned long ul = strtoul(value, &endptr, 0);
3086 if (*endptr == '\0' && ul != 0) {
3087 ALOGD("Silence is golden");
3088 // The setprop command will not allow a property to be changed after
3089 // the first time it is set, so we don't have to worry about un-muting.
3090 setMasterMute_l(true);
3091 }
3092 }
3093 }
3094}
3095
3096// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003097ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003098{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003099 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003100 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003101 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003102 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003103
3104 // If an NBAIO sink is present, use it to write the normal mixer's submix
3105 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003106
Andy Hung010a1a12014-03-13 13:57:33 -07003107 const size_t count = mBytesRemaining / mFrameSize;
3108
Simon Wilson2d590962012-11-29 15:18:50 -08003109 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003110 // update the setpoint when AudioFlinger::mScreenState changes
3111 uint32_t screenState = AudioFlinger::mScreenState;
3112 if (screenState != mScreenState) {
3113 mScreenState = screenState;
3114 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3115 if (pipe != NULL) {
3116 pipe->setAvgFrames((mScreenState & 1) ?
3117 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3118 }
3119 }
Andy Hung010a1a12014-03-13 13:57:33 -07003120 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003121 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003122 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003123 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003124#ifdef TEE_SINK
3125 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3126#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003127 } else {
3128 bytesWritten = framesWritten;
3129 }
3130 // otherwise use the HAL / AudioStreamOut directly
3131 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003132 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003133
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003135 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3136 mWriteAckSequence += 2;
3137 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 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003141 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003142 // FIXME We should have an implementation of timestamps for direct output threads.
3143 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003144 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003145 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003146
Eric Laurentbfb1b832013-01-07 09:53:42 -08003147 if (mUseAsyncWrite &&
3148 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3149 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003150 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003151 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003152 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003153 }
Eric Laurent81784c32012-11-19 14:55:58 -08003154 }
3155
Eric Laurent81784c32012-11-19 14:55:58 -08003156 mNumWrites++;
3157 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003158 if (mStandby) {
3159 mThreadMetrics.logBeginInterval();
3160 mStandby = false;
3161 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162 return bytesWritten;
3163}
3164
3165void AudioFlinger::PlaybackThread::threadLoop_drain()
3166{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003167 bool supportsDrain = false;
3168 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3170 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003171 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3172 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003173 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003174 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003175 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003176 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003177 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003178 }
3179}
3180
3181void AudioFlinger::PlaybackThread::threadLoop_exit()
3182{
Eric Laurent275e8e92014-11-30 15:14:47 -08003183 {
3184 Mutex::Autolock _l(mLock);
3185 for (size_t i = 0; i < mTracks.size(); i++) {
3186 sp<Track> track = mTracks[i];
3187 track->invalidate();
3188 }
Andy Hungdae27702016-10-31 14:01:16 -07003189 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3190 // After we exit there are no more track changes sent to BatteryNotifier
3191 // because that requires an active threadLoop.
3192 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3193 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003194 }
Eric Laurent81784c32012-11-19 14:55:58 -08003195}
3196
3197/*
3198The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003199 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003200 - mActiveSleepTimeUs from activeSleepTimeUs()
3201 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003202 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3203 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003204 - maxPeriod from frame count and sample rate (MIXER only)
3205
3206The parameters that affect these derived values are:
3207 - frame count
3208 - frame size
3209 - sample rate
3210 - device type: A2DP or not
3211 - device latency
3212 - format: PCM or not
3213 - active sleep time
3214 - idle sleep time
3215*/
3216
3217void AudioFlinger::PlaybackThread::cacheParameters_l()
3218{
Andy Hung25c2dac2014-02-27 14:56:00 -08003219 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003220 mActiveSleepTimeUs = activeSleepTimeUs();
3221 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003222
3223 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3224 // truncating audio when going to standby.
3225 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003226 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003227 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3228 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3229 }
3230 }
Eric Laurent81784c32012-11-19 14:55:58 -08003231}
3232
Eric Laurent13084622016-05-17 10:51:49 -07003233bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003234{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003235 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003236 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003237 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003238 size_t size = mTracks.size();
3239 for (size_t i = 0; i < size; i++) {
3240 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003241 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003242 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003243 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003244 }
3245 }
Eric Laurent13084622016-05-17 10:51:49 -07003246 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003247}
3248
Haynes Mathew George05317d22016-05-03 16:34:26 -07003249void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3250{
3251 Mutex::Autolock _l(mLock);
3252 invalidateTracks_l(streamType);
3253}
3254
Eric Laurent81784c32012-11-19 14:55:58 -08003255status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3256{
Glenn Kastend848eb42016-03-08 13:42:11 -08003257 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003258 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003259 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003260 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3261 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3262 &halInBuffer);
3263 if (result != OK) return result;
3264 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003265 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003266 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003267 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003268 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003269 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003270 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003271 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003272 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003273 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003274 &halInBuffer);
3275 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003276#ifdef FLOAT_EFFECT_CHAIN
3277 buffer = halInBuffer->audioBuffer()->f32;
3278#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003279 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003280#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003281 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3282 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003283 }
3284
3285 // Attach all tracks with same session ID to this chain.
3286 for (size_t i = 0; i < mTracks.size(); ++i) {
3287 sp<Track> track = mTracks[i];
3288 if (session == track->sessionId()) {
3289 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3290 buffer);
3291 track->setMainBuffer(buffer);
3292 chain->incTrackCnt();
3293 }
3294 }
3295
3296 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003297 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003298 if (session == track->sessionId()) {
3299 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3300 chain->incActiveTrackCnt();
3301 }
3302 }
3303 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003304 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003305 chain->setInBuffer(halInBuffer);
3306 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003307 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3308 // chains list in order to be processed last as it contains output device effects.
3309 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3310 // processing effects specific to an output stream before effects applied to all streams
3311 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003312 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3313 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003314 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003315 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003316 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003317 // Effect chain for other sessions are inserted at beginning of effect
3318 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003319 // sessions is not important.
3320 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003321 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3322 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003323 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003324 size_t size = mEffectChains.size();
3325 size_t i = 0;
3326 for (i = 0; i < size; i++) {
3327 if (mEffectChains[i]->sessionId() < session) {
3328 break;
3329 }
3330 }
3331 mEffectChains.insertAt(chain, i);
3332 checkSuspendOnAddEffectChain_l(chain);
3333
3334 return NO_ERROR;
3335}
3336
3337size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3338{
Glenn Kastend848eb42016-03-08 13:42:11 -08003339 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003340
3341 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3342
3343 for (size_t i = 0; i < mEffectChains.size(); i++) {
3344 if (chain == mEffectChains[i]) {
3345 mEffectChains.removeAt(i);
3346 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003347 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003348 if (session == track->sessionId()) {
3349 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3350 chain.get(), session);
3351 chain->decActiveTrackCnt();
3352 }
3353 }
3354
3355 // detach all tracks with same session ID from this chain
3356 for (size_t i = 0; i < mTracks.size(); ++i) {
3357 sp<Track> track = mTracks[i];
3358 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003359 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003360 chain->decTrackCnt();
3361 }
3362 }
3363 break;
3364 }
3365 }
3366 return mEffectChains.size();
3367}
3368
3369status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003370 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003371{
3372 Mutex::Autolock _l(mLock);
3373 return attachAuxEffect_l(track, EffectId);
3374}
3375
3376status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003377 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003378{
3379 status_t status = NO_ERROR;
3380
3381 if (EffectId == 0) {
3382 track->setAuxBuffer(0, NULL);
3383 } else {
3384 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3385 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3386 if (effect != 0) {
3387 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3388 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3389 } else {
3390 status = INVALID_OPERATION;
3391 }
3392 } else {
3393 status = BAD_VALUE;
3394 }
3395 }
3396 return status;
3397}
3398
3399void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3400{
3401 for (size_t i = 0; i < mTracks.size(); ++i) {
3402 sp<Track> track = mTracks[i];
3403 if (track->auxEffectId() == effectId) {
3404 attachAuxEffect_l(track, 0);
3405 }
3406 }
3407}
3408
3409bool AudioFlinger::PlaybackThread::threadLoop()
3410{
Glenn Kasten388d5712017-04-07 14:38:41 -07003411 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003412
Eric Laurent81784c32012-11-19 14:55:58 -08003413 Vector< sp<Track> > tracksToRemove;
3414
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003415 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003416 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
3417 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003418
3419 // MIXER
3420 nsecs_t lastWarning = 0;
3421
3422 // DUPLICATING
3423 // FIXME could this be made local to while loop?
3424 writeFrames = 0;
3425
3426 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003427 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003428
3429 if (mType == MIXER) {
3430 sleepTimeShift = 0;
3431 }
3432
3433 CpuStats cpuStats;
3434 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3435
3436 acquireWakeLock();
3437
Glenn Kasteneef598c2017-04-03 14:41:13 -07003438 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3439 // thread associated with this PlaybackThread.
3440 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3441 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003442 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3443 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003444 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003445 const char *logString = NULL;
3446
rago1bb90822017-05-02 18:31:48 -07003447 // Estimated time for next buffer to be written to hal. This is used only on
3448 // suspended mode (for now) to help schedule the wait time until next iteration.
3449 nsecs_t timeLoopNextNs = 0;
3450
Eric Laurent664539d2013-09-23 18:24:31 -07003451 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003452
Andy Hungf3234512018-07-03 14:51:47 -07003453 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3454 // TODO: add confirmation checks:
3455 // 1) DIRECT threads and linear PCM format really resets to 0?
3456 // 2) Is frame count really valid if not linear pcm?
3457 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3458 if (mType == OFFLOAD || mType == DIRECT) {
3459 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3460 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003461 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003462
Andy Hung446f4df2019-02-21 12:26:41 -08003463 // loopCount is used for statistics and diagnostics.
3464 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003465 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003466 // Log merge requests are performed during AudioFlinger binder transactions, but
3467 // that does not cover audio playback. It's requested here for that reason.
3468 mAudioFlinger->requestLogMerge();
3469
Eric Laurent81784c32012-11-19 14:55:58 -08003470 cpuStats.sample(myName);
3471
3472 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003473 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003474 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003475
Andy Hung2dbffc22018-08-08 18:50:41 -07003476 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3477 //
jiabinc52b1ff2019-10-31 17:20:42 -07003478 // Note: we access outDeviceTypes() outside of mLock.
3479 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003480 // Here, we try for the AF lock, but do not block on it as the latency
3481 // is more informational.
3482 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3483 std::vector<PatchPanel::SoftwarePatch> swPatches;
3484 double latencyMs;
3485 status_t status = INVALID_OPERATION;
3486 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3487 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3488 && swPatches.size() > 0) {
3489 status = swPatches[0].getLatencyMs_l(&latencyMs);
3490 downstreamPatchHandle = swPatches[0].getPatchHandle();
3491 }
3492 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003493 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003494 lastDownstreamPatchHandle = downstreamPatchHandle;
3495 }
3496 if (status == OK) {
3497 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003498 // latency of 5 seconds).
3499 const double minLatency = 0., maxLatency = 5000.;
3500 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003501 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003502 } else {
3503 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003504 if (latencyMs < minLatency) latencyMs = minLatency;
3505 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003506 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003507 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003508 }
3509 mAudioFlinger->mLock.unlock();
3510 }
3511 } else {
3512 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3513 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003514 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003515 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3516 }
3517 }
3518
Eric Laurent81784c32012-11-19 14:55:58 -08003519 { // scope for mLock
3520
3521 Mutex::Autolock _l(mLock);
3522
Eric Laurent021cf962014-05-13 10:18:14 -07003523 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003524
Glenn Kasteneef598c2017-04-03 14:41:13 -07003525 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003526 if (logString != NULL) {
3527 mNBLogWriter->logTimestamp();
3528 mNBLogWriter->log(logString);
3529 logString = NULL;
3530 }
3531
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003532 // Collect timestamp statistics for the Playback Thread types that support it.
3533 if (mType == MIXER
3534 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003535 || mType == DIRECT
3536 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003537 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003538 // and associate with the sink frames written out. We need
3539 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003540 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003541 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003542 if (mStandby) {
3543 mTimestampVerifier.discontinuity();
3544 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3545 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3546 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3547 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003548
3549 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003550 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
Andy Hungc8fddf32018-08-08 18:32:37 -07003551 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3552 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3553 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3554 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3555 = correctedTimestamp.mFrames;
3556 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3557 = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10003558 ALOGVV("TS_AFTER: %d %lld %lld", id(),
Andy Hungc8fddf32018-08-08 18:32:37 -07003559 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3560 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003561
3562 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003563 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003564 const int64_t newPosition =
3565 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003566 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003567 // prevent retrograde
3568 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3569 newPosition,
3570 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3571 - mSuspendedFrames));
3572 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003573 }
3574
Andy Hung818e7a32016-02-16 18:08:07 -08003575 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003576 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003577
3578 // We keep track of the last valid kernel position in case we are in underrun
3579 // and the normal mixer period is the same as the fast mixer period, or there
3580 // is some error from the HAL.
3581 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3582 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3583 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3584 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3585 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3586
3587 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3588 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3589 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3590 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003591 }
3592
3593 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3594 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003595 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003596 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003597 }
3598
Andy Hung818e7a32016-02-16 18:08:07 -08003599 // copy over kernel info
3600 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003601 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3602 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003603 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3604 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003605 } else {
3606 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003607 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003608
Andy Hungc54b1ff2016-02-23 14:07:07 -08003609 // mFramesWritten for non-offloaded tracks are contiguous
3610 // even after standby() is called. This is useful for the track frame
3611 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003612 bool serverLocationUpdate = false;
3613 if (mFramesWritten != lastFramesWritten) {
3614 serverLocationUpdate = true;
3615 lastFramesWritten = mFramesWritten;
3616 }
3617 // Only update timestamps if there is a meaningful change.
3618 // Either the kernel timestamp must be valid or we have written something.
3619 if (kernelLocationUpdate || serverLocationUpdate) {
3620 if (serverLocationUpdate) {
3621 // use the time before we called the HAL write - it is a bit more accurate
3622 // to when the server last read data than the current time here.
3623 //
Andy Hung446f4df2019-02-21 12:26:41 -08003624 // If we haven't written anything, mLastIoBeginNs will be -1
Andy Hung69488c42016-05-16 18:43:33 -07003625 // and we use systemTime().
3626 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
Andy Hung446f4df2019-02-21 12:26:41 -08003627 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
3628 ? systemTime() : mLastIoBeginNs;
Andy Hung69488c42016-05-16 18:43:33 -07003629 }
Andy Hungdae27702016-10-31 14:01:16 -07003630
3631 for (const sp<Track> &t : mActiveTracks) {
3632 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003633 t->updateTrackFrameInfo(
3634 t->mAudioTrackServerProxy->framesReleased(),
3635 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003636 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003637 mTimestamp);
3638 }
Andy Hunge10393e2015-06-12 13:59:33 -07003639 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003640 }
Andy Hunge6c37112019-02-26 17:38:10 -08003641
3642 if (audio_has_proportional_frames(mFormat)) {
3643 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
3644 if (latencyMs != 0.) { // note 0. means timestamp is empty.
3645 mLatencyMs.add(latencyMs);
3646 }
3647 }
3648
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003649 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003650#if 0
3651 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003652 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003653 timespec ts;
3654 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003655 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003656 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003657 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003658 }
3659 ++z;
3660#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003661 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003662 if (mSignalPending) {
3663 // A signal was raised while we were unlocked
3664 mSignalPending = false;
3665 } else if (waitingAsyncCallback_l()) {
3666 if (exitPending()) {
3667 break;
3668 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003669 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003670 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003671 releaseWakeLock_l();
3672 released = true;
3673 }
Andy Hung10cbff12017-02-21 17:30:14 -08003674
3675 const int64_t waitNs = computeWaitTimeNs_l();
3676 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3677 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3678 if (status == TIMED_OUT) {
3679 mSignalPending = true; // if timeout recheck everything
3680 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003682 if (released) {
3683 acquireWakeLock_l();
3684 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003685 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3686 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003687
3688 continue;
3689 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003690 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003691 isSuspended()) {
3692 // put audio hardware into standby after short delay
3693 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003694
3695 threadLoop_standby();
3696
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003697 // This is where we go into standby
3698 if (!mStandby) {
3699 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003700 mThreadMetrics.logEndInterval();
3701 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003702 }
Andy Hungd0979812019-02-21 15:51:44 -08003703 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003704 }
3705
Eric Tan39ec8d62018-07-24 09:49:29 -07003706 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003707 // we're about to wait, flush the binder command buffer
3708 IPCThreadState::self()->flushCommands();
3709
3710 clearOutputTracks();
3711
3712 if (exitPending()) {
3713 break;
3714 }
3715
3716 releaseWakeLock_l();
3717 // wait until we have something to do...
3718 ALOGV("%s going to sleep", myName.string());
3719 mWaitWorkCV.wait(mLock);
3720 ALOGV("%s waking up", myName.string());
3721 acquireWakeLock_l();
3722
3723 mMixerStatus = MIXER_IDLE;
3724 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3725 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003726 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003727 checkSilentMode_l();
3728
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003729 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3730 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003731 if (mType == MIXER) {
3732 sleepTimeShift = 0;
3733 }
3734
3735 continue;
3736 }
3737 }
Eric Laurent81784c32012-11-19 14:55:58 -08003738 // mMixerStatusIgnoringFastTracks is also updated internally
3739 mMixerStatus = prepareTracks_l(&tracksToRemove);
3740
Andy Hungdae27702016-10-31 14:01:16 -07003741 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003742
Kevin Rocard069c2712018-03-29 19:09:14 -07003743 updateMetadata_l();
3744
Eric Laurent81784c32012-11-19 14:55:58 -08003745 // prevent any changes in effect chain list and in each effect chain
3746 // during mixing and effect process as the audio buffers could be deleted
3747 // or modified if an effect is created or deleted
3748 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003749
3750 // Determine which session to pick up haptic data.
3751 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003752 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003753 // TODO: Write haptic data directly to sink buffer when mixing.
3754 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3755 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003756 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3757 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3758 activeHapticSessionId = track->sessionId();
3759 break;
3760 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003761 if (track->getHapticPlaybackEnabled()) {
3762 activeHapticSessionId = track->sessionId();
3763 break;
3764 }
3765 }
3766 }
3767
Andy Hungc1646382019-04-30 16:12:10 -07003768 // Acquire a local copy of active tracks with lock (release w/o lock).
3769 //
3770 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3771 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3772 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3773 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003774 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003775
Eric Laurentbfb1b832013-01-07 09:53:42 -08003776 if (mBytesRemaining == 0) {
3777 mCurrentWriteLength = 0;
3778 if (mMixerStatus == MIXER_TRACKS_READY) {
3779 // threadLoop_mix() sets mCurrentWriteLength
3780 threadLoop_mix();
3781 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3782 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003783 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003784 // must be written to HAL
3785 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003786 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003787 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003788
3789 // Tally underrun frames as we are inserting 0s here.
3790 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003791 if (track->mFillingUpStatus == Track::FS_ACTIVE
3792 && !track->isStopped()
3793 && !track->isPaused()
3794 && !track->isTerminated()) {
3795 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3796 __func__, track->id(), track->getTrackStateAsString(),
3797 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003798 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3799 }
3800 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003801 }
3802 }
Andy Hung98ef9782014-03-04 14:46:50 -08003803 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003804 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003805 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3806 // or mSinkBuffer (if there are no effects).
3807 //
3808 // This is done pre-effects computation; if effects change to
3809 // support higher precision, this needs to move.
3810 //
3811 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003812 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003813 if (mMixerBufferValid) {
3814 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3815 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3816
Andy Hung2ddee192015-12-18 17:34:44 -08003817 // mono blend occurs for mixer threads only (not direct or offloaded)
3818 // and is handled here if we're going directly to the sink.
3819 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003820 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3821 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003822 }
3823
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003824 if (!hasFastMixer()) {
3825 // Balance must take effect after mono conversion.
3826 // We do it here if there is no FastMixer.
3827 // mBalance detects zero balance within the class for speed (not needed here).
3828 mBalance.setBalance(mMasterBalance.load());
3829 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3830 }
3831
Andy Hung98ef9782014-03-04 14:46:50 -08003832 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003833 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3834
3835 // If we're going directly to the sink and there are haptic channels,
3836 // we should adjust channels as the sample data is partially interleaved
3837 // in this case.
3838 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3839 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3840 mChannelCount + mHapticChannelCount,
3841 audio_bytes_per_sample(format),
3842 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3843 }
Andy Hung98ef9782014-03-04 14:46:50 -08003844 }
3845
Eric Laurentbfb1b832013-01-07 09:53:42 -08003846 mBytesRemaining = mCurrentWriteLength;
3847 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003848 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3849 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3850 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3851 mBytesWritten += mBytesRemaining;
3852 mFramesWritten += framesRemaining;
3853 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003854 mBytesRemaining = 0;
3855 }
Eric Laurent81784c32012-11-19 14:55:58 -08003856
Eric Laurentbfb1b832013-01-07 09:53:42 -08003857 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003858 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003859 for (size_t i = 0; i < effectChains.size(); i ++) {
3860 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003861 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003862 if (activeHapticSessionId != AUDIO_SESSION_NONE
3863 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003864 // Haptic data is active in this case, copy it directly from
3865 // in buffer to out buffer.
3866 const size_t audioBufferSize = mNormalFrameCount
3867 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3868 memcpy_by_audio_format(
3869 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3870 EFFECT_BUFFER_FORMAT,
3871 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3872 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3873 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003874 }
Eric Laurent81784c32012-11-19 14:55:58 -08003875 }
3876 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003877 // Process effect chains for offloaded thread even if no audio
3878 // was read from audio track: process only updates effect state
3879 // and thus does have to be synchronized with audio writes but may have
3880 // to be called while waiting for async write callback
3881 if (mType == OFFLOAD) {
3882 for (size_t i = 0; i < effectChains.size(); i ++) {
3883 effectChains[i]->process_l();
3884 }
3885 }
Eric Laurent81784c32012-11-19 14:55:58 -08003886
Andy Hung98ef9782014-03-04 14:46:50 -08003887 // Only if the Effects buffer is enabled and there is data in the
3888 // Effects buffer (buffer valid), we need to
3889 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003890 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003891 if (mEffectBufferValid) {
3892 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003893
3894 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003895 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3896 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003897 }
3898
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003899 if (!hasFastMixer()) {
3900 // Balance must take effect after mono conversion.
3901 // We do it here if there is no FastMixer.
3902 // mBalance detects zero balance within the class for speed (not needed here).
3903 mBalance.setBalance(mMasterBalance.load());
3904 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3905 }
3906
Andy Hung98ef9782014-03-04 14:46:50 -08003907 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003908 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3909 // The sample data is partially interleaved when haptic channels exist,
3910 // we need to adjust channels here.
3911 if (mHapticChannelCount > 0) {
3912 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3913 mChannelCount + mHapticChannelCount,
3914 audio_bytes_per_sample(mFormat),
3915 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3916 }
Andy Hung98ef9782014-03-04 14:46:50 -08003917 }
3918
Eric Laurent81784c32012-11-19 14:55:58 -08003919 // enable changes in effect chain
3920 unlockEffectChains(effectChains);
3921
Eric Laurentbfb1b832013-01-07 09:53:42 -08003922 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003923 // mSleepTimeUs == 0 means we must write to audio hardware
3924 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003925 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003926 // writePeriodNs is updated >= 0 when ret > 0.
3927 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003928 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003929 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003930 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003931 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003932 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003933 if (ret < 0) {
3934 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003935 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003936 mBytesWritten += ret;
3937 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003938 const int64_t frames = ret / mFrameSize;
3939 mFramesWritten += frames;
3940
3941 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3942 // process information relating to write time.
3943 if (audio_has_proportional_frames(mFormat)) {
3944 // we are in a continuous mixing cycle
3945 if (mMixerStatus == MIXER_TRACKS_READY &&
3946 loopCount == lastLoopCountWritten + 1) {
3947
3948 const double jitterMs =
3949 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3950 {frames, writePeriodNs},
3951 {0, 0} /* lastTimestamp */, mSampleRate);
3952 const double processMs =
3953 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3954
3955 Mutex::Autolock _l(mLock);
3956 mIoJitterMs.add(jitterMs);
3957 mProcessTimeMs.add(processMs);
3958 }
3959
3960 // write blocked detection
3961 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3962 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3963 mNumDelayedWrites++;
3964 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3965 ATRACE_NAME("underrun");
3966 ALOGW("write blocked for %lld msecs, "
3967 "%d delayed writes, thread %d",
3968 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3969 mNumDelayedWrites, mId);
3970 lastWarning = lastIoEndNs;
3971 }
3972 }
3973 }
3974 // update timing info.
3975 mLastIoBeginNs = lastIoBeginNs;
3976 mLastIoEndNs = lastIoEndNs;
3977 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003978 }
3979 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3980 (mMixerStatus == MIXER_DRAIN_ALL)) {
3981 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003982 }
Andy Hung08fb1742015-05-31 23:22:10 -07003983 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003984
3985 if (mThreadThrottle
3986 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003987 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003988 // Limit MixerThread data processing to no more than twice the
3989 // expected processing rate.
3990 //
3991 // This helps prevent underruns with NuPlayer and other applications
3992 // which may set up buffers that are close to the minimum size, or use
3993 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3994 //
3995 // The throttle smooths out sudden large data drains from the device,
3996 // e.g. when it comes out of standby, which often causes problems with
3997 // (1) mixer threads without a fast mixer (which has its own warm-up)
3998 // (2) minimum buffer sized tracks (even if the track is full,
3999 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004000 //
4001 // Total time spent in last processing cycle equals time spent in
4002 // 1. threadLoop_write, as well as time spent in
4003 // 2. threadLoop_mix (significant for heavy mixing, especially
4004 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004005
Andy Hung446f4df2019-02-21 12:26:41 -08004006 // it's OK if deltaMs is an overestimate.
4007
4008 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004009
Ivan Lozanoea04d392017-11-07 14:37:07 -08004010 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004011 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004012 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004013
Andy Hung08fb1742015-05-31 23:22:10 -07004014 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004015 // notify of throttle start on verbose log
4016 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4017 "mixer(%p) throttle begin:"
4018 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004019 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004020 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004021 // Throttle must be attributed to the previous mixer loop's write time
4022 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004023 // This also ensures proper timing statistics.
4024 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004025 } else {
4026 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4027 if (diff > 0) {
4028 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004029 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004030 ALOGD_IF(!isSingleDeviceType(
4031 outDeviceTypes(), audio_is_a2dp_out_device) &&
4032 !isSingleDeviceType(
4033 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004034 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004035 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4036 }
Andy Hung08fb1742015-05-31 23:22:10 -07004037 }
4038 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004039 }
Eric Laurent81784c32012-11-19 14:55:58 -08004040
Eric Laurentbfb1b832013-01-07 09:53:42 -08004041 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004042 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004043 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004044 // suspended requires accurate metering of sleep time.
4045 if (isSuspended()) {
4046 // advance by expected sleepTime
4047 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4048 const nsecs_t nowNs = systemTime();
4049
4050 // compute expected next time vs current time.
4051 // (negative deltas are treated as delays).
4052 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4053 if (deltaNs < -kMaxNextBufferDelayNs) {
4054 // Delays longer than the max allowed trigger a reset.
4055 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4056 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4057 timeLoopNextNs = nowNs + deltaNs;
4058 } else if (deltaNs < 0) {
4059 // Delays within the max delay allowed: zero the delta/sleepTime
4060 // to help the system catch up in the next iteration(s)
4061 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4062 deltaNs = 0;
4063 }
4064 // update sleep time (which is >= 0)
4065 mSleepTimeUs = deltaNs / 1000;
4066 }
Eric Laurente93cc032016-05-05 10:15:10 -07004067 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4068 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004069 }
Glenn Kastene7754022014-10-31 12:11:26 -07004070 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004071 }
Eric Laurent81784c32012-11-19 14:55:58 -08004072 }
4073
4074 // Finally let go of removed track(s), without the lock held
4075 // since we can't guarantee the destructors won't acquire that
4076 // same lock. This will also mutate and push a new fast mixer state.
4077 threadLoop_removeTracks(tracksToRemove);
4078 tracksToRemove.clear();
4079
4080 // FIXME I don't understand the need for this here;
4081 // it was in the original code but maybe the
4082 // assignment in saveOutputTracks() makes this unnecessary?
4083 clearOutputTracks();
4084
4085 // Effect chains will be actually deleted here if they were removed from
4086 // mEffectChains list during mixing or effects processing
4087 effectChains.clear();
4088
4089 // FIXME Note that the above .clear() is no longer necessary since effectChains
4090 // is now local to this block, but will keep it for now (at least until merge done).
4091 }
4092
Eric Laurentbfb1b832013-01-07 09:53:42 -08004093 threadLoop_exit();
4094
Eric Laurentcf817a22014-08-04 20:36:31 -07004095 if (!mStandby) {
4096 threadLoop_standby();
4097 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004098 }
4099
4100 releaseWakeLock();
4101
4102 ALOGV("Thread %p type %d exiting", this, mType);
4103 return false;
4104}
4105
Eric Laurentbfb1b832013-01-07 09:53:42 -08004106// removeTracks_l() must be called with ThreadBase::mLock held
4107void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4108{
Andy Hungfe726a62018-09-27 15:17:25 -07004109 for (const auto& track : tracksToRemove) {
4110 mActiveTracks.remove(track);
4111 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4112 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4113 if (chain != 0) {
4114 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4115 __func__, track->id(), chain.get(), track->sessionId());
4116 chain->decActiveTrackCnt();
4117 }
4118 // If an external client track, inform APM we're no longer active, and remove if needed.
4119 // We do this under lock so that the state is consistent if the Track is destroyed.
4120 if (track->isExternalTrack()) {
4121 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004122 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004123 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004124 }
4125 }
Andy Hungfe726a62018-09-27 15:17:25 -07004126 if (track->isTerminated()) {
4127 // remove from our tracks vector
4128 removeTrack_l(track);
4129 }
jiabineb3bda02020-06-30 14:07:03 -07004130 if (mHapticChannelCount > 0 &&
4131 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4132 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004133 mLock.unlock();
4134 // Unlock due to VibratorService will lock for this call and will
4135 // call Tracks.mute/unmute which also require thread's lock.
4136 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4137 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004138
4139 // When the track is stop, set the haptic intensity as MUTE
4140 // for the HapticGenerator effect.
4141 if (chain != nullptr) {
4142 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4143 }
jiabin245cdd92018-12-07 17:55:15 -08004144 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004145 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004146}
Eric Laurent81784c32012-11-19 14:55:58 -08004147
Eric Laurentaccc1472013-09-20 09:36:34 -07004148status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4149{
4150 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004151 ExtendedTimestamp ets;
4152 status_t status = mNormalSink->getTimestamp(ets);
4153 if (status == NO_ERROR) {
4154 status = ets.getBestTimestamp(&timestamp);
4155 }
4156 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004157 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004158 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07004159 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004160 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07004161 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11004162 if (mDownstreamLatencyStatMs.getN() > 0) {
4163 const uint32_t positionOffset =
4164 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4165 if (positionOffset > timestamp.mPosition) {
4166 timestamp.mPosition = 0;
4167 } else {
4168 timestamp.mPosition -= positionOffset;
4169 }
4170 }
Eric Laurentaccc1472013-09-20 09:36:34 -07004171 return NO_ERROR;
4172 }
4173 }
4174 return INVALID_OPERATION;
4175}
Eric Laurent1c333e22014-05-20 10:48:17 -07004176
Eric Laurenteab90452019-06-24 15:17:46 -07004177// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4178// still applied by the mixer.
4179// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4180// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4181// if more than one track are active
4182status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4183{
4184 status_t result = NO_ERROR;
4185 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4186 if (*volume != mLeftVolFloat) {
4187 result = mOutput->stream->setVolume(*volume, *volume);
4188 ALOGE_IF(result != OK,
4189 "Error when setting output stream volume: %d", result);
4190 if (result == NO_ERROR) {
4191 mLeftVolFloat = *volume;
4192 }
4193 }
4194 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4195 // remove stream volume contribution from software volume.
4196 if (mLeftVolFloat == *volume) {
4197 *volume = 1.0f;
4198 }
4199 }
4200 return result;
4201}
4202
Eric Laurent054d9d32015-04-24 08:48:48 -07004203status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4204 audio_patch_handle_t *handle)
4205{
Andy Hungf60abce2016-08-26 11:37:54 -07004206 status_t status;
4207 if (property_get_bool("af.patch_park", false /* default_value */)) {
4208 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4209 // or if HAL does not properly lock against access.
4210 AutoPark<FastMixer> park(mFastMixer);
4211 status = PlaybackThread::createAudioPatch_l(patch, handle);
4212 } else {
4213 status = PlaybackThread::createAudioPatch_l(patch, handle);
4214 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004215 return status;
4216}
4217
Eric Laurent1c333e22014-05-20 10:48:17 -07004218status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4219 audio_patch_handle_t *handle)
4220{
4221 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004222
4223 // store new device and send to effects
4224 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004225 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004226 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004227 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4228 && !mOutput->audioHwDev->supportsAudioPatches(),
4229 "Enumerated device type(%#x) must not be used "
4230 "as it does not support audio patches",
4231 patch->sinks[i].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004232 type |= patch->sinks[i].ext.device.type;
jiabinc52b1ff2019-10-31 17:20:42 -07004233 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4234 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004235 }
4236
François Gaffie0c280aa2018-07-25 10:02:15 +02004237 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004238#ifdef ADD_BATTERY_DATA
4239 // when changing the audio output device, call addBatteryData to notify
4240 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004241 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004242 uint32_t params = 0;
4243 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004244 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004245 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004246 }
4247
Eric Laurent054d9d32015-04-24 08:48:48 -07004248 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004249 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004250 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4251 }
4252
4253 if (params != 0) {
4254 addBatteryData(params);
4255 }
4256 }
4257#endif
4258
4259 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004260 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004261 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004262
jiabinc52b1ff2019-10-31 17:20:42 -07004263 // mPatch.num_sinks is not set when the thread is created so that
4264 // the first patch creation triggers an ioConfigChanged callback
4265 bool configChanged = (mPatch.num_sinks == 0) ||
4266 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004267 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004268 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004269 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004270
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004271 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004272 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4273 status = hwDevice->createAudioPatch(patch->num_sources,
4274 patch->sources,
4275 patch->num_sinks,
4276 patch->sinks,
4277 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004278 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004279 char *address;
4280 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4281 //FIXME: we only support address on first sink with HAL version < 3.0
4282 address = audio_device_address_to_parameter(
4283 patch->sinks[0].ext.device.type,
4284 patch->sinks[0].ext.device.address);
4285 } else {
4286 address = (char *)calloc(1, 1);
4287 }
4288 AudioParameter param = AudioParameter(String8(address));
4289 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004290 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004291 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004292 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004293 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004294 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004295
4296 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004297 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004298 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004299 // also dispatch to active AudioTracks for MediaMetrics
4300 for (const auto &track : mActiveTracks) {
4301 track->logEndInterval();
4302 track->logBeginInterval(patchSinksAsString);
4303 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004304
Eric Laurente8726fe2015-06-26 09:39:24 -07004305 if (configChanged) {
4306 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4307 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004308 return status;
4309}
4310
Eric Laurent054d9d32015-04-24 08:48:48 -07004311status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4312{
Andy Hungf60abce2016-08-26 11:37:54 -07004313 status_t status;
4314 if (property_get_bool("af.patch_park", false /* default_value */)) {
4315 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4316 // or if HAL does not properly lock against access.
4317 AutoPark<FastMixer> park(mFastMixer);
4318 status = PlaybackThread::releaseAudioPatch_l(handle);
4319 } else {
4320 status = PlaybackThread::releaseAudioPatch_l(handle);
4321 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004322 return status;
4323}
4324
Eric Laurent1c333e22014-05-20 10:48:17 -07004325status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4326{
4327 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004328
jiabinc52b1ff2019-10-31 17:20:42 -07004329 mPatch = audio_patch{};
4330 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004331
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004332 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004333 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4334 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004335 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004336 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004337 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004338 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004339 }
4340 return status;
4341}
4342
Eric Laurent83b88082014-06-20 18:31:16 -07004343void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4344{
4345 Mutex::Autolock _l(mLock);
4346 mTracks.add(track);
4347}
4348
4349void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4350{
4351 Mutex::Autolock _l(mLock);
4352 destroyTrack_l(track);
4353}
4354
Mikhail Naganovdc769682018-05-04 15:34:08 -07004355void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004356{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004357 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004358 config->role = AUDIO_PORT_ROLE_SOURCE;
4359 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4360 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004361 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4362 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4363 config->flags.output = mOutput->flags;
4364 }
Eric Laurent83b88082014-06-20 18:31:16 -07004365}
4366
Eric Laurent81784c32012-11-19 14:55:58 -08004367// ----------------------------------------------------------------------------
4368
4369AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004370 audio_io_handle_t id, bool systemReady, type_t type)
4371 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004372 // mAudioMixer below
4373 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004374 mFastMixerFutex(0),
4375 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004376 // mOutputSink below
4377 // mPipeSink below
4378 // mNormalSink below
4379{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004380 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004381 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004382 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004383 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004384 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4385 mNormalFrameCount);
4386 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4387
Andy Hungfbfc3952015-01-15 13:33:51 -08004388 if (type == DUPLICATING) {
4389 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4390 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4391 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4392 return;
4393 }
Eric Laurent81784c32012-11-19 14:55:58 -08004394 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004395 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004396 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004397 const NBAIO_Format offers[1] = {Format_from_SR_C(
4398 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004399#if !LOG_NDEBUG
4400 ssize_t index =
4401#else
4402 (void)
4403#endif
4404 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004405 ALOG_ASSERT(index == 0);
4406
4407 // initialize fast mixer depending on configuration
4408 bool initFastMixer;
4409 switch (kUseFastMixer) {
4410 case FastMixer_Never:
4411 initFastMixer = false;
4412 break;
4413 case FastMixer_Always:
4414 initFastMixer = true;
4415 break;
4416 case FastMixer_Static:
4417 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004418 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4419 // where the period is less than an experimentally determined threshold that can be
4420 // scheduled reliably with CFS. However, the BT A2DP HAL is
4421 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4422 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004423 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004424 break;
4425 }
Andy Hungfda69402017-02-15 14:33:12 -08004426 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4427 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4428 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004429 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004430 audio_format_t fastMixerFormat;
4431 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4432 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4433 } else {
4434 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4435 }
4436 if (mFormat != fastMixerFormat) {
4437 // change our Sink format to accept our intermediate precision
4438 mFormat = fastMixerFormat;
4439 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004440 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004441 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4442 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4443 }
Eric Laurent81784c32012-11-19 14:55:58 -08004444
4445 // create a MonoPipe to connect our submix to FastMixer
4446 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004447
Andy Hung1258c1a2014-05-23 21:22:17 -07004448 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004449 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004450 format.mFormat = fastMixerFormat;
4451 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4452
Eric Laurent81784c32012-11-19 14:55:58 -08004453 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4454 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4455 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4456 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4457 const NBAIO_Format offers[1] = {format};
4458 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004459#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004460 ssize_t index =
4461#else
4462 (void)
4463#endif
4464 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004465 ALOG_ASSERT(index == 0);
4466 monoPipe->setAvgFrames((mScreenState & 1) ?
4467 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4468 mPipeSink = monoPipe;
4469
Eric Laurent81784c32012-11-19 14:55:58 -08004470 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004471 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004472 FastMixerStateQueue *sq = mFastMixer->sq();
4473#ifdef STATE_QUEUE_DUMP
4474 sq->setObserverDump(&mStateQueueObserverDump);
4475 sq->setMutatorDump(&mStateQueueMutatorDump);
4476#endif
4477 FastMixerState *state = sq->begin();
4478 FastTrack *fastTrack = &state->mFastTracks[0];
4479 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4480 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4481 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004482 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4483 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004484 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004485 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004486 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004487 fastTrack->mGeneration++;
4488 state->mFastTracksGen++;
4489 state->mTrackMask = 1;
4490 // fast mixer will use the HAL output sink
4491 state->mOutputSink = mOutputSink.get();
4492 state->mOutputSinkGen++;
4493 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004494 // specify sink channel mask when haptic channel mask present as it can not
4495 // be calculated directly from channel count
4496 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4497 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004498 state->mCommand = FastMixerState::COLD_IDLE;
4499 // already done in constructor initialization list
4500 //mFastMixerFutex = 0;
4501 state->mColdFutexAddr = &mFastMixerFutex;
4502 state->mColdGen++;
4503 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004504 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4505 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004506 sq->end();
4507 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4508
Eric Tan0513b5d2018-09-17 10:32:48 -07004509 NBLog::thread_info_t info;
4510 info.id = mId;
4511 info.type = NBLog::FASTMIXER;
4512 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4513
Eric Laurent81784c32012-11-19 14:55:58 -08004514 // start the fast mixer
4515 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4516 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004517 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004518 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004519
4520#ifdef AUDIO_WATCHDOG
4521 // create and start the watchdog
4522 mAudioWatchdog = new AudioWatchdog();
4523 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4524 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4525 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004526 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004527#endif
Andy Hung8946a282018-04-19 20:04:56 -07004528 } else {
4529#ifdef TEE_SINK
4530 // Only use the MixerThread tee if there is no FastMixer.
4531 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4532 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4533#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004534 }
4535
4536 switch (kUseFastMixer) {
4537 case FastMixer_Never:
4538 case FastMixer_Dynamic:
4539 mNormalSink = mOutputSink;
4540 break;
4541 case FastMixer_Always:
4542 mNormalSink = mPipeSink;
4543 break;
4544 case FastMixer_Static:
4545 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4546 break;
4547 }
4548}
4549
4550AudioFlinger::MixerThread::~MixerThread()
4551{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004552 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004553 FastMixerStateQueue *sq = mFastMixer->sq();
4554 FastMixerState *state = sq->begin();
4555 if (state->mCommand == FastMixerState::COLD_IDLE) {
4556 int32_t old = android_atomic_inc(&mFastMixerFutex);
4557 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004558 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004559 }
4560 }
4561 state->mCommand = FastMixerState::EXIT;
4562 sq->end();
4563 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4564 mFastMixer->join();
4565 // Though the fast mixer thread has exited, it's state queue is still valid.
4566 // We'll use that extract the final state which contains one remaining fast track
4567 // corresponding to our sub-mix.
4568 state = sq->begin();
4569 ALOG_ASSERT(state->mTrackMask == 1);
4570 FastTrack *fastTrack = &state->mFastTracks[0];
4571 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4572 delete fastTrack->mBufferProvider;
4573 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004574 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004575#ifdef AUDIO_WATCHDOG
4576 if (mAudioWatchdog != 0) {
4577 mAudioWatchdog->requestExit();
4578 mAudioWatchdog->requestExitAndWait();
4579 mAudioWatchdog.clear();
4580 }
4581#endif
4582 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004583 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004584 delete mAudioMixer;
4585}
4586
4587
4588uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4589{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004590 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004591 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4592 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4593 }
4594 return latency;
4595}
4596
Eric Laurentbfb1b832013-01-07 09:53:42 -08004597ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004598{
4599 // FIXME we should only do one push per cycle; confirm this is true
4600 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004601 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004602 FastMixerStateQueue *sq = mFastMixer->sq();
4603 FastMixerState *state = sq->begin();
4604 if (state->mCommand != FastMixerState::MIX_WRITE &&
4605 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4606 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004607
4608 // FIXME workaround for first HAL write being CPU bound on some devices
4609 ATRACE_BEGIN("write");
4610 mOutput->write((char *)mSinkBuffer, 0);
4611 ATRACE_END();
4612
Eric Laurent81784c32012-11-19 14:55:58 -08004613 int32_t old = android_atomic_inc(&mFastMixerFutex);
4614 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004615 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004616 }
4617#ifdef AUDIO_WATCHDOG
4618 if (mAudioWatchdog != 0) {
4619 mAudioWatchdog->resume();
4620 }
4621#endif
4622 }
4623 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004624#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004625 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004626 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004627#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004628 sq->end();
4629 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4630 if (kUseFastMixer == FastMixer_Dynamic) {
4631 mNormalSink = mPipeSink;
4632 }
4633 } else {
4634 sq->end(false /*didModify*/);
4635 }
4636 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004637 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004638}
4639
4640void AudioFlinger::MixerThread::threadLoop_standby()
4641{
4642 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004643 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004644 FastMixerStateQueue *sq = mFastMixer->sq();
4645 FastMixerState *state = sq->begin();
4646 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004647 // Report any frames trapped in the Monopipe
4648 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4649 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4650 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4651 "monoPipeWritten:%lld monoPipeLeft:%lld",
4652 (long long)mFramesWritten, (long long)mSuspendedFrames,
4653 (long long)mPipeSink->framesWritten(), pipeFrames);
4654 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4655
Eric Laurent81784c32012-11-19 14:55:58 -08004656 state->mCommand = FastMixerState::COLD_IDLE;
4657 state->mColdFutexAddr = &mFastMixerFutex;
4658 state->mColdGen++;
4659 mFastMixerFutex = 0;
4660 sq->end();
4661 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4662 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4663 if (kUseFastMixer == FastMixer_Dynamic) {
4664 mNormalSink = mOutputSink;
4665 }
4666#ifdef AUDIO_WATCHDOG
4667 if (mAudioWatchdog != 0) {
4668 mAudioWatchdog->pause();
4669 }
4670#endif
4671 } else {
4672 sq->end(false /*didModify*/);
4673 }
4674 }
4675 PlaybackThread::threadLoop_standby();
4676}
4677
Eric Laurentbfb1b832013-01-07 09:53:42 -08004678bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4679{
4680 return false;
4681}
4682
4683bool AudioFlinger::PlaybackThread::shouldStandby_l()
4684{
4685 return !mStandby;
4686}
4687
4688bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4689{
4690 Mutex::Autolock _l(mLock);
4691 return waitingAsyncCallback_l();
4692}
4693
Eric Laurent81784c32012-11-19 14:55:58 -08004694// shared by MIXER and DIRECT, overridden by DUPLICATING
4695void AudioFlinger::PlaybackThread::threadLoop_standby()
4696{
4697 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004698 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004699 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004700 // discard any pending drain or write ack by incrementing sequence
4701 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4702 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004703 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004704 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4705 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004706 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004707 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004708}
4709
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004710void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4711{
4712 ALOGV("signal playback thread");
4713 broadcast_l();
4714}
4715
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004716void AudioFlinger::PlaybackThread::onAsyncError()
4717{
4718 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4719 invalidateTracks((audio_stream_type_t)i);
4720 }
4721}
4722
Eric Laurent81784c32012-11-19 14:55:58 -08004723void AudioFlinger::MixerThread::threadLoop_mix()
4724{
Eric Laurent81784c32012-11-19 14:55:58 -08004725 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004726 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004727 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004728 // increase sleep time progressively when application underrun condition clears.
4729 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4730 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4731 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004732 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004733 sleepTimeShift--;
4734 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004735 mSleepTimeUs = 0;
4736 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004737 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004738
Eric Laurent81784c32012-11-19 14:55:58 -08004739}
4740
4741void AudioFlinger::MixerThread::threadLoop_sleepTime()
4742{
4743 // If no tracks are ready, sleep once for the duration of an output
4744 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004745 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004746 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004747 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4748 // Using the Monopipe availableToWrite, we estimate the
4749 // sleep time to retry for more data (before we underrun).
4750 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4751 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4752 const size_t pipeFrames = monoPipe->maxFrames();
4753 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4754 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4755 const size_t framesDelay = std::min(
4756 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4757 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4758 pipeFrames, framesLeft, framesDelay);
4759 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4760 } else {
4761 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4762 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4763 mSleepTimeUs = kMinThreadSleepTimeUs;
4764 }
4765 // reduce sleep time in case of consecutive application underruns to avoid
4766 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4767 // duration we would end up writing less data than needed by the audio HAL if
4768 // the condition persists.
4769 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4770 sleepTimeShift++;
4771 }
Eric Laurent81784c32012-11-19 14:55:58 -08004772 }
4773 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004774 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004775 }
4776 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004777 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4778 // before effects processing or output.
4779 if (mMixerBufferValid) {
4780 memset(mMixerBuffer, 0, mMixerBufferSize);
4781 } else {
4782 memset(mSinkBuffer, 0, mSinkBufferSize);
4783 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004784 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004785 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4786 "anticipated start");
4787 }
4788 // TODO add standby time extension fct of effect tail
4789}
4790
4791// prepareTracks_l() must be called with ThreadBase::mLock held
4792AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4793 Vector< sp<Track> > *tracksToRemove)
4794{
Andy Hungc0691382018-09-12 18:01:57 -07004795 // clean up deleted track ids in AudioMixer before allocating new tracks
4796 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4797 // for each trackId, destroy it in the AudioMixer
4798 if (mAudioMixer->exists(trackId)) {
4799 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004800 }
4801 });
Andy Hungc0691382018-09-12 18:01:57 -07004802 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004803
4804 mixer_state mixerStatus = MIXER_IDLE;
4805 // find out which tracks need to be processed
4806 size_t count = mActiveTracks.size();
4807 size_t mixedTracks = 0;
4808 size_t tracksWithEffect = 0;
4809 // counts only _active_ fast tracks
4810 size_t fastTracks = 0;
4811 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4812
4813 float masterVolume = mMasterVolume;
4814 bool masterMute = mMasterMute;
4815
4816 if (masterMute) {
4817 masterVolume = 0;
4818 }
4819 // Delegate master volume control to effect in output mix effect chain if needed
4820 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4821 if (chain != 0) {
4822 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4823 chain->setVolume_l(&v, &v);
4824 masterVolume = (float)((v + (1 << 23)) >> 24);
4825 chain.clear();
4826 }
4827
4828 // prepare a new state to push
4829 FastMixerStateQueue *sq = NULL;
4830 FastMixerState *state = NULL;
4831 bool didModify = false;
4832 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004833 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004834 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004835 sq = mFastMixer->sq();
4836 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004837 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004838 }
4839
Andy Hung69aed5f2014-02-25 17:24:40 -08004840 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004841 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004842
Andy Hungbd3b2b02018-05-21 10:53:11 -07004843 // DeferredOperations handles statistics after setting mixerStatus.
4844 class DeferredOperations {
4845 public:
Andy Hungea840382020-05-05 21:50:17 -07004846 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4847 : mMixerStatus(mixerStatus)
4848 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004849
4850 // when leaving scope, tally frames properly.
4851 ~DeferredOperations() {
4852 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4853 // because that is when the underrun occurs.
4854 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004855 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004856 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004857 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004858 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004859 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004860 }
4861 }
Andy Hungea840382020-05-05 21:50:17 -07004862 // send the max underrun frames for this mixer period
4863 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004864 }
4865
4866 // tallyUnderrunFrames() is called to update the track counters
4867 // with the number of underrun frames for a particular mixer period.
4868 // We defer tallying until we know the final mixer status.
4869 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4870 mUnderrunFrames.emplace_back(track, underrunFrames);
4871 }
4872
4873 private:
4874 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004875 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004876 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004877 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004878 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004879
jiabin245cdd92018-12-07 17:55:15 -08004880 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004881 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004882 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004883
4884 // this const just means the local variable doesn't change
4885 Track* const track = t.get();
4886
4887 // process fast tracks
4888 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004889 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4890 "%s(%d): FastTrack(%d) present without FastMixer",
4891 __func__, id(), track->id());
4892
jiabin245cdd92018-12-07 17:55:15 -08004893 if (track->getHapticPlaybackEnabled()) {
4894 noFastHapticTrack = false;
4895 }
Eric Laurent81784c32012-11-19 14:55:58 -08004896
4897 // It's theoretically possible (though unlikely) for a fast track to be created
4898 // and then removed within the same normal mix cycle. This is not a problem, as
4899 // the track never becomes active so it's fast mixer slot is never touched.
4900 // The converse, of removing an (active) track and then creating a new track
4901 // at the identical fast mixer slot within the same normal mix cycle,
4902 // is impossible because the slot isn't marked available until the end of each cycle.
4903 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004904 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004905 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4906 FastTrack *fastTrack = &state->mFastTracks[j];
4907
4908 // Determine whether the track is currently in underrun condition,
4909 // and whether it had a recent underrun.
4910 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4911 FastTrackUnderruns underruns = ftDump->mUnderruns;
4912 uint32_t recentFull = (underruns.mBitFields.mFull -
4913 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4914 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4915 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4916 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4917 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4918 uint32_t recentUnderruns = recentPartial + recentEmpty;
4919 track->mObservedUnderruns = underruns;
4920 // don't count underruns that occur while stopping or pausing
4921 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004922 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004923 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4924 recentUnderruns > 0) {
4925 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004926 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004927 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004928 // Immediately account for FastTrack underruns.
4929 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004930
4931 // This is similar to the state machine for normal tracks,
4932 // with a few modifications for fast tracks.
4933 bool isActive = true;
4934 switch (track->mState) {
4935 case TrackBase::STOPPING_1:
4936 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004937 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004938 track->mState = TrackBase::STOPPING_2;
4939 }
4940 break;
4941 case TrackBase::PAUSING:
4942 // ramp down is not yet implemented
4943 track->setPaused();
4944 break;
4945 case TrackBase::RESUMING:
4946 // ramp up is not yet implemented
4947 track->mState = TrackBase::ACTIVE;
4948 break;
4949 case TrackBase::ACTIVE:
4950 if (recentFull > 0 || recentPartial > 0) {
4951 // track has provided at least some frames recently: reset retry count
4952 track->mRetryCount = kMaxTrackRetries;
4953 }
4954 if (recentUnderruns == 0) {
4955 // no recent underruns: stay active
4956 break;
4957 }
4958 // there has recently been an underrun of some kind
4959 if (track->sharedBuffer() == 0) {
4960 // were any of the recent underruns "empty" (no frames available)?
4961 if (recentEmpty == 0) {
4962 // no, then ignore the partial underruns as they are allowed indefinitely
4963 break;
4964 }
4965 // there has recently been an "empty" underrun: decrement the retry counter
4966 if (--(track->mRetryCount) > 0) {
4967 break;
4968 }
4969 // indicate to client process that the track was disabled because of underrun;
4970 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004971 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004972 // remove from active list, but state remains ACTIVE [confusing but true]
4973 isActive = false;
4974 break;
4975 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004976 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004977 case TrackBase::STOPPING_2:
4978 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004979 case TrackBase::STOPPED:
4980 case TrackBase::FLUSHED: // flush() while active
4981 // Check for presentation complete if track is inactive
4982 // We have consumed all the buffers of this track.
4983 // This would be incomplete if we auto-paused on underrun
4984 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004985 uint32_t latency = 0;
4986 status_t result = mOutput->stream->getLatency(&latency);
4987 ALOGE_IF(result != OK,
4988 "Error when retrieving output stream latency: %d", result);
4989 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004990 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004991 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4992 // track stays in active list until presentation is complete
4993 break;
4994 }
4995 }
4996 if (track->isStopping_2()) {
4997 track->mState = TrackBase::STOPPED;
4998 }
4999 if (track->isStopped()) {
5000 // Can't reset directly, as fast mixer is still polling this track
5001 // track->reset();
5002 // So instead mark this track as needing to be reset after push with ack
5003 resetMask |= 1 << i;
5004 }
5005 isActive = false;
5006 break;
5007 case TrackBase::IDLE:
5008 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005009 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005010 }
5011
5012 if (isActive) {
5013 // was it previously inactive?
5014 if (!(state->mTrackMask & (1 << j))) {
5015 ExtendedAudioBufferProvider *eabp = track;
5016 VolumeProvider *vp = track;
5017 fastTrack->mBufferProvider = eabp;
5018 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005019 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005020 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005021 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005022 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005023 fastTrack->mGeneration++;
5024 state->mTrackMask |= 1 << j;
5025 didModify = true;
5026 // no acknowledgement required for newly active tracks
5027 }
Kevin Rocard12381092018-04-11 09:19:59 -07005028 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005029 float volume;
5030 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5031 volume = 0.f;
5032 } else {
5033 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5034 }
5035
5036 handleVoipVolume_l(&volume);
5037
Eric Laurent81784c32012-11-19 14:55:58 -08005038 // cache the combined master volume and stream type volume for fast mixer; this
5039 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005040 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005041 proxy->framesReleased()).first;
5042 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005043 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005044 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5045 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5046 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005047
Kevin Rocard12381092018-04-11 09:19:59 -07005048 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005049 ++fastTracks;
5050 } else {
5051 // was it previously active?
5052 if (state->mTrackMask & (1 << j)) {
5053 fastTrack->mBufferProvider = NULL;
5054 fastTrack->mGeneration++;
5055 state->mTrackMask &= ~(1 << j);
5056 didModify = true;
5057 // If any fast tracks were removed, we must wait for acknowledgement
5058 // because we're about to decrement the last sp<> on those tracks.
5059 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5060 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005061 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5062 // AudioTrack may start (which may not be with a start() but with a write()
5063 // after underrun) and immediately paused or released. In that case the
5064 // FastTrack state hasn't had time to update.
5065 // TODO Remove the ALOGW when this theory is confirmed.
5066 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005067 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5068 j, track->mState, state->mTrackMask, recentUnderruns,
5069 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005070 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005071 }
5072 tracksToRemove->add(track);
5073 // Avoids a misleading display in dumpsys
5074 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5075 }
jiabin245cdd92018-12-07 17:55:15 -08005076 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5077 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5078 didModify = true;
5079 }
Eric Laurent81784c32012-11-19 14:55:58 -08005080 continue;
5081 }
5082
5083 { // local variable scope to avoid goto warning
5084
5085 audio_track_cblk_t* cblk = track->cblk();
5086
5087 // The first time a track is added we wait
5088 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005089 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005090
5091 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005092 // use the trackId as the AudioMixer name.
5093 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005094 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005095 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005096 track->mChannelMask,
5097 track->mFormat,
5098 track->mSessionId);
5099 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005100 ALOGW("%s(): AudioMixer cannot create track(%d)"
5101 " mask %#x, format %#x, sessionId %d",
5102 __func__, trackId,
5103 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005104 tracksToRemove->add(track);
5105 track->invalidate(); // consider it dead.
5106 continue;
5107 }
5108 }
5109
Eric Laurent81784c32012-11-19 14:55:58 -08005110 // make sure that we have enough frames to mix one full buffer.
5111 // enforce this condition only once to enable draining the buffer in case the client
5112 // app does not call stop() and relies on underrun to stop:
5113 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5114 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005115 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005116 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005117 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005118
5119 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005120 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005121 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5122 // add frames already consumed but not yet released by the resampler
5123 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005124 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005125
Eric Laurent81784c32012-11-19 14:55:58 -08005126 uint32_t minFrames = 1;
5127 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5128 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005129 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005130 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005131
5132 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005133 if (ATRACE_ENABLED()) {
5134 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005135 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005136 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005137 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005138 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005139 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005140 !track->isPaused() && !track->isTerminated())
5141 {
Andy Hungc0691382018-09-12 18:01:57 -07005142 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005143
5144 mixedTracks++;
5145
Andy Hung69aed5f2014-02-25 17:24:40 -08005146 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5147 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005148 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005149 if (track->mainBuffer() != mSinkBuffer &&
5150 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005151 if (mEffectBufferEnabled) {
5152 mEffectBufferValid = true; // Later can set directly.
5153 }
Eric Laurent81784c32012-11-19 14:55:58 -08005154 chain = getEffectChain_l(track->sessionId());
5155 // Delegate volume control to effect in track effect chain if needed
5156 if (chain != 0) {
5157 tracksWithEffect++;
5158 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005159 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005160 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005161 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005162 }
5163 }
5164
5165
5166 int param = AudioMixer::VOLUME;
5167 if (track->mFillingUpStatus == Track::FS_FILLED) {
5168 // no ramp for the first volume setting
5169 track->mFillingUpStatus = Track::FS_ACTIVE;
5170 if (track->mState == TrackBase::RESUMING) {
5171 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005172 // If a new track is paused immediately after start, do not ramp on resume.
5173 if (cblk->mServer != 0) {
5174 param = AudioMixer::RAMP_VOLUME;
5175 }
Eric Laurent81784c32012-11-19 14:55:58 -08005176 }
Andy Hungc0691382018-09-12 18:01:57 -07005177 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005178 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005179 // FIXME should not make a decision based on mServer
5180 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005181 // If the track is stopped before the first frame was mixed,
5182 // do not apply ramp
5183 param = AudioMixer::RAMP_VOLUME;
5184 }
5185
5186 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005187 uint32_t vl, vr; // in U8.24 integer format
5188 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005189 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005190 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005191 // Always fetch volumeshaper volume to ensure state is updated.
5192 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5193 const float vh = track->getVolumeHandler()->getVolume(
5194 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005195
Eric Laurenteab90452019-06-24 15:17:46 -07005196 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5197 v = 0;
5198 }
5199
5200 handleVoipVolume_l(&v);
5201
5202 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005203 vl = vr = 0;
5204 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005205 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005206 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005207 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005208 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5209 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005210 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005211 if (vlf > GAIN_FLOAT_UNITY) {
5212 ALOGV("Track left volume out of range: %.3g", vlf);
5213 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005214 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005215 if (vrf > GAIN_FLOAT_UNITY) {
5216 ALOGV("Track right volume out of range: %.3g", vrf);
5217 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005218 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005219 // now apply the master volume and stream type volume and shaper volume
5220 vlf *= v * vh;
5221 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005222 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005223 // then derive vl and vr as U8.24 versions for the effect chain
5224 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5225 vl = (uint32_t) (scaleto8_24 * vlf);
5226 vr = (uint32_t) (scaleto8_24 * vrf);
5227 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005228 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005229 // send level comes from shared memory and so may be corrupt
5230 if (sendLevel > MAX_GAIN_INT) {
5231 ALOGV("Track send level out of range: %04X", sendLevel);
5232 sendLevel = MAX_GAIN_INT;
5233 }
Andy Hung6be49402014-05-30 10:42:03 -07005234 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5235 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005236 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005237
Kevin Rocard12381092018-04-11 09:19:59 -07005238 track->setFinalVolume((vrf + vlf) / 2.f);
5239
Eric Laurent81784c32012-11-19 14:55:58 -08005240 // Delegate volume control to effect in track effect chain if needed
5241 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5242 // Do not ramp volume if volume is controlled by effect
5243 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005244 // Update remaining floating point volume levels
5245 vlf = (float)vl / (1 << 24);
5246 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005247 track->mHasVolumeController = true;
5248 } else {
5249 // force no volume ramp when volume controller was just disabled or removed
5250 // from effect chain to avoid volume spike
5251 if (track->mHasVolumeController) {
5252 param = AudioMixer::VOLUME;
5253 }
5254 track->mHasVolumeController = false;
5255 }
5256
Eric Laurent81784c32012-11-19 14:55:58 -08005257 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005258 mAudioMixer->setBufferProvider(trackId, track);
5259 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005260
Andy Hungc0691382018-09-12 18:01:57 -07005261 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5262 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5263 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005264 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005265 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005266 AudioMixer::TRACK,
5267 AudioMixer::FORMAT, (void *)track->format());
5268 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005269 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005270 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005271 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005272 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005273 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005274 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005275 AudioMixer::MIXER_CHANNEL_MASK,
5276 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005277 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005278 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005279 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005280 if (reqSampleRate == 0) {
5281 reqSampleRate = mSampleRate;
5282 } else if (reqSampleRate > maxSampleRate) {
5283 reqSampleRate = maxSampleRate;
5284 }
Eric Laurent81784c32012-11-19 14:55:58 -08005285 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005286 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005287 AudioMixer::RESAMPLE,
5288 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005289 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005290
Andy Hung333ab962019-05-28 20:23:35 -07005291 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005292 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005293 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005294 AudioMixer::TIMESTRETCH,
5295 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005296 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005297
Andy Hung69aed5f2014-02-25 17:24:40 -08005298 /*
5299 * Select the appropriate output buffer for the track.
5300 *
Andy Hung98ef9782014-03-04 14:46:50 -08005301 * Tracks with effects go into their own effects chain buffer
5302 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005303 *
5304 * Other tracks can use mMixerBuffer for higher precision
5305 * channel accumulation. If this buffer is enabled
5306 * (mMixerBufferEnabled true), then selected tracks will accumulate
5307 * into it.
5308 *
5309 */
5310 if (mMixerBufferEnabled
5311 && (track->mainBuffer() == mSinkBuffer
5312 || track->mainBuffer() == mMixerBuffer)) {
5313 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005314 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005315 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005316 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005317 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005318 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005319 AudioMixer::TRACK,
5320 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5321 // TODO: override track->mainBuffer()?
5322 mMixerBufferValid = true;
5323 } else {
5324 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005325 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005326 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005327 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005328 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005329 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005330 AudioMixer::TRACK,
5331 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5332 }
Eric Laurent81784c32012-11-19 14:55:58 -08005333 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005334 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005335 AudioMixer::TRACK,
5336 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005337 mAudioMixer->setParameter(
5338 trackId,
5339 AudioMixer::TRACK,
5340 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005341 mAudioMixer->setParameter(
5342 trackId,
5343 AudioMixer::TRACK,
5344 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005345
5346 // reset retry count
5347 track->mRetryCount = kMaxTrackRetries;
5348
5349 // If one track is ready, set the mixer ready if:
5350 // - the mixer was not ready during previous round OR
5351 // - no other track is not ready
5352 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5353 mixerStatus != MIXER_TRACKS_ENABLED) {
5354 mixerStatus = MIXER_TRACKS_READY;
5355 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005356
5357 // Enable the next few lines to instrument a test for underrun log handling.
5358 // TODO: Remove when we have a better way of testing the underrun log.
5359#if 0
5360 static int i;
5361 if ((++i & 0xf) == 0) {
5362 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5363 }
5364#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005365 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005366 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005367 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005368 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5369 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005370 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005371 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005372 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005373
Eric Laurent81784c32012-11-19 14:55:58 -08005374 // clear effect chain input buffer if an active track underruns to avoid sending
5375 // previous audio buffer again to effects
5376 chain = getEffectChain_l(track->sessionId());
5377 if (chain != 0) {
5378 chain->clearInputBuffer();
5379 }
5380
Andy Hungc0691382018-09-12 18:01:57 -07005381 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005382 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5383 track->isStopped() || track->isPaused()) {
5384 // We have consumed all the buffers of this track.
5385 // Remove it from the list of active tracks.
5386 // TODO: use actual buffer filling status instead of latency when available from
5387 // audio HAL
5388 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005389 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005390 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5391 if (track->isStopped()) {
5392 track->reset();
5393 }
5394 tracksToRemove->add(track);
5395 }
5396 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005397 // No buffers for this track. Give it a few chances to
5398 // fill a buffer, then remove it from active list.
5399 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005400 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5401 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005402 tracksToRemove->add(track);
5403 // indicate to client process that the track was disabled because of underrun;
5404 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005405 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005406 // If one track is not ready, mark the mixer also not ready if:
5407 // - the mixer was ready during previous round OR
5408 // - no other track is ready
5409 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5410 mixerStatus != MIXER_TRACKS_READY) {
5411 mixerStatus = MIXER_TRACKS_ENABLED;
5412 }
5413 }
Andy Hungc0691382018-09-12 18:01:57 -07005414 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005415 }
5416
5417 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005418
5419 }
5420
jiabin245cdd92018-12-07 17:55:15 -08005421 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5422 // When there is no fast track playing haptic and FastMixer exists,
5423 // enabling the first FastTrack, which provides mixed data from normal
5424 // tracks, to play haptic data.
5425 FastTrack *fastTrack = &state->mFastTracks[0];
5426 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5427 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5428 didModify = true;
5429 }
5430 }
5431
Eric Laurent81784c32012-11-19 14:55:58 -08005432 // Push the new FastMixer state if necessary
5433 bool pauseAudioWatchdog = false;
5434 if (didModify) {
5435 state->mFastTracksGen++;
5436 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5437 if (kUseFastMixer == FastMixer_Dynamic &&
5438 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5439 state->mCommand = FastMixerState::COLD_IDLE;
5440 state->mColdFutexAddr = &mFastMixerFutex;
5441 state->mColdGen++;
5442 mFastMixerFutex = 0;
5443 if (kUseFastMixer == FastMixer_Dynamic) {
5444 mNormalSink = mOutputSink;
5445 }
5446 // If we go into cold idle, need to wait for acknowledgement
5447 // so that fast mixer stops doing I/O.
5448 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5449 pauseAudioWatchdog = true;
5450 }
Eric Laurent81784c32012-11-19 14:55:58 -08005451 }
5452 if (sq != NULL) {
5453 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005454 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5455 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5456 // when bringing the output sink into standby.)
5457 //
5458 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5459 //
5460 // This occurs with BT suspend when we idle the FastMixer with
5461 // active tracks, which may be added or removed.
5462 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005463 }
5464#ifdef AUDIO_WATCHDOG
5465 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5466 mAudioWatchdog->pause();
5467 }
5468#endif
5469
5470 // Now perform the deferred reset on fast tracks that have stopped
5471 while (resetMask != 0) {
5472 size_t i = __builtin_ctz(resetMask);
5473 ALOG_ASSERT(i < count);
5474 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005475 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005476 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5477 track->reset();
5478 }
5479
Andy Hung80d03d22018-04-10 10:32:11 -07005480 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5481 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5482 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5483 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5484 // See also the implementation of destroyTrack_l().
5485 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005486 const int trackId = track->id();
5487 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5488 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005489 }
5490 }
5491
Eric Laurent81784c32012-11-19 14:55:58 -08005492 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005493 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005494
Eric Laurent97d547d2014-09-02 14:45:53 -07005495 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5496 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005497 }
5498
5499 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005500 // as long as there are effects we should clear the effects buffer, to avoid
5501 // passing a non-clean buffer to the effect chain
5502 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005503 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005504 // sink or mix buffer must be cleared if all tracks are connected to an
5505 // effect chain as in this case the mixer will not write to the sink or mix buffer
5506 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005507 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5508 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005509 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005510 if (mMixerBufferValid) {
5511 memset(mMixerBuffer, 0, mMixerBufferSize);
5512 // TODO: In testing, mSinkBuffer below need not be cleared because
5513 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5514 // after mixing.
5515 //
5516 // To enforce this guarantee:
5517 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5518 // (mixedTracks == 0 && fastTracks > 0))
5519 // must imply MIXER_TRACKS_READY.
5520 // Later, we may clear buffers regardless, and skip much of this logic.
5521 }
Andy Hung98ef9782014-03-04 14:46:50 -08005522 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005523 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005524 }
5525
5526 // if any fast tracks, then status is ready
5527 mMixerStatusIgnoringFastTracks = mixerStatus;
5528 if (fastTracks > 0) {
5529 mixerStatus = MIXER_TRACKS_READY;
5530 }
5531 return mixerStatus;
5532}
5533
Eric Laurentad7dd962016-09-22 12:38:37 -07005534// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005535uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005536{
5537 uint32_t trackCount = 0;
5538 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005539 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005540 trackCount++;
5541 }
5542 }
5543 return trackCount;
5544}
5545
Andy Hung1bc088a2018-02-09 15:57:31 -08005546// isTrackAllowed_l() must be called with ThreadBase::mLock held
5547bool AudioFlinger::MixerThread::isTrackAllowed_l(
5548 audio_channel_mask_t channelMask, audio_format_t format,
5549 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005550{
Andy Hung1bc088a2018-02-09 15:57:31 -08005551 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5552 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005553 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005554 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005555 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005556 ALOGW("%s: invalid format: %#x", __func__, format);
5557 return false;
5558 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005559 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005560 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5561 return false;
5562 }
5563 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005564}
5565
Eric Laurent10351942014-05-08 18:49:52 -07005566// checkForNewParameter_l() must be called with ThreadBase::mLock held
5567bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5568 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005569{
Eric Laurent81784c32012-11-19 14:55:58 -08005570 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005571 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005572
Eric Laurent10351942014-05-08 18:49:52 -07005573 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005574
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005575 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005576
Eric Laurent10351942014-05-08 18:49:52 -07005577 AudioParameter param = AudioParameter(keyValuePair);
5578 int value;
5579 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5580 reconfig = true;
5581 }
5582 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005583 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005584 status = BAD_VALUE;
5585 } else {
5586 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005587 reconfig = true;
5588 }
Eric Laurent10351942014-05-08 18:49:52 -07005589 }
5590 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005591 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005592 status = BAD_VALUE;
5593 } else {
5594 // no need to save value, since it's constant
5595 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005596 }
Eric Laurent10351942014-05-08 18:49:52 -07005597 }
5598 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5599 // do not accept frame count changes if tracks are open as the track buffer
5600 // size depends on frame count and correct behavior would not be guaranteed
5601 // if frame count is changed after track creation
5602 if (!mTracks.isEmpty()) {
5603 status = INVALID_OPERATION;
5604 } else {
5605 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005606 }
Eric Laurent10351942014-05-08 18:49:52 -07005607 }
5608 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005609 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005610 }
Eric Laurent81784c32012-11-19 14:55:58 -08005611
Eric Laurent10351942014-05-08 18:49:52 -07005612 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005613 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005614 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005615 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005616 if (!mStandby) {
5617 mThreadMetrics.logEndInterval();
5618 mStandby = true;
5619 }
Eric Laurent10351942014-05-08 18:49:52 -07005620 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005621 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005622 }
Eric Laurent10351942014-05-08 18:49:52 -07005623 if (status == NO_ERROR && reconfig) {
5624 readOutputParameters_l();
5625 delete mAudioMixer;
5626 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005627 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005628 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005629 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005630 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005631 track->mChannelMask,
5632 track->mFormat,
5633 track->mSessionId);
5634 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005635 "%s(): AudioMixer cannot create track(%d)"
5636 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005637 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005638 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005639 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005640 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005641 }
Eric Laurent81784c32012-11-19 14:55:58 -08005642 }
5643
Eric Laurent42537be2016-01-08 17:16:42 -08005644 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005645}
5646
5647
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005648void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005649{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005650 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005651 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005652 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005653 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005654 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5655 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5656 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005657 if (hasFastMixer()) {
5658 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5659
5660 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5661 // while we are dumping it. It may be inconsistent, but it won't mutate!
5662 // This is a large object so we place it on the heap.
5663 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005664 const std::unique_ptr<FastMixerDumpState> copy =
5665 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005666 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005667
5668#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005669 // Similar for state queue
5670 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5671 observerCopy.dump(fd);
5672 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5673 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005674#endif
5675
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005676#ifdef AUDIO_WATCHDOG
5677 if (mAudioWatchdog != 0) {
5678 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5679 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5680 wdCopy.dump(fd);
5681 }
5682#endif
5683
5684 } else {
5685 dprintf(fd, " No FastMixer\n");
5686 }
Eric Laurent81784c32012-11-19 14:55:58 -08005687}
5688
5689uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5690{
5691 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5692}
5693
5694uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5695{
5696 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5697}
5698
5699void AudioFlinger::MixerThread::cacheParameters_l()
5700{
5701 PlaybackThread::cacheParameters_l();
5702
5703 // FIXME: Relaxed timing because of a certain device that can't meet latency
5704 // Should be reduced to 2x after the vendor fixes the driver issue
5705 // increase threshold again due to low power audio mode. The way this warning
5706 // threshold is calculated and its usefulness should be reconsidered anyway.
5707 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5708}
5709
5710// ----------------------------------------------------------------------------
5711
5712AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005713 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5714 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005715{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005716 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005717}
5718
Eric Laurent81784c32012-11-19 14:55:58 -08005719AudioFlinger::DirectOutputThread::~DirectOutputThread()
5720{
5721}
5722
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005723void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005724{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005725 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005726 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5727 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5728}
5729
5730void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5731{
5732 Mutex::Autolock _l(mLock);
5733 if (mMasterBalance != balance) {
5734 mMasterBalance.store(balance);
5735 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5736 broadcast_l();
5737 }
5738}
5739
Eric Laurent5850c4c2016-11-10 13:04:31 -08005740void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005741{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005742 float left, right;
5743
Andy Hung333ab962019-05-28 20:23:35 -07005744 // Ensure volumeshaper state always advances even when muted.
5745 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5746 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5747 proxy->framesReleased());
5748 mVolumeShaperActive = shaperActive;
5749
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005750 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005751 left = right = 0;
5752 } else {
5753 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005754 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005755
Glenn Kastenc56f3422014-03-21 17:53:17 -07005756 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5757 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5758 if (left > GAIN_FLOAT_UNITY) {
5759 left = GAIN_FLOAT_UNITY;
5760 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005761 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005762 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5763 if (right > GAIN_FLOAT_UNITY) {
5764 right = GAIN_FLOAT_UNITY;
5765 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005766 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005767 }
5768
5769 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005770 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005771 if (left != mLeftVolFloat || right != mRightVolFloat) {
5772 mLeftVolFloat = left;
5773 mRightVolFloat = right;
5774
Eric Laurentbfb1b832013-01-07 09:53:42 -08005775 // Delegate volume control to effect in track effect chain if needed
5776 // only one effect chain can be present on DirectOutputThread, so if
5777 // there is one, the track is connected to it
5778 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005779 // if effect chain exists, volume is handled by it.
5780 // Convert volumes from float to 8.24
5781 uint32_t vl = (uint32_t)(left * (1 << 24));
5782 uint32_t vr = (uint32_t)(right * (1 << 24));
5783 // Direct/Offload effect chains set output volume in setVolume_l().
5784 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5785 } else {
5786 // otherwise we directly set the volume.
5787 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005788 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005789 }
5790 }
5791}
5792
Phil Burk43b4dcc2015-06-09 16:53:44 -07005793void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5794{
5795 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005796 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005797
Eric Laurent0f0631e2015-07-06 18:01:25 -07005798 if (previousTrack != 0 && latestTrack != 0) {
5799 if (mType == DIRECT) {
5800 if (previousTrack.get() != latestTrack.get()) {
5801 mFlushPending = true;
5802 }
5803 } else /* mType == OFFLOAD */ {
5804 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5805 mFlushPending = true;
5806 }
5807 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005808 } else if (previousTrack == 0) {
5809 // there could be an old track added back during track transition for direct
5810 // output, so always issues flush to flush data of the previous track if it
5811 // was already destroyed with HAL paused, then flush can resume the playback
5812 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005813 }
5814 PlaybackThread::onAddNewTrack_l();
5815}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005816
Eric Laurent81784c32012-11-19 14:55:58 -08005817AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5818 Vector< sp<Track> > *tracksToRemove
5819)
5820{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005821 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005822 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005823 bool doHwPause = false;
5824 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005825
5826 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005827 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005828 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005829 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005830 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005831 continue;
5832 }
5833
Eric Laurent5850c4c2016-11-10 13:04:31 -08005834 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005835#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005836 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005837#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005838 // Only consider last track started for volume and mixer state control.
5839 // In theory an older track could underrun and restart after the new one starts
5840 // but as we only care about the transition phase between two tracks on a
5841 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005842 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005843 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005844
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005845 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005846 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005847 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005848 doHwPause = true;
5849 mHwPaused = true;
5850 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005851 } else if (track->isFlushPending()) {
5852 track->flushAck();
5853 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005854 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005855 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005856 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005857 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005858 if (last) {
5859 mLeftVolFloat = mRightVolFloat = -1.0;
5860 if (mHwPaused) {
5861 doHwResume = true;
5862 mHwPaused = false;
5863 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005864 }
5865 }
5866
Eric Laurent81784c32012-11-19 14:55:58 -08005867 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005868 // for all its buffers to be filled before processing it.
5869 // Allow draining the buffer in case the client
5870 // app does not call stop() and relies on underrun to stop:
5871 // hence the test on (track->mRetryCount > 1).
5872 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005873 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005874 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005875 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005876 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005877 minFrames = mNormalFrameCount;
5878 } else {
5879 minFrames = 1;
5880 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005881
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005882 const size_t framesReady = track->framesReady();
5883 const int trackId = track->id();
5884 if (ATRACE_ENABLED()) {
5885 std::string traceName("nRdy");
5886 traceName += std::to_string(trackId);
5887 ATRACE_INT(traceName.c_str(), framesReady);
5888 }
5889 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005890 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005891 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005892 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005893
5894 if (track->mFillingUpStatus == Track::FS_FILLED) {
5895 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005896 if (last) {
5897 // make sure processVolume_l() will apply new volume even if 0
5898 mLeftVolFloat = mRightVolFloat = -1.0;
5899 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005900 if (!mHwSupportsPause) {
5901 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005902 }
5903 }
5904
5905 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005906 processVolume_l(track, last);
5907 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005908 sp<Track> previousTrack = mPreviousTrack.promote();
5909 if (previousTrack != 0) {
5910 if (track != previousTrack.get()) {
5911 // Flush any data still being written from last track
5912 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005913 // Invalidate previous track to force a seek when resuming.
5914 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005915 }
5916 }
5917 mPreviousTrack = track;
5918
Eric Laurentd595b7c2013-04-03 17:27:56 -07005919 // reset retry count
5920 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005921 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005922 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005923 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005924 doHwResume = true;
5925 mHwPaused = false;
5926 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005927 }
Eric Laurent81784c32012-11-19 14:55:58 -08005928 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005929 // clear effect chain input buffer if the last active track started underruns
5930 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005931 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005932 mEffectChains[0]->clearInputBuffer();
5933 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005934 if (track->isStopping_1()) {
5935 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005936 if (last && mHwPaused) {
5937 doHwResume = true;
5938 mHwPaused = false;
5939 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005940 }
5941 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5942 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005943 // We have consumed all the buffers of this track.
5944 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005945 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005946 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005947 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5948 } else {
5949 audioHALFrames = 0;
5950 }
5951
Andy Hung818e7a32016-02-16 18:08:07 -08005952 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005953 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005954 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08005955 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005956 if (track->isStopping_2()) {
5957 track->mState = TrackBase::STOPPED;
5958 }
Eric Laurent81784c32012-11-19 14:55:58 -08005959 if (track->isStopped()) {
5960 track->reset();
5961 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005962 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005963 }
5964 } else {
5965 // No buffers for this track. Give it a few chances to
5966 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005967 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005968 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005969 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005970 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005971 // indicate to client process that the track was disabled because of underrun;
5972 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005973 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005974 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005975 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5976 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005977 framesReady, minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005978 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005979 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005980 doHwPause = true;
5981 mHwPaused = true;
5982 }
Eric Laurent81784c32012-11-19 14:55:58 -08005983 }
5984 }
5985 }
5986 }
5987
Eric Laurentd1f69b02014-12-15 14:33:13 -08005988 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005989 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005990 for (size_t i = 0; i < mTracks.size(); i++) {
5991 if (mTracks[i]->isFlushPending()) {
5992 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005993 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005994 }
5995 }
5996 }
5997
5998 // make sure the pause/flush/resume sequence is executed in the right order.
5999 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6000 // before flush and then resume HW. This can happen in case of pause/flush/resume
6001 // if resume is received before pause is executed.
6002 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006003 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006004 status_t result = mOutput->stream->pause();
6005 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006006 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006007 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006008 flushHw_l();
6009 }
6010 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006011 status_t result = mOutput->stream->resume();
6012 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006013 }
Eric Laurent81784c32012-11-19 14:55:58 -08006014 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006015 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006016
6017 return mixerStatus;
6018}
6019
6020void AudioFlinger::DirectOutputThread::threadLoop_mix()
6021{
Eric Laurent81784c32012-11-19 14:55:58 -08006022 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006023 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006024 // output audio to hardware
6025 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006026 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006027 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006028 status_t status = mActiveTrack->getNextBuffer(&buffer);
6029 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006030 // no need to pad with 0 for compressed audio
6031 if (audio_has_proportional_frames(mFormat)) {
6032 memset(curBuf, 0, frameCount * mFrameSize);
6033 }
Eric Laurent81784c32012-11-19 14:55:58 -08006034 break;
6035 }
6036 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6037 frameCount -= buffer.frameCount;
6038 curBuf += buffer.frameCount * mFrameSize;
6039 mActiveTrack->releaseBuffer(&buffer);
6040 }
Andy Hung2098f272014-02-27 14:00:06 -08006041 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006042 mSleepTimeUs = 0;
6043 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006044 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006045}
6046
6047void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6048{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006049 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006050 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006051 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006052 return;
6053 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006054 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006055 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07006056 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006057 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006058 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006059 }
Phil Burkfdb3c072016-02-09 10:47:02 -08006060 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08006061 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006062 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006063 }
6064}
6065
Eric Laurentd1f69b02014-12-15 14:33:13 -08006066void AudioFlinger::DirectOutputThread::threadLoop_exit()
6067{
6068 {
6069 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006070 for (size_t i = 0; i < mTracks.size(); i++) {
6071 if (mTracks[i]->isFlushPending()) {
6072 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006073 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006074 }
6075 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006076 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006077 flushHw_l();
6078 }
6079 }
6080 PlaybackThread::threadLoop_exit();
6081}
6082
6083// must be called with thread mutex locked
6084bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6085{
6086 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006087 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006088
6089 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6090 // after a timeout and we will enter standby then.
6091 if (mTracks.size() > 0) {
6092 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006093 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6094 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006095 }
6096
Eric Laurent5cff4032015-05-26 13:49:58 -07006097 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006098}
6099
Eric Laurent10351942014-05-08 18:49:52 -07006100// checkForNewParameter_l() must be called with ThreadBase::mLock held
6101bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6102 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006103{
6104 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08006105 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006106
Eric Laurent10351942014-05-08 18:49:52 -07006107 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006108
Eric Laurent10351942014-05-08 18:49:52 -07006109 AudioParameter param = AudioParameter(keyValuePair);
6110 int value;
6111 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006112 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006113 }
Eric Laurent10351942014-05-08 18:49:52 -07006114 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6115 // do not accept frame count changes if tracks are open as the track buffer
6116 // size depends on frame count and correct behavior would not be garantied
6117 // if frame count is changed after track creation
6118 if (!mTracks.isEmpty()) {
6119 status = INVALID_OPERATION;
6120 } else {
6121 reconfig = true;
6122 }
6123 }
6124 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006125 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006126 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006127 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006128 if (!mStandby) {
6129 mThreadMetrics.logEndInterval();
6130 mStandby = true;
6131 }
Eric Laurent10351942014-05-08 18:49:52 -07006132 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006133 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006134 }
6135 if (status == NO_ERROR && reconfig) {
6136 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006137 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006138 }
6139 }
6140
Eric Laurent42537be2016-01-08 17:16:42 -08006141 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08006142}
6143
6144uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6145{
6146 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006147 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006148 time = PlaybackThread::activeSleepTimeUs();
6149 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006150 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006151 }
6152 return time;
6153}
6154
6155uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6156{
6157 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006158 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006159 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6160 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006161 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006162 }
6163 return time;
6164}
6165
6166uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6167{
6168 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006169 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006170 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6171 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006172 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006173 }
6174 return time;
6175}
6176
6177void AudioFlinger::DirectOutputThread::cacheParameters_l()
6178{
6179 PlaybackThread::cacheParameters_l();
6180
6181 // use shorter standby delay as on normal output to release
6182 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006183 // no delay on outputs with HW A/V sync
6184 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006185 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006186 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006187 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006188 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006189 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006190 }
Eric Laurent81784c32012-11-19 14:55:58 -08006191}
6192
Eric Laurente659ef42014-09-29 13:06:46 -07006193void AudioFlinger::DirectOutputThread::flushHw_l()
6194{
Phil Burk062e67a2015-02-11 13:40:50 -08006195 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006196 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006197 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07006198 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Sampath Shetty999f0e82020-01-15 10:19:06 +11006199 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006200}
6201
Andy Hung10cbff12017-02-21 17:30:14 -08006202int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6203 // If a VolumeShaper is active, we must wake up periodically to update volume.
6204 const int64_t NS_PER_MS = 1000000;
6205 return mVolumeShaperActive ?
6206 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6207}
6208
Eric Laurent81784c32012-11-19 14:55:58 -08006209// ----------------------------------------------------------------------------
6210
Eric Laurentbfb1b832013-01-07 09:53:42 -08006211AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006212 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006213 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006214 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006215 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006216 mDrainSequence(0),
6217 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006218{
6219}
6220
6221AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6222{
6223}
6224
6225void AudioFlinger::AsyncCallbackThread::onFirstRef()
6226{
6227 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6228}
6229
6230bool AudioFlinger::AsyncCallbackThread::threadLoop()
6231{
6232 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006233 uint32_t writeAckSequence;
6234 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006235 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006236
6237 {
6238 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006239 while (!((mWriteAckSequence & 1) ||
6240 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006241 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006242 exitPending())) {
6243 mWaitWorkCV.wait(mLock);
6244 }
6245
Eric Laurentbfb1b832013-01-07 09:53:42 -08006246 if (exitPending()) {
6247 break;
6248 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006249 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6250 mWriteAckSequence, mDrainSequence);
6251 writeAckSequence = mWriteAckSequence;
6252 mWriteAckSequence &= ~1;
6253 drainSequence = mDrainSequence;
6254 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006255 asyncError = mAsyncError;
6256 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006257 }
6258 {
Eric Laurent4de95592013-09-26 15:28:21 -07006259 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6260 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006261 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006262 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006263 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006264 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006265 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006266 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006267 if (asyncError) {
6268 playbackThread->onAsyncError();
6269 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006270 }
6271 }
6272 }
6273 return false;
6274}
6275
6276void AudioFlinger::AsyncCallbackThread::exit()
6277{
6278 ALOGV("AsyncCallbackThread::exit");
6279 Mutex::Autolock _l(mLock);
6280 requestExit();
6281 mWaitWorkCV.broadcast();
6282}
6283
Eric Laurent3b4529e2013-09-05 18:09:19 -07006284void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006285{
6286 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006287 // bit 0 is cleared
6288 mWriteAckSequence = sequence << 1;
6289}
6290
6291void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6292{
6293 Mutex::Autolock _l(mLock);
6294 // ignore unexpected callbacks
6295 if (mWriteAckSequence & 2) {
6296 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006297 mWaitWorkCV.signal();
6298 }
6299}
6300
Eric Laurent3b4529e2013-09-05 18:09:19 -07006301void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006302{
6303 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006304 // bit 0 is cleared
6305 mDrainSequence = sequence << 1;
6306}
6307
6308void AudioFlinger::AsyncCallbackThread::resetDraining()
6309{
6310 Mutex::Autolock _l(mLock);
6311 // ignore unexpected callbacks
6312 if (mDrainSequence & 2) {
6313 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006314 mWaitWorkCV.signal();
6315 }
6316}
6317
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006318void AudioFlinger::AsyncCallbackThread::setAsyncError()
6319{
6320 Mutex::Autolock _l(mLock);
6321 mAsyncError = true;
6322 mWaitWorkCV.signal();
6323}
6324
Eric Laurentbfb1b832013-01-07 09:53:42 -08006325
6326// ----------------------------------------------------------------------------
6327AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006328 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6329 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006330 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6331 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006332{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006333 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006334 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006335 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006336}
6337
Eric Laurentbfb1b832013-01-07 09:53:42 -08006338void AudioFlinger::OffloadThread::threadLoop_exit()
6339{
6340 if (mFlushPending || mHwPaused) {
6341 // If a flush is pending or track was paused, just discard buffered data
6342 flushHw_l();
6343 } else {
6344 mMixerStatus = MIXER_DRAIN_ALL;
6345 threadLoop_drain();
6346 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006347 if (mUseAsyncWrite) {
6348 ALOG_ASSERT(mCallbackThread != 0);
6349 mCallbackThread->exit();
6350 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006351 PlaybackThread::threadLoop_exit();
6352}
6353
6354AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6355 Vector< sp<Track> > *tracksToRemove
6356)
6357{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006358 size_t count = mActiveTracks.size();
6359
6360 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006361 bool doHwPause = false;
6362 bool doHwResume = false;
6363
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006364 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006365
Eric Laurentbfb1b832013-01-07 09:53:42 -08006366 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006367 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006368 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006369#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006370 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006371#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006372 // Only consider last track started for volume and mixer state control.
6373 // In theory an older track could underrun and restart after the new one starts
6374 // but as we only care about the transition phase between two tracks on a
6375 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006376 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006377 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006378
Haynes Mathew George7844f672014-01-15 12:32:55 -08006379 if (track->isInvalid()) {
6380 ALOGW("An invalidated track shouldn't be in active list");
6381 tracksToRemove->add(track);
6382 continue;
6383 }
6384
6385 if (track->mState == TrackBase::IDLE) {
6386 ALOGW("An idle track shouldn't be in active list");
6387 continue;
6388 }
6389
Eric Laurentbfb1b832013-01-07 09:53:42 -08006390 if (track->isPausing()) {
6391 track->setPaused();
6392 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006393 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006394 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006395 mHwPaused = true;
6396 }
6397 // If we were part way through writing the mixbuffer to
6398 // the HAL we must save this until we resume
6399 // BUG - this will be wrong if a different track is made active,
6400 // in that case we want to discard the pending data in the
6401 // mixbuffer and tell the client to present it again when the
6402 // track is resumed
6403 mPausedWriteLength = mCurrentWriteLength;
6404 mPausedBytesRemaining = mBytesRemaining;
6405 mBytesRemaining = 0; // stop writing
6406 }
6407 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006408 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006409 if (track->isStopping_1()) {
6410 track->mRetryCount = kMaxTrackStopRetriesOffload;
6411 } else {
6412 track->mRetryCount = kMaxTrackRetriesOffload;
6413 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006414 track->flushAck();
6415 if (last) {
6416 mFlushPending = true;
6417 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006418 } else if (track->isResumePending()){
6419 track->resumeAck();
6420 if (last) {
6421 if (mPausedBytesRemaining) {
6422 // Need to continue write that was interrupted
6423 mCurrentWriteLength = mPausedWriteLength;
6424 mBytesRemaining = mPausedBytesRemaining;
6425 mPausedBytesRemaining = 0;
6426 }
6427 if (mHwPaused) {
6428 doHwResume = true;
6429 mHwPaused = false;
6430 // threadLoop_mix() will handle the case that we need to
6431 // resume an interrupted write
6432 }
6433 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006434 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006435
Eric Laurent3df841a2016-07-15 15:15:40 -07006436 mLeftVolFloat = mRightVolFloat = -1.0;
6437
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006438 // Do not handle new data in this iteration even if track->framesReady()
6439 mixerStatus = MIXER_TRACKS_ENABLED;
6440 }
6441 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006442 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006443 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006444 if (track->mFillingUpStatus == Track::FS_FILLED) {
6445 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006446 if (last) {
6447 // make sure processVolume_l() will apply new volume even if 0
6448 mLeftVolFloat = mRightVolFloat = -1.0;
6449 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006450 }
6451
6452 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006453 sp<Track> previousTrack = mPreviousTrack.promote();
6454 if (previousTrack != 0) {
6455 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006456 // Flush any data still being written from last track
6457 mBytesRemaining = 0;
6458 if (mPausedBytesRemaining) {
6459 // Last track was paused so we also need to flush saved
6460 // mixbuffer state and invalidate track so that it will
6461 // re-submit that unwritten data when it is next resumed
6462 mPausedBytesRemaining = 0;
6463 // Invalidate is a bit drastic - would be more efficient
6464 // to have a flag to tell client that some of the
6465 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006466 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006467 }
6468 // flush data already sent to the DSP if changing audio session as audio
6469 // comes from a different source. Also invalidate previous track to force a
6470 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006471 if (previousTrack->sessionId() != track->sessionId()) {
6472 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006473 }
6474 }
6475 }
6476 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006477 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006478 if (track->isStopping_1()) {
6479 track->mRetryCount = kMaxTrackStopRetriesOffload;
6480 } else {
6481 track->mRetryCount = kMaxTrackRetriesOffload;
6482 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006483 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006484 mixerStatus = MIXER_TRACKS_READY;
6485 }
6486 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006487 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006488 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006489 if (--(track->mRetryCount) <= 0) {
6490 // Hardware buffer can hold a large amount of audio so we must
6491 // wait for all current track's data to drain before we say
6492 // that the track is stopped.
6493 if (mBytesRemaining == 0) {
6494 // Only start draining when all data in mixbuffer
6495 // has been written
6496 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6497 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6498 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6499 if (last && !mStandby) {
6500 // do not modify drain sequence if we are already draining. This happens
6501 // when resuming from pause after drain.
6502 if ((mDrainSequence & 1) == 0) {
6503 mSleepTimeUs = 0;
6504 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6505 mixerStatus = MIXER_DRAIN_TRACK;
6506 mDrainSequence += 2;
6507 }
6508 if (mHwPaused) {
6509 // It is possible to move from PAUSED to STOPPING_1 without
6510 // a resume so we must ensure hardware is running
6511 doHwResume = true;
6512 mHwPaused = false;
6513 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006514 }
6515 }
Eric Laurente93cc032016-05-05 10:15:10 -07006516 } else if (last) {
6517 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6518 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006519 }
6520 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006521 // Drain has completed or we are in standby, signal presentation complete
6522 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006523 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006524 uint32_t latency = 0;
6525 status_t result = mOutput->stream->getLatency(&latency);
6526 ALOGE_IF(result != OK,
6527 "Error when retrieving output stream latency: %d", result);
6528 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006529 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006530 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006531 track->presentationComplete(framesWritten, audioHALFrames);
6532 track->reset();
6533 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006534 // DIRECT and OFFLOADED stop resets frame counts.
6535 if (!mUseAsyncWrite) {
6536 // If we don't get explicit drain notification we must
6537 // register discontinuity regardless of whether this is
6538 // the previous (!last) or the upcoming (last) track
6539 // to avoid skipping the discontinuity.
6540 mTimestampVerifier.discontinuity();
6541 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006542 }
6543 } else {
6544 // No buffers for this track. Give it a few chances to
6545 // fill a buffer, then remove it from active list.
6546 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006547 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006548 uint64_t position = 0;
6549 struct timespec unused;
6550 // The running check restarts the retry counter at least once.
6551 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6552 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6553 running = true;
6554 mOffloadUnderrunPosition = position;
6555 }
6556 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006557 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6558 (long long)position, (long long)mOffloadUnderrunPosition);
6559 }
6560 if (running) { // still running, give us more time.
6561 track->mRetryCount = kMaxTrackRetriesOffload;
6562 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006563 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6564 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006565 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006566 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006567 // it will then automatically call start() when data is available
6568 track->disable();
6569 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006570 } else if (last){
6571 mixerStatus = MIXER_TRACKS_ENABLED;
6572 }
6573 }
6574 }
6575 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006576 if (track->isReady()) { // check ready to prevent premature start.
6577 processVolume_l(track, last);
6578 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006579 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006580
Eric Laurentea0fade2013-10-04 16:23:48 -07006581 // make sure the pause/flush/resume sequence is executed in the right order.
6582 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6583 // before flush and then resume HW. This can happen in case of pause/flush/resume
6584 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006585 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006586 status_t result = mOutput->stream->pause();
6587 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006588 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006589 if (mFlushPending) {
6590 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006591 }
Eric Laurentfd477972013-10-25 18:10:40 -07006592 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006593 status_t result = mOutput->stream->resume();
6594 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006595 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006596
Eric Laurentbfb1b832013-01-07 09:53:42 -08006597 // remove all the tracks that need to be...
6598 removeTracks_l(*tracksToRemove);
6599
6600 return mixerStatus;
6601}
6602
Eric Laurentbfb1b832013-01-07 09:53:42 -08006603// must be called with thread mutex locked
6604bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6605{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006606 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6607 mWriteAckSequence, mDrainSequence);
6608 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006609 return true;
6610 }
6611 return false;
6612}
6613
Eric Laurentbfb1b832013-01-07 09:53:42 -08006614bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6615{
6616 Mutex::Autolock _l(mLock);
6617 return waitingAsyncCallback_l();
6618}
6619
6620void AudioFlinger::OffloadThread::flushHw_l()
6621{
Eric Laurente659ef42014-09-29 13:06:46 -07006622 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006623 // Flush anything still waiting in the mixbuffer
6624 mCurrentWriteLength = 0;
6625 mBytesRemaining = 0;
6626 mPausedWriteLength = 0;
6627 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006628 // reset bytes written count to reflect that DSP buffers are empty after flush.
6629 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006630 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006631
Eric Laurentbfb1b832013-01-07 09:53:42 -08006632 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006633 // discard any pending drain or write ack by incrementing sequence
6634 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6635 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006636 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006637 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6638 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006639 }
6640}
6641
Haynes Mathew George05317d22016-05-03 16:34:26 -07006642void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6643{
6644 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006645 if (PlaybackThread::invalidateTracks_l(streamType)) {
6646 mFlushPending = true;
6647 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006648}
6649
Eric Laurentbfb1b832013-01-07 09:53:42 -08006650// ----------------------------------------------------------------------------
6651
Eric Laurent81784c32012-11-19 14:55:58 -08006652AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006653 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006654 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006655 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006656 mWaitTimeMs(UINT_MAX)
6657{
6658 addOutputTrack(mainThread);
6659}
6660
6661AudioFlinger::DuplicatingThread::~DuplicatingThread()
6662{
6663 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6664 mOutputTracks[i]->destroy();
6665 }
6666}
6667
6668void AudioFlinger::DuplicatingThread::threadLoop_mix()
6669{
6670 // mix buffers...
6671 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006672 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006673 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006674 if (mMixerBufferValid) {
6675 memset(mMixerBuffer, 0, mMixerBufferSize);
6676 } else {
6677 memset(mSinkBuffer, 0, mSinkBufferSize);
6678 }
Eric Laurent81784c32012-11-19 14:55:58 -08006679 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006680 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006681 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006682 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006683 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006684}
6685
6686void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6687{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006688 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006689 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006690 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006691 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006692 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006693 }
6694 } else if (mBytesWritten != 0) {
6695 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6696 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006697 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006698 } else {
6699 // flush remaining overflow buffers in output tracks
6700 writeFrames = 0;
6701 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006702 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006703 }
6704}
6705
Eric Laurentbfb1b832013-01-07 09:53:42 -08006706ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006707{
6708 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006709 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6710
6711 // Consider the first OutputTrack for timestamp and frame counting.
6712
6713 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6714 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6715 // we always claim success.
6716 if (i == 0) {
6717 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6718 ALOGD_IF(correction != 0 && writeFrames != 0,
6719 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6720 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6721 mFramesWritten -= correction;
6722 }
6723
6724 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006725 }
Andy Hungcf10d742020-04-28 15:38:24 -07006726 if (mStandby) {
6727 mThreadMetrics.logBeginInterval();
6728 mStandby = false;
6729 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006730 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006731}
6732
6733void AudioFlinger::DuplicatingThread::threadLoop_standby()
6734{
6735 // DuplicatingThread implements standby by stopping all tracks
6736 for (size_t i = 0; i < outputTracks.size(); i++) {
6737 outputTracks[i]->stop();
6738 }
6739}
6740
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006741void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006742{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006743 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006744
6745 std::stringstream ss;
6746 const size_t numTracks = mOutputTracks.size();
6747 ss << " " << numTracks << " OutputTracks";
6748 if (numTracks > 0) {
6749 ss << ":";
6750 for (const auto &track : mOutputTracks) {
6751 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006752 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006753 if (thread.get() != nullptr) {
6754 ss << thread.get() << ", " << thread->id();
6755 } else {
6756 ss << "null";
6757 }
6758 ss << ")";
6759 }
6760 }
6761 ss << "\n";
6762 std::string result = ss.str();
6763 write(fd, result.c_str(), result.size());
6764}
6765
Eric Laurent81784c32012-11-19 14:55:58 -08006766void AudioFlinger::DuplicatingThread::saveOutputTracks()
6767{
6768 outputTracks = mOutputTracks;
6769}
6770
6771void AudioFlinger::DuplicatingThread::clearOutputTracks()
6772{
6773 outputTracks.clear();
6774}
6775
6776void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6777{
6778 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006779 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6780 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6781 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6782 const size_t frameCount =
6783 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6784 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6785 // from different OutputTracks and their associated MixerThreads (e.g. one may
6786 // nearly empty and the other may be dropping data).
6787
6788 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006789 this,
6790 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006791 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006792 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006793 frameCount,
6794 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006795 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6796 if (status != NO_ERROR) {
6797 ALOGE("addOutputTrack() initCheck failed %d", status);
6798 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006799 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006800 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6801 mOutputTracks.add(outputTrack);
6802 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6803 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006804}
6805
6806void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6807{
6808 Mutex::Autolock _l(mLock);
6809 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6810 if (mOutputTracks[i]->thread() == thread) {
6811 mOutputTracks[i]->destroy();
6812 mOutputTracks.removeAt(i);
6813 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006814 if (thread->getOutput() == mOutput) {
6815 mOutput = NULL;
6816 }
Eric Laurent81784c32012-11-19 14:55:58 -08006817 return;
6818 }
6819 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006820 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006821}
6822
6823// caller must hold mLock
6824void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6825{
6826 mWaitTimeMs = UINT_MAX;
6827 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6828 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6829 if (strong != 0) {
6830 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6831 if (waitTimeMs < mWaitTimeMs) {
6832 mWaitTimeMs = waitTimeMs;
6833 }
6834 }
6835 }
6836}
6837
6838
6839bool AudioFlinger::DuplicatingThread::outputsReady(
6840 const SortedVector< sp<OutputTrack> > &outputTracks)
6841{
6842 for (size_t i = 0; i < outputTracks.size(); i++) {
6843 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6844 if (thread == 0) {
6845 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6846 outputTracks[i].get());
6847 return false;
6848 }
6849 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6850 // see note at standby() declaration
6851 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6852 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6853 thread.get());
6854 return false;
6855 }
6856 }
6857 return true;
6858}
6859
Kevin Rocard12381092018-04-11 09:19:59 -07006860void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6861 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006862{
Kevin Rocard12381092018-04-11 09:19:59 -07006863 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6864 outputTrack->setMetadatas(metadata.tracks);
6865 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006866}
6867
Eric Laurent81784c32012-11-19 14:55:58 -08006868uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6869{
6870 return (mWaitTimeMs * 1000) / 2;
6871}
6872
6873void AudioFlinger::DuplicatingThread::cacheParameters_l()
6874{
6875 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6876 updateWaitTime_l();
6877
6878 MixerThread::cacheParameters_l();
6879}
6880
Eric Laurent6acd1d42017-01-04 14:23:29 -08006881
Eric Laurent81784c32012-11-19 14:55:58 -08006882// ----------------------------------------------------------------------------
6883// Record
6884// ----------------------------------------------------------------------------
6885
6886AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6887 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006888 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006889 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006890 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006891 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006892 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006893 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006894 mActiveTracks(&this->mLocalLog),
6895 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006896 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006897 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006898 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6899 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006900 // mFastCapture below
6901 , mFastCaptureFutex(0)
6902 // mInputSource
6903 // mPipeSink
6904 // mPipeSource
6905 , mPipeFramesP2(0)
6906 // mPipeMemory
6907 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006908 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006909 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006910{
Glenn Kastend7dca052015-03-05 16:05:54 -08006911 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6912 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006913
George Burgess IVa8f90c12020-05-14 11:27:19 -07006914 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07006915 mIsMsdDevice = strcmp(
6916 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6917 }
6918
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006919 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006920
Andy Hungc8fddf32018-08-08 18:32:37 -07006921 // TODO: We may also match on address as well as device type for
6922 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07006923 // TODO: This property should be ensure that only contains one single device type.
6924 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6925 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006926 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6927 : AUDIO_DEVICE_NONE));
6928
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006929 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006930 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006931 size_t numCounterOffers = 0;
6932 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006933#if !LOG_NDEBUG
6934 ssize_t index =
6935#else
6936 (void)
6937#endif
6938 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006939 ALOG_ASSERT(index == 0);
6940
6941 // initialize fast capture depending on configuration
6942 bool initFastCapture;
6943 switch (kUseFastCapture) {
6944 case FastCapture_Never:
6945 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006946 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006947 break;
6948 case FastCapture_Always:
6949 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006950 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006951 break;
6952 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006953 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006954 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6955 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6956 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006957 break;
6958 // case FastCapture_Dynamic:
6959 }
6960
6961 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006962 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006963 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006964 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6965 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006966 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006967 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006968 const sp<MemoryDealer> roHeap(readOnlyHeap());
6969 sp<IMemory> pipeMemory;
6970 if ((roHeap == 0) ||
6971 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07006972 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006973 ALOGE("not enough memory for pipe buffer size=%zu; "
6974 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6975 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6976 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006977 goto failed;
6978 }
6979 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6980 memset(pipeBuffer, 0, pipeSize);
6981 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6982 const NBAIO_Format offers[1] = {format};
6983 size_t numCounterOffers = 0;
6984 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6985 ALOG_ASSERT(index == 0);
6986 mPipeSink = pipe;
6987 PipeReader *pipeReader = new PipeReader(*pipe);
6988 numCounterOffers = 0;
6989 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6990 ALOG_ASSERT(index == 0);
6991 mPipeSource = pipeReader;
6992 mPipeFramesP2 = pipeFramesP2;
6993 mPipeMemory = pipeMemory;
6994
6995 // create fast capture
6996 mFastCapture = new FastCapture();
6997 FastCaptureStateQueue *sq = mFastCapture->sq();
6998#ifdef STATE_QUEUE_DUMP
6999 // FIXME
7000#endif
7001 FastCaptureState *state = sq->begin();
7002 state->mCblk = NULL;
7003 state->mInputSource = mInputSource.get();
7004 state->mInputSourceGen++;
7005 state->mPipeSink = pipe;
7006 state->mPipeSinkGen++;
7007 state->mFrameCount = mFrameCount;
7008 state->mCommand = FastCaptureState::COLD_IDLE;
7009 // already done in constructor initialization list
7010 //mFastCaptureFutex = 0;
7011 state->mColdFutexAddr = &mFastCaptureFutex;
7012 state->mColdGen++;
7013 state->mDumpState = &mFastCaptureDumpState;
7014#ifdef TEE_SINK
7015 // FIXME
7016#endif
7017 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7018 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7019 sq->end();
7020 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7021
7022 // start the fast capture
7023 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7024 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007025 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007026 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007027#ifdef AUDIO_WATCHDOG
7028 // FIXME
7029#endif
7030
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007031 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007032 }
Andy Hung8946a282018-04-19 20:04:56 -07007033#ifdef TEE_SINK
7034 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7035 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7036#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007037failed: ;
7038
7039 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007040}
7041
Eric Laurent81784c32012-11-19 14:55:58 -08007042AudioFlinger::RecordThread::~RecordThread()
7043{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007044 if (mFastCapture != 0) {
7045 FastCaptureStateQueue *sq = mFastCapture->sq();
7046 FastCaptureState *state = sq->begin();
7047 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7048 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7049 if (old == -1) {
7050 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7051 }
7052 }
7053 state->mCommand = FastCaptureState::EXIT;
7054 sq->end();
7055 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7056 mFastCapture->join();
7057 mFastCapture.clear();
7058 }
7059 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007060 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007061 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007062}
7063
7064void AudioFlinger::RecordThread::onFirstRef()
7065{
Glenn Kastend7dca052015-03-05 16:05:54 -08007066 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007067}
7068
Eric Laurent555530a2017-02-07 18:17:24 -08007069void AudioFlinger::RecordThread::preExit()
7070{
7071 ALOGV(" preExit()");
7072 Mutex::Autolock _l(mLock);
7073 for (size_t i = 0; i < mTracks.size(); i++) {
7074 sp<RecordTrack> track = mTracks[i];
7075 track->invalidate();
7076 }
7077 mActiveTracks.clear();
7078 mStartStopCond.broadcast();
7079}
7080
Eric Laurent81784c32012-11-19 14:55:58 -08007081bool AudioFlinger::RecordThread::threadLoop()
7082{
Eric Laurent81784c32012-11-19 14:55:58 -08007083 nsecs_t lastWarning = 0;
7084
7085 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007086
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007087reacquire_wakelock:
7088 sp<RecordTrack> activeTrack;
7089 {
7090 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007091 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007092 }
7093
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007094 // used to request a deferred sleep, to be executed later while mutex is unlocked
7095 uint32_t sleepUs = 0;
7096
Andy Hung446f4df2019-02-21 12:26:41 -08007097 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7098
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007099 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007100 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007101 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007102
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007103 // activeTracks accumulates a copy of a subset of mActiveTracks
7104 Vector< sp<RecordTrack> > activeTracks;
7105
Glenn Kasten735f45f2014-08-18 15:51:59 -07007106 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007107 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007108
Glenn Kasten735f45f2014-08-18 15:51:59 -07007109 // reference to a fast track which is about to be removed
7110 sp<RecordTrack> fastTrackToRemove;
7111
Eric Laurent33403f02020-05-29 18:35:06 -07007112 bool silenceFastCapture = false;
7113
Eric Laurent81784c32012-11-19 14:55:58 -08007114 { // scope for mLock
7115 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007116
Eric Laurent021cf962014-05-13 10:18:14 -07007117 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007118
Eric Laurent000a4192014-01-29 15:17:32 -08007119 // check exitPending here because checkForNewParameters_l() and
7120 // checkForNewParameters_l() can temporarily release mLock
7121 if (exitPending()) {
7122 break;
7123 }
7124
Eric Laurent5c25d562016-07-13 17:17:45 -07007125 // sleep with mutex unlocked
7126 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007127 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007128 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7129 ATRACE_END();
7130 sleepUs = 0;
7131 continue;
7132 }
7133
Glenn Kasten2b806402013-11-20 16:37:38 -08007134 // if no active track(s), then standby and release wakelock
7135 size_t size = mActiveTracks.size();
7136 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007137 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007138 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007139 releaseWakeLock_l();
7140 ALOGV("RecordThread: loop stopping");
7141 // go to sleep
7142 mWaitWorkCV.wait(mLock);
7143 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007144 goto reacquire_wakelock;
7145 }
7146
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007147 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007148 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007149 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007150
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007151 activeTrack = mActiveTracks[i];
7152 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007153 if (activeTrack->isFastTrack()) {
7154 ALOG_ASSERT(fastTrackToRemove == 0);
7155 fastTrackToRemove = activeTrack;
7156 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007157 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007158 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007159 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007160 continue;
7161 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007162
7163 TrackBase::track_state activeTrackState = activeTrack->mState;
7164 switch (activeTrackState) {
7165
7166 case TrackBase::PAUSING:
7167 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007168 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007169 doBroadcast = true;
7170 size--;
7171 continue;
7172
7173 case TrackBase::STARTING_1:
7174 sleepUs = 10000;
7175 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007176 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007177 continue;
7178
7179 case TrackBase::STARTING_2:
7180 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007181 if (mStandby) {
7182 mThreadMetrics.logBeginInterval();
7183 mStandby = false;
7184 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007185 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007186 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007187 break;
7188
7189 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007190 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007191 break;
7192
Andy Hungce685402018-10-05 17:23:27 -07007193 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7194 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7195 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007196 default:
Andy Hungce685402018-10-05 17:23:27 -07007197 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7198 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007199 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007200
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007201 if (activeTrack->isFastTrack()) {
7202 ALOG_ASSERT(!mFastTrackAvail);
7203 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007204 // if the active fast track is silenced either:
7205 // 1) silence the whole capture from fast capture buffer if this is
7206 // the only active track
7207 // 2) invalidate this track: this will cause the client to reconnect and possibly
7208 // be invalidated again until unsilenced
7209 if (activeTrack->isSilenced()) {
7210 if (size > 1) {
7211 activeTrack->invalidate();
7212 ALOG_ASSERT(fastTrackToRemove == 0);
7213 fastTrackToRemove = activeTrack;
7214 removeTrack_l(activeTrack);
7215 mActiveTracks.remove(activeTrack);
7216 size--;
7217 continue;
7218 } else {
7219 silenceFastCapture = true;
7220 }
7221 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007222 fastTrack = activeTrack;
7223 }
Eric Laurent33403f02020-05-29 18:35:06 -07007224
7225 activeTracks.add(activeTrack);
7226 i++;
7227
Glenn Kasten9e982352013-08-14 14:39:50 -07007228 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007229
Andy Hungdae27702016-10-31 14:01:16 -07007230 mActiveTracks.updatePowerState(this);
7231
Kevin Rocard069c2712018-03-29 19:09:14 -07007232 updateMetadata_l();
7233
Eric Laurent5c25d562016-07-13 17:17:45 -07007234 if (allStopped) {
7235 standbyIfNotAlreadyInStandby();
7236 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007237 if (doBroadcast) {
7238 mStartStopCond.broadcast();
7239 }
7240
7241 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007242 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007243 if (sleepUs == 0) {
7244 sleepUs = kRecordThreadSleepUs;
7245 }
7246 continue;
7247 }
7248 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007249
Eric Laurent81784c32012-11-19 14:55:58 -08007250 lockEffectChains_l(effectChains);
7251 }
7252
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007253 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007254
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007255 size_t size = effectChains.size();
7256 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007257 // thread mutex is not locked, but effect chain is locked
7258 effectChains[i]->process_l();
7259 }
7260
Glenn Kasten735f45f2014-08-18 15:51:59 -07007261 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007262 if (mFastCapture != 0) {
7263 FastCaptureStateQueue *sq = mFastCapture->sq();
7264 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007265 bool didModify = false;
7266 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007267 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7268 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7269 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7270 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7271 if (old == -1) {
7272 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7273 }
7274 }
7275 state->mCommand = FastCaptureState::READ_WRITE;
7276#if 0 // FIXME
7277 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007278 FastThreadDumpState::kSamplingNforLowRamDevice :
7279 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007280#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007281 didModify = true;
7282 }
7283 audio_track_cblk_t *cblkOld = state->mCblk;
7284 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7285 if (cblkNew != cblkOld) {
7286 state->mCblk = cblkNew;
7287 // block until acked if removing a fast track
7288 if (cblkOld != NULL) {
7289 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7290 }
7291 didModify = true;
7292 }
jiabin01c8f562018-07-19 17:47:28 -07007293 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7294 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7295 if (state->mFastPatchRecordBufferProvider != abp) {
7296 state->mFastPatchRecordBufferProvider = abp;
7297 state->mFastPatchRecordFormat = fastTrack == 0 ?
7298 AUDIO_FORMAT_INVALID : fastTrack->format();
7299 didModify = true;
7300 }
Eric Laurent33403f02020-05-29 18:35:06 -07007301 if (state->mSilenceCapture != silenceFastCapture) {
7302 state->mSilenceCapture = silenceFastCapture;
7303 didModify = true;
7304 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007305 sq->end(didModify);
7306 if (didModify) {
7307 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007308#if 0
7309 if (kUseFastCapture == FastCapture_Dynamic) {
7310 mNormalSource = mPipeSource;
7311 }
7312#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007313 }
7314 }
7315
Glenn Kasten735f45f2014-08-18 15:51:59 -07007316 // now run the fast track destructor with thread mutex unlocked
7317 fastTrackToRemove.clear();
7318
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007319 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7320 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7321 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7322 // If destination is non-contiguous, first read past the nominal end of buffer, then
7323 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007324
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007325 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007326 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007327 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007328
7329 // If an NBAIO source is present, use it to read the normal capture's data
7330 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007331 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007332
7333 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7334 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7335 // we immediately retry the read() to get data and prevent another overflow.
7336 for (int retries = 0; retries <= 2; ++retries) {
7337 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7338 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7339 framesToRead);
7340 if (framesRead != OVERRUN) break;
7341 }
7342
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007343 const ssize_t availableToRead = mPipeSource->availableToRead();
7344 if (availableToRead >= 0) {
7345 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
7346 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7347 "more frames to read than fifo size, %zd > %zu",
7348 availableToRead, mPipeFramesP2);
7349 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7350 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7351 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7352 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007353 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7354 }
7355 if (framesRead < 0) {
7356 status_t status = (status_t) framesRead;
7357 switch (status) {
7358 case OVERRUN:
7359 ALOGW("overrun on read from pipe");
7360 framesRead = 0;
7361 break;
7362 case NEGOTIATE:
7363 ALOGE("re-negotiation is needed");
7364 framesRead = -1; // Will cause an attempt to recover.
7365 break;
7366 default:
7367 ALOGE("unknown error %d on read from pipe", status);
7368 break;
7369 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007370 }
7371 // otherwise use the HAL / AudioStreamIn directly
7372 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007373 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007374 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007375 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007376 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007377 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007378 if (result < 0) {
7379 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007380 } else {
7381 framesRead = bytesRead / mFrameSize;
7382 }
7383 }
7384
Andy Hung446f4df2019-02-21 12:26:41 -08007385 const int64_t lastIoEndNs = systemTime(); // end IO timing
7386
Andy Hung3f0c9022016-01-15 17:49:46 -08007387 // Update server timestamp with server stats
7388 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007389 if (framesRead >= 0) {
7390 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7391 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7392 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007393
7394 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007395 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007396 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007397 if (mStandby) {
7398 mTimestampVerifier.discontinuity();
Mikhail Naganov2534b382019-09-25 13:05:02 -07007399 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007400 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7401
7402 mTimestampVerifier.add(position, time, mSampleRate);
7403
7404 // Correct timestamps
7405 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007406 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007407 id(), (long long)time, (long long)position);
7408 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7409 position = correctedTimestamp.mFrames;
7410 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007411 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007412 id(), (long long)time, (long long)position);
7413 }
7414
Andy Hung3f0c9022016-01-15 17:49:46 -08007415 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7416 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7417 // Note: In general record buffers should tend to be empty in
7418 // a properly running pipeline.
7419 //
7420 // Also, it is not advantageous to call get_presentation_position during the read
7421 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007422 } else {
7423 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007424 }
7425 }
Andy Hunge6c37112019-02-26 17:38:10 -08007426
7427 // From the timestamp, input read latency is negative output write latency.
7428 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7429 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7430 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7431 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7432 mLatencyMs.add(latencyMs);
7433 }
7434
Andy Hung3f0c9022016-01-15 17:49:46 -08007435 // Use this to track timestamp information
7436 // ALOGD("%s", mTimestamp.toString().c_str());
7437
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007438 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007439 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007440 // Force input into standby so that it tries to recover at next read attempt
7441 inputStandBy();
7442 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007443 }
7444 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007445 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007446 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007447 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007448 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007449
Andy Hung8946a282018-04-19 20:04:56 -07007450#ifdef TEE_SINK
7451 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7452#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007453 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007454 {
7455 size_t part1 = mRsmpInFramesP2 - rear;
7456 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007457 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007458 (framesRead - part1) * mFrameSize);
7459 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007460 }
7461 rear = mRsmpInRear += framesRead;
7462
7463 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007464
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007465 // loop over each active track
7466 for (size_t i = 0; i < size; i++) {
7467 activeTrack = activeTracks[i];
7468
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007469 // skip fast tracks, as those are handled directly by FastCapture
7470 if (activeTrack->isFastTrack()) {
7471 continue;
7472 }
7473
Andy Hung73c02e42015-03-29 01:13:58 -07007474 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007475 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7476
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007477 enum {
7478 OVERRUN_UNKNOWN,
7479 OVERRUN_TRUE,
7480 OVERRUN_FALSE
7481 } overrun = OVERRUN_UNKNOWN;
7482
7483 // loop over getNextBuffer to handle circular sink
7484 for (;;) {
7485
7486 activeTrack->mSink.frameCount = ~0;
7487 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7488 size_t framesOut = activeTrack->mSink.frameCount;
7489 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7490
Andy Hung73c02e42015-03-29 01:13:58 -07007491 // check available frames and handle overrun conditions
7492 // if the record track isn't draining fast enough.
7493 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007494 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007495 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7496 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007497 overrun = OVERRUN_TRUE;
7498 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007499 if (framesOut == 0 || framesIn == 0) {
7500 break;
7501 }
7502
Andy Hung6770c6f2015-04-07 13:43:36 -07007503 // Don't allow framesOut to be larger than what is possible with resampling
7504 // from framesIn.
7505 // This isn't strictly necessary but helps limit buffer resizing in
7506 // RecordBufferConverter. TODO: remove when no longer needed.
7507 framesOut = min(framesOut,
7508 destinationFramesPossible(
7509 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007510
7511 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007512 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007513 // straight from RecordThread buffer to RecordTrack buffer.
7514 AudioBufferProvider::Buffer buffer;
7515 buffer.frameCount = framesOut;
7516 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7517 if (status == OK && buffer.frameCount != 0) {
7518 ALOGV_IF(buffer.frameCount != framesOut,
7519 "%s() read less than expected (%zu vs %zu)",
7520 __func__, buffer.frameCount, framesOut);
7521 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007522 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007523 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7524 } else {
7525 framesOut = 0;
7526 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7527 __func__, status, buffer.frameCount);
7528 }
7529 } else {
7530 // process frames from the RecordThread buffer provider to the RecordTrack
7531 // buffer
7532 framesOut = activeTrack->mRecordBufferConverter->convert(
7533 activeTrack->mSink.raw,
7534 activeTrack->mResamplerBufferProvider,
7535 framesOut);
7536 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007537
7538 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7539 overrun = OVERRUN_FALSE;
7540 }
7541
7542 if (activeTrack->mFramesToDrop == 0) {
7543 if (framesOut > 0) {
7544 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007545 // Sanitize before releasing if the track has no access to the source data
7546 // An idle UID receives silence from non virtual devices until active
7547 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007548 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007549 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007550 activeTrack->releaseBuffer(&activeTrack->mSink);
7551 }
7552 } else {
7553 // FIXME could do a partial drop of framesOut
7554 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007555 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007556 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007557 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007558 }
7559 } else {
7560 activeTrack->mFramesToDrop += framesOut;
7561 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7562 activeTrack->mSyncStartEvent->isCancelled()) {
7563 ALOGW("Synced record %s, session %d, trigger session %d",
7564 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7565 activeTrack->sessionId(),
7566 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007567 activeTrack->mSyncStartEvent->triggerSession() :
7568 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007569 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007570 }
7571 }
7572 }
7573
7574 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007575 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007576 }
7577 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007578
7579 switch (overrun) {
7580 case OVERRUN_TRUE:
7581 // client isn't retrieving buffers fast enough
7582 if (!activeTrack->setOverflow()) {
7583 nsecs_t now = systemTime();
7584 // FIXME should lastWarning per track?
7585 if ((now - lastWarning) > kWarningThrottleNs) {
7586 ALOGW("RecordThread: buffer overflow");
7587 lastWarning = now;
7588 }
7589 }
7590 break;
7591 case OVERRUN_FALSE:
7592 activeTrack->clearOverflow();
7593 break;
7594 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007595 break;
7596 }
7597
Andy Hung3f0c9022016-01-15 17:49:46 -08007598 // update frame information and push timestamp out
7599 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007600 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007601 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7602 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007603 }
7604
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007605unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007606 // enable changes in effect chain
7607 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007608 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007609 if (audio_has_proportional_frames(mFormat)
7610 && loopCount == lastLoopCountRead + 1) {
7611 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7612 const double jitterMs =
7613 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7614 {framesRead, readPeriodNs},
7615 {0, 0} /* lastTimestamp */, mSampleRate);
7616 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7617
7618 Mutex::Autolock _l(mLock);
7619 mIoJitterMs.add(jitterMs);
7620 mProcessTimeMs.add(processMs);
7621 }
7622 // update timing info.
7623 mLastIoBeginNs = lastIoBeginNs;
7624 mLastIoEndNs = lastIoEndNs;
7625 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007626 }
7627
Glenn Kasten93e471f2013-08-19 08:40:07 -07007628 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007629
7630 {
7631 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007632 for (size_t i = 0; i < mTracks.size(); i++) {
7633 sp<RecordTrack> track = mTracks[i];
7634 track->invalidate();
7635 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007636 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007637 mStartStopCond.broadcast();
7638 }
7639
7640 releaseWakeLock();
7641
7642 ALOGV("RecordThread %p exiting", this);
7643 return false;
7644}
7645
Glenn Kasten93e471f2013-08-19 08:40:07 -07007646void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007647{
7648 if (!mStandby) {
7649 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007650 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007651 mStandby = true;
7652 }
7653}
7654
7655void AudioFlinger::RecordThread::inputStandBy()
7656{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007657 // Idle the fast capture if it's currently running
7658 if (mFastCapture != 0) {
7659 FastCaptureStateQueue *sq = mFastCapture->sq();
7660 FastCaptureState *state = sq->begin();
7661 if (!(state->mCommand & FastCaptureState::IDLE)) {
7662 state->mCommand = FastCaptureState::COLD_IDLE;
7663 state->mColdFutexAddr = &mFastCaptureFutex;
7664 state->mColdGen++;
7665 mFastCaptureFutex = 0;
7666 sq->end();
7667 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7668 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7669#if 0
7670 if (kUseFastCapture == FastCapture_Dynamic) {
7671 // FIXME
7672 }
7673#endif
7674#ifdef AUDIO_WATCHDOG
7675 // FIXME
7676#endif
7677 } else {
7678 sq->end(false /*didModify*/);
7679 }
7680 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007681 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007682 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007683
7684 // If going into standby, flush the pipe source.
7685 if (mPipeSource.get() != nullptr) {
7686 const ssize_t flushed = mPipeSource->flush();
7687 if (flushed > 0) {
7688 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7689 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7690 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7691 }
7692 }
Eric Laurent81784c32012-11-19 14:55:58 -08007693}
7694
Glenn Kasten05997e22014-03-13 15:08:33 -07007695// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007696sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007697 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007698 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007699 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007700 audio_format_t format,
7701 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007702 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007703 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007704 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007705 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007706 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007707 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007708 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007709 status_t *status,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007710 audio_port_handle_t portId,
7711 const String16& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08007712{
Glenn Kasten74935e42013-12-19 08:56:45 -08007713 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007714 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007715 sp<RecordTrack> track;
7716 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007717 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007718 audio_input_flags_t requestedFlags = *flags;
7719 uint32_t sampleRate;
7720
7721 lStatus = initCheck();
7722 if (lStatus != NO_ERROR) {
7723 ALOGE("createRecordTrack_l() audio driver not initialized");
7724 goto Exit;
7725 }
7726
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007727 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7728 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7729 lStatus = BAD_VALUE;
7730 goto Exit;
7731 }
7732
Eric Laurentf14db3c2017-12-08 14:20:36 -08007733 if (*pSampleRate == 0) {
7734 *pSampleRate = mSampleRate;
7735 }
7736 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007737
7738 // special case for FAST flag considered OK if fast capture is present
7739 if (hasFastCapture()) {
7740 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7741 }
7742
Eric Laurentf14db3c2017-12-08 14:20:36 -08007743 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007744 if ((*flags & inputFlags) != *flags) {
7745 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7746 " input flags (%08x)",
7747 *flags, inputFlags);
7748 *flags = (audio_input_flags_t)(*flags & inputFlags);
7749 }
Eric Laurent81784c32012-11-19 14:55:58 -08007750
Glenn Kasten90e58b12013-07-31 16:16:02 -07007751 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007752 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007753 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007754 // we formerly checked for a callback handler (non-0 tid),
7755 // but that is no longer required for TRANSFER_OBTAIN mode
7756 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007757 // Frame count is not specified (0), or is less than or equal the pipe depth.
7758 // It is OK to provide a higher capacity than requested.
7759 // We will force it to mPipeFramesP2 below.
7760 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007761 // PCM data
7762 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007763 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007764 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007765 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007766 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007767 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007768 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007769 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007770 hasFastCapture() &&
7771 // there are sufficient fast track slots available
7772 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007773 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007774 // check compatibility with audio effects.
7775 Mutex::Autolock _l(mLock);
7776 // Do not accept FAST flag if the session has software effects
7777 sp<EffectChain> chain = getEffectChain_l(sessionId);
7778 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007779 audio_input_flags_t old = *flags;
7780 chain->checkInputFlagCompatibility(flags);
7781 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007782 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7783 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007784 }
7785 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007786 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007787 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7788 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007789 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007790 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7791 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007792 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007793 this, frameCount, mFrameCount, mPipeFramesP2,
7794 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007795 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007796 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007797 }
7798 }
7799
Eric Laurentf14db3c2017-12-08 14:20:36 -08007800 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7801 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7802 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7803 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7804 lStatus = BAD_TYPE;
7805 goto Exit;
7806 }
7807
Glenn Kasten74105912014-07-03 12:28:53 -07007808 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007809 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007810 // fast track: frame count is exactly the pipe depth
7811 frameCount = mPipeFramesP2;
7812 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007813 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007814 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007815 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7816 // or 20 ms if there is a fast capture
7817 // TODO This could be a roundupRatio inline, and const
7818 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7819 * sampleRate + mSampleRate - 1) / mSampleRate;
7820 // minimum number of notification periods is at least kMinNotifications,
7821 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7822 static const size_t kMinNotifications = 3;
7823 static const uint32_t kMinMs = 30;
7824 // TODO This could be a roundupRatio inline
7825 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7826 // TODO This could be a roundupRatio inline
7827 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7828 maxNotificationFrames;
7829 const size_t minFrameCount = maxNotificationFrames *
7830 max(kMinNotifications, minNotificationsByMs);
7831 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007832 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7833 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007834 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007835 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007836 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007837 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007838
7839 { // scope for mLock
7840 Mutex::Autolock _l(mLock);
7841
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007842 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007843 format, channelMask, frameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007844 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, uid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007845 *flags, TrackBase::TYPE_DEFAULT, opPackageName, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007846
Glenn Kasten03003332013-08-06 15:40:54 -07007847 lStatus = track->initCheck();
7848 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007849 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007850 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007851 goto Exit;
7852 }
7853 mTracks.add(track);
7854
Eric Laurent05067782016-06-01 18:27:28 -07007855 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007856 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7857 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7858 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007859 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007860 }
Eric Laurent81784c32012-11-19 14:55:58 -08007861 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007862
Eric Laurent81784c32012-11-19 14:55:58 -08007863 lStatus = NO_ERROR;
7864
7865Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007866 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007867 return track;
7868}
7869
7870status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7871 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007872 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007873{
7874 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7875 sp<ThreadBase> strongMe = this;
7876 status_t status = NO_ERROR;
7877
7878 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007879 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007880 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007881 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007882 triggerSession,
7883 recordTrack->sessionId(),
7884 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007885 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007886 // Sync event can be cancelled by the trigger session if the track is not in a
7887 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007888 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007889 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007890 } else {
7891 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007892 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007893 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007894 }
7895 }
7896
7897 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007898 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007899 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007900 if (recordTrack->isInvalid()) {
7901 recordTrack->clearSyncStartEvent();
7902 return INVALID_OPERATION;
7903 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007904 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7905 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007906 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7907 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007908 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007909 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007910 } else {
7911 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007912 }
7913 return status;
7914 }
7915
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007916 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7917 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7918 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007919 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007920 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007921 status_t status = NO_ERROR;
7922 if (recordTrack->isExternalTrack()) {
7923 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007924 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007925 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007926 if (recordTrack->isInvalid()) {
7927 recordTrack->clearSyncStartEvent();
7928 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7929 recordTrack->mState = TrackBase::STARTING_2;
7930 // STARTING_2 forces destroy to call stopInput.
7931 }
7932 return INVALID_OPERATION;
7933 }
7934 if (recordTrack->mState != TrackBase::STARTING_1) {
7935 ALOGW("%s(%d): unsynchronized mState:%d change",
7936 __func__, recordTrack->id(), recordTrack->mState);
7937 // Someone else has changed state, let them take over,
7938 // leave mState in the new state.
7939 recordTrack->clearSyncStartEvent();
7940 return INVALID_OPERATION;
7941 }
7942 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007943 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007944 ALOGW("%s(%d): startInput failed, status %d",
7945 __func__, recordTrack->id(), status);
7946 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7947 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007948 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007949 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007950 return status;
7951 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07007952 sendIoConfigEvent_l(
7953 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08007954 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07007955
7956 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
7957
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007958 // Catch up with current buffer indices if thread is already running.
7959 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7960 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7961 // see previously buffered data before it called start(), but with greater risk of overrun.
7962
Andy Hung73c02e42015-03-29 01:13:58 -07007963 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007964 if (!recordTrack->isDirect()) {
7965 // clear any converter state as new data will be discontinuous
7966 recordTrack->mRecordBufferConverter->reset();
7967 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007968 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007969 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007970 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007971 return status;
7972 }
Eric Laurent81784c32012-11-19 14:55:58 -08007973}
7974
Eric Laurent81784c32012-11-19 14:55:58 -08007975void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7976{
7977 sp<SyncEvent> strongEvent = event.promote();
7978
7979 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007980 sp<RefBase> ptr = strongEvent->cookie().promote();
7981 if (ptr != 0) {
7982 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7983 recordTrack->handleSyncStartEvent(strongEvent);
7984 }
Eric Laurent81784c32012-11-19 14:55:58 -08007985 }
7986}
7987
Glenn Kastena8356f62013-07-25 14:37:52 -07007988bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007989 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007990 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007991 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007992 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007993 return false;
7994 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007995 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007996 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007997
Andy Hungabfab202019-03-07 19:45:54 -08007998 // NOTE: Waiting here is important to keep stop synchronous.
7999 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008000 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8001 mWaitWorkCV.broadcast(); // signal thread to stop
8002 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008003 }
Andy Hungce685402018-10-05 17:23:27 -07008004
8005 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008006 ALOGV("Record stopped OK");
8007 return true;
8008 }
Andy Hungce685402018-10-05 17:23:27 -07008009
8010 // don't handle anything - we've been invalidated or restarted and in a different state
8011 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8012 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008013 return false;
8014}
8015
Glenn Kasten0f11b512014-01-31 16:18:54 -08008016bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008017{
8018 return false;
8019}
8020
Glenn Kasten0f11b512014-01-31 16:18:54 -08008021status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008022{
8023#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8024 if (!isValidSyncEvent(event)) {
8025 return BAD_VALUE;
8026 }
8027
Glenn Kastend848eb42016-03-08 13:42:11 -08008028 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008029 status_t ret = NAME_NOT_FOUND;
8030
8031 Mutex::Autolock _l(mLock);
8032
8033 for (size_t i = 0; i < mTracks.size(); i++) {
8034 sp<RecordTrack> track = mTracks[i];
8035 if (eventSession == track->sessionId()) {
8036 (void) track->setSyncEvent(event);
8037 ret = NO_ERROR;
8038 }
8039 }
8040 return ret;
8041#else
8042 return BAD_VALUE;
8043#endif
8044}
8045
jiabin653cc0a2018-01-17 17:54:10 -08008046status_t AudioFlinger::RecordThread::getActiveMicrophones(
8047 std::vector<media::MicrophoneInfo>* activeMicrophones)
8048{
8049 ALOGV("RecordThread::getActiveMicrophones");
8050 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07008051 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8052 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008053}
8054
Paul McLean12340082019-03-19 09:35:05 -06008055status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8056 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008057{
Paul McLean12340082019-03-19 09:35:05 -06008058 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008059 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008060 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008061}
8062
Paul McLean12340082019-03-19 09:35:05 -06008063status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008064{
Paul McLean12340082019-03-19 09:35:05 -06008065 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008066 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008067 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008068}
8069
Kevin Rocard069c2712018-03-29 19:09:14 -07008070void AudioFlinger::RecordThread::updateMetadata_l()
8071{
8072 if (mInput == nullptr || mInput->stream == nullptr ||
8073 !mActiveTracks.readAndClearHasChanged()) {
8074 return;
8075 }
8076 StreamInHalInterface::SinkMetadata metadata;
8077 for (const sp<RecordTrack> &track : mActiveTracks) {
8078 // No track is invalid as this is called after prepareTrack_l in the same critical section
8079 metadata.tracks.push_back({
8080 .source = track->attributes().source,
8081 .gain = 1, // capture tracks do not have volumes
8082 });
8083 }
8084 mInput->stream->updateSinkMetadata(metadata);
8085}
8086
Eric Laurent81784c32012-11-19 14:55:58 -08008087// destroyTrack_l() must be called with ThreadBase::mLock held
8088void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8089{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008090 track->terminate();
8091 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08008092 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008093 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008094 removeTrack_l(track);
8095 }
8096}
8097
8098void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8099{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008100 String8 result;
8101 track->appendDump(result, false /* active */);
8102 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8103
Eric Laurent81784c32012-11-19 14:55:58 -08008104 mTracks.remove(track);
8105 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008106 if (track->isFastTrack()) {
8107 ALOG_ASSERT(!mFastTrackAvail);
8108 mFastTrackAvail = true;
8109 }
Eric Laurent81784c32012-11-19 14:55:58 -08008110}
8111
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008112void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008113{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008114 AudioStreamIn *input = mInput;
8115 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8116 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008117 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008118 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008119 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008120 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008121 }
Andy Hungbfa64962017-06-12 14:43:19 -07008122
8123 if (input != nullptr) {
8124 dprintf(fd, " Hal stream dump:\n");
8125 (void)input->stream->dump(fd);
8126 }
8127
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008128 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008129 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008130
Glenn Kasten2f90c512015-12-02 11:40:09 -08008131 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8132 // while we are dumping it. It may be inconsistent, but it won't mutate!
8133 // This is a large object so we place it on the heap.
8134 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008135 const std::unique_ptr<FastCaptureDumpState> copy =
8136 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008137 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008138}
8139
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008140void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008141{
Eric Laurent81784c32012-11-19 14:55:58 -08008142 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008143 size_t numtracks = mTracks.size();
8144 size_t numactive = mActiveTracks.size();
8145 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008146 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008147 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008148 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008149 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008150 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008151 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008152 for (size_t i = 0; i < numtracks ; ++i) {
8153 sp<RecordTrack> track = mTracks[i];
8154 if (track != 0) {
8155 bool active = mActiveTracks.indexOf(track) >= 0;
8156 if (active) {
8157 numactiveseen++;
8158 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008159 result.append(prefix);
8160 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008161 }
Eric Laurent81784c32012-11-19 14:55:58 -08008162 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008163 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008164 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008165 }
8166
Marco Nelissenb2208842014-02-07 14:00:50 -08008167 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008168 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008169 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008170 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008171 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008172 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008173 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008174 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008175 result.append(prefix);
8176 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008177 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008178 }
Eric Laurent81784c32012-11-19 14:55:58 -08008179
8180 }
8181 write(fd, result.string(), result.size());
8182}
8183
Eric Laurent5ada82e2019-08-29 17:53:54 -07008184void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008185{
8186 Mutex::Autolock _l(mLock);
8187 for (size_t i = 0; i < mTracks.size() ; i++) {
8188 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008189 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008190 track->setSilenced(silenced);
8191 }
8192 }
8193}
Andy Hung73c02e42015-03-29 01:13:58 -07008194
8195void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8196{
8197 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8198 RecordThread *recordThread = (RecordThread *) threadBase.get();
8199 mRsmpInFront = recordThread->mRsmpInRear;
8200 mRsmpInUnrel = 0;
8201}
8202
8203void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8204 size_t *framesAvailable, bool *hasOverrun)
8205{
8206 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8207 RecordThread *recordThread = (RecordThread *) threadBase.get();
8208 const int32_t rear = recordThread->mRsmpInRear;
8209 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008210 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008211
8212 size_t framesIn;
8213 bool overrun = false;
8214 if (filled < 0) {
8215 // should not happen, but treat like a massive overrun and re-sync
8216 framesIn = 0;
8217 mRsmpInFront = rear;
8218 overrun = true;
8219 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8220 framesIn = (size_t) filled;
8221 } else {
8222 // client is not keeping up with server, but give it latest data
8223 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008224 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8225 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008226 overrun = true;
8227 }
8228 if (framesAvailable != NULL) {
8229 *framesAvailable = framesIn;
8230 }
8231 if (hasOverrun != NULL) {
8232 *hasOverrun = overrun;
8233 }
8234}
8235
Eric Laurent81784c32012-11-19 14:55:58 -08008236// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008237status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008238 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008239{
Andy Hung73c02e42015-03-29 01:13:58 -07008240 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008241 if (threadBase == 0) {
8242 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008243 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008244 return NOT_ENOUGH_DATA;
8245 }
8246 RecordThread *recordThread = (RecordThread *) threadBase.get();
8247 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008248 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008249 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008250 // FIXME should not be P2 (don't want to increase latency)
8251 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008252 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008253 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008254 front &= recordThread->mRsmpInFramesP2 - 1;
8255 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008256 if (part1 > (size_t) filled) {
8257 part1 = filled;
8258 }
8259 size_t ask = buffer->frameCount;
8260 ALOG_ASSERT(ask > 0);
8261 if (part1 > ask) {
8262 part1 = ask;
8263 }
8264 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008265 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008266 buffer->raw = NULL;
8267 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008268 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008269 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008270 }
8271
Andy Hung57446612015-04-19 23:56:46 -07008272 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008273 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008274 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008275 return NO_ERROR;
8276}
8277
8278// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008279void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8280 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008281{
Hongwei Wang95e37682019-04-12 11:13:36 -07008282 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008283 if (stepCount == 0) {
8284 return;
8285 }
Andy Hung73c02e42015-03-29 01:13:58 -07008286 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8287 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008288 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008289 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008290 buffer->frameCount = 0;
8291}
8292
Eric Laurentd8365c52017-07-16 15:27:05 -07008293void AudioFlinger::RecordThread::checkBtNrec()
8294{
8295 Mutex::Autolock _l(mLock);
8296 checkBtNrec_l();
8297}
8298
8299void AudioFlinger::RecordThread::checkBtNrec_l()
8300{
8301 // disable AEC and NS if the device is a BT SCO headset supporting those
8302 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008303 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008304 mAudioFlinger->btNrecIsOff();
8305 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8306 for (size_t i = 0; i < mEffectChains.size(); i++) {
8307 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8308 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8309 }
8310 }
8311}
8312
Andy Hung97a893e2015-03-29 01:03:07 -07008313
Eric Laurent10351942014-05-08 18:49:52 -07008314bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8315 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008316{
8317 bool reconfig = false;
8318
Eric Laurent10351942014-05-08 18:49:52 -07008319 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008320
Eric Laurent10351942014-05-08 18:49:52 -07008321 audio_format_t reqFormat = mFormat;
8322 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008323 // 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 -07008324 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8325
8326 AudioParameter param = AudioParameter(keyValuePair);
8327 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008328
8329 // scope for AutoPark extends to end of method
8330 AutoPark<FastCapture> park(mFastCapture);
8331
Eric Laurent10351942014-05-08 18:49:52 -07008332 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8333 // channel count change can be requested. Do we mandate the first client defines the
8334 // HAL sampling rate and channel count or do we allow changes on the fly?
8335 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8336 samplingRate = value;
8337 reconfig = true;
8338 }
8339 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008340 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008341 status = BAD_VALUE;
8342 } else {
8343 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008344 reconfig = true;
8345 }
Eric Laurent10351942014-05-08 18:49:52 -07008346 }
8347 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8348 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008349 if (!audio_is_input_channel(mask) ||
8350 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008351 status = BAD_VALUE;
8352 } else {
8353 channelMask = mask;
8354 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008355 }
Eric Laurent10351942014-05-08 18:49:52 -07008356 }
8357 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8358 // do not accept frame count changes if tracks are open as the track buffer
8359 // size depends on frame count and correct behavior would not be guaranteed
8360 // if frame count is changed after track creation
8361 if (mActiveTracks.size() > 0) {
8362 status = INVALID_OPERATION;
8363 } else {
8364 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008365 }
Eric Laurent10351942014-05-08 18:49:52 -07008366 }
8367 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008368 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008369 }
8370 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8371 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008372 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008373 }
Glenn Kastene198c362013-08-13 09:13:36 -07008374
Eric Laurent10351942014-05-08 18:49:52 -07008375 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008376 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008377 if (status == INVALID_OPERATION) {
8378 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008379 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008380 }
8381 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008382 if (status == BAD_VALUE) {
8383 uint32_t sRate;
8384 audio_channel_mask_t channelMask;
8385 audio_format_t format;
8386 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8387 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8388 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8389 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8390 status = NO_ERROR;
8391 }
Eric Laurent81784c32012-11-19 14:55:58 -08008392 }
Eric Laurent10351942014-05-08 18:49:52 -07008393 if (status == NO_ERROR) {
8394 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008395 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008396 }
8397 }
Eric Laurent81784c32012-11-19 14:55:58 -08008398 }
Eric Laurent10351942014-05-08 18:49:52 -07008399
Eric Laurent81784c32012-11-19 14:55:58 -08008400 return reconfig;
8401}
8402
8403String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8404{
Eric Laurent81784c32012-11-19 14:55:58 -08008405 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008406 if (initCheck() == NO_ERROR) {
8407 String8 out_s8;
8408 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8409 return out_s8;
8410 }
Eric Laurent81784c32012-11-19 14:55:58 -08008411 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008412 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008413}
8414
Eric Laurent09f1ed22019-04-24 17:45:17 -07008415void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8416 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008417 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8418
8419 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008420
8421 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008422 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008423 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008424 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008425 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008426 desc->mChannelMask = mChannelMask;
8427 desc->mSamplingRate = mSampleRate;
8428 desc->mFormat = mFormat;
8429 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008430 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008431 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008432 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008433 case AUDIO_CLIENT_STARTED:
8434 desc->mPatch = mPatch;
8435 desc->mPortId = portId;
8436 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008437 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008438 default:
8439 break;
8440 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008441 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008442}
8443
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008444void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008445{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008446 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8447 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008448 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008449 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8450 if (audio_is_linear_pcm(mFormat)) {
8451 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8452 mChannelCount, FCC_8);
8453 } else {
8454 // Can have more that FCC_8 channels in encoded streams.
8455 ALOGI("HAL format %#x is not linear pcm", mFormat);
8456 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008457 result = mInput->stream->getFrameSize(&mFrameSize);
8458 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008459 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8460 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008461 result = mInput->stream->getBufferSize(&mBufferSize);
8462 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008463 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008464 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8465 "mBufferSize=%zu, mFrameCount=%zu",
8466 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008467 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008468 // 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 -07008469 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008470 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008471 // A larger value should allow more old data to be read after a track calls start(),
8472 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008473 //
8474 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008475 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008476 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008477 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008478 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008479
8480 // TODO optimize audio capture buffer sizes ...
8481 // Here we calculate the size of the sliding buffer used as a source
8482 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8483 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8484 // be better to have it derived from the pipe depth in the long term.
8485 // The current value is higher than necessary. However it should not add to latency.
8486
Glenn Kasten85948432013-08-19 12:09:05 -07008487 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008488 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8489 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008490 // if posix_memalign fails, will segv here.
8491 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008492
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008493 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8494 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008495
8496 audio_input_flags_t flags = mInput->flags;
8497 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8498 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8499 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8500 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8501 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8502 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8503 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8504 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8505 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008506}
8507
Glenn Kasten5f972c02014-01-13 09:59:31 -08008508uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008509{
8510 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008511 uint32_t result;
8512 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8513 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008514 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008515 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008516}
8517
Glenn Kastend848eb42016-03-08 13:42:11 -08008518KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008519{
Glenn Kastend848eb42016-03-08 13:42:11 -08008520 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008521 Mutex::Autolock _l(mLock);
8522 for (size_t j = 0; j < mTracks.size(); ++j) {
8523 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008524 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008525 if (ids.indexOfKey(sessionId) < 0) {
8526 ids.add(sessionId, true);
8527 }
8528 }
8529 return ids;
8530}
8531
8532AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8533{
8534 Mutex::Autolock _l(mLock);
8535 AudioStreamIn *input = mInput;
8536 mInput = NULL;
8537 return input;
8538}
8539
8540// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008541sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008542{
8543 if (mInput == NULL) {
8544 return NULL;
8545 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008546 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008547}
8548
8549status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8550{
Eric Laurent81784c32012-11-19 14:55:58 -08008551 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008552 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008553 chain->setInBuffer(NULL);
8554 chain->setOutBuffer(NULL);
8555
8556 checkSuspendOnAddEffectChain_l(chain);
8557
Eric Laurent1b928682014-10-02 19:41:47 -07008558 // make sure enabled pre processing effects state is communicated to the HAL as we
8559 // just moved them to a new input stream.
8560 chain->syncHalEffectsState();
8561
Eric Laurent81784c32012-11-19 14:55:58 -08008562 mEffectChains.add(chain);
8563
8564 return NO_ERROR;
8565}
8566
8567size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8568{
8569 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008570
8571 for (size_t i = 0; i < mEffectChains.size(); i++) {
8572 if (chain == mEffectChains[i]) {
8573 mEffectChains.removeAt(i);
8574 break;
8575 }
Eric Laurent81784c32012-11-19 14:55:58 -08008576 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008577 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008578}
8579
Eric Laurent1c333e22014-05-20 10:48:17 -07008580status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8581 audio_patch_handle_t *handle)
8582{
8583 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008584
8585 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008586 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8587 mInDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
François Gaffie0c280aa2018-07-25 10:02:15 +02008588 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008589 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008590 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008591 }
8592
Eric Laurentd8365c52017-07-16 15:27:05 -07008593 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008594
8595 // store new source and send to effects
8596 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8597 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008598 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008599 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008600 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008601 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008602
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008603 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008604 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8605 status = hwDevice->createAudioPatch(patch->num_sources,
8606 patch->sources,
8607 patch->num_sinks,
8608 patch->sinks,
8609 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008610 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008611 char *address;
8612 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8613 address = audio_device_address_to_parameter(
8614 patch->sources[0].ext.device.type,
8615 patch->sources[0].ext.device.address);
8616 } else {
8617 address = (char *)calloc(1, 1);
8618 }
8619 AudioParameter param = AudioParameter(String8(address));
8620 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008621 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008622 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008623 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008624 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008625 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008626 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008627 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008628
jiabinc52b1ff2019-10-31 17:20:42 -07008629 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008630 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008631 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008632 }
Eric Laurent296fb132015-05-01 11:38:42 -07008633
Andy Hungc2b11cb2020-04-22 09:04:01 -07008634 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008635 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008636 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008637 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008638 // also dispatch to active AudioRecords
8639 for (const auto &track : mActiveTracks) {
8640 track->logEndInterval();
8641 track->logBeginInterval(pathSourcesAsString);
8642 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008643 return status;
8644}
8645
8646status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8647{
8648 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008649
jiabinc52b1ff2019-10-31 17:20:42 -07008650 mPatch = audio_patch{};
8651 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008652
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008653 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008654 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8655 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008656 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008657 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008658 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008659 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008660 }
8661 return status;
8662}
8663
jiabinc52b1ff2019-10-31 17:20:42 -07008664void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8665{
8666 mOutDevices = outDevices;
8667 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8668 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008669 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008670 }
8671}
8672
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008673void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008674{
8675 Mutex::Autolock _l(mLock);
8676 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008677 if (record->getSource()) {
8678 mSource = record->getSource();
8679 }
Eric Laurent83b88082014-06-20 18:31:16 -07008680}
8681
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008682void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008683{
8684 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008685 if (mSource == record->getSource()) {
8686 mSource = mInput;
8687 }
Eric Laurent83b88082014-06-20 18:31:16 -07008688 destroyTrack_l(record);
8689}
8690
Mikhail Naganovdc769682018-05-04 15:34:08 -07008691void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008692{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008693 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008694 config->role = AUDIO_PORT_ROLE_SINK;
8695 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8696 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008697 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8698 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8699 config->flags.input = mInput->flags;
8700 }
Eric Laurent83b88082014-06-20 18:31:16 -07008701}
Eric Laurent1c333e22014-05-20 10:48:17 -07008702
Eric Laurent6acd1d42017-01-04 14:23:29 -08008703// ----------------------------------------------------------------------------
8704// Mmap
8705// ----------------------------------------------------------------------------
8706
8707AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8708 : mThread(thread)
8709{
Phil Burk9fabbf82017-08-03 12:02:00 -07008710 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008711}
8712
8713AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8714{
Phil Burk9fabbf82017-08-03 12:02:00 -07008715 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008716}
8717
8718status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8719 struct audio_mmap_buffer_info *info)
8720{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008721 return mThread->createMmapBuffer(minSizeFrames, info);
8722}
8723
8724status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8725{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008726 return mThread->getMmapPosition(position);
8727}
8728
Eric Laurenta54f1282017-07-01 19:39:32 -07008729status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008730 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008731
8732{
jiabind1f1cb62020-03-24 11:57:57 -07008733 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008734}
8735
8736status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8737{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008738 return mThread->stop(handle);
8739}
8740
Eric Laurent18b57012017-02-13 16:23:52 -08008741status_t AudioFlinger::MmapThreadHandle::standby()
8742{
Eric Laurent18b57012017-02-13 16:23:52 -08008743 return mThread->standby();
8744}
8745
Eric Laurent6acd1d42017-01-04 14:23:29 -08008746
8747AudioFlinger::MmapThread::MmapThread(
8748 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07008749 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07008750 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008751 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008752 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008753 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008754 mActiveTracks(&this->mLocalLog),
8755 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8756 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008757{
Eric Laurent18b57012017-02-13 16:23:52 -08008758 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008759 readHalParameters_l();
8760}
8761
8762AudioFlinger::MmapThread::~MmapThread()
8763{
Eric Laurent18b57012017-02-13 16:23:52 -08008764 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008765}
8766
8767void AudioFlinger::MmapThread::onFirstRef()
8768{
8769 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8770}
8771
8772void AudioFlinger::MmapThread::disconnect()
8773{
Eric Laurent331679c2018-04-16 17:03:16 -07008774 ActiveTracks<MmapTrack> activeTracks;
8775 {
8776 Mutex::Autolock _l(mLock);
8777 for (const sp<MmapTrack> &t : mActiveTracks) {
8778 activeTracks.add(t);
8779 }
8780 }
8781 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008782 stop(t->portId());
8783 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008784 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008785 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008786 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008787 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008788 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008789 }
8790}
8791
8792
8793void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8794 audio_stream_type_t streamType __unused,
8795 audio_session_t sessionId,
8796 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008797 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008798 audio_port_handle_t portId)
8799{
8800 mAttr = *attr;
8801 mSessionId = sessionId;
8802 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008803 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008804 mPortId = portId;
8805}
8806
8807status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8808 struct audio_mmap_buffer_info *info)
8809{
8810 if (mHalStream == 0) {
8811 return NO_INIT;
8812 }
Eric Laurent18b57012017-02-13 16:23:52 -08008813 mStandby = true;
8814 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008815 return mHalStream->createMmapBuffer(minSizeFrames, info);
8816}
8817
8818status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8819{
8820 if (mHalStream == 0) {
8821 return NO_INIT;
8822 }
8823 return mHalStream->getMmapPosition(position);
8824}
8825
Eric Laurent331679c2018-04-16 17:03:16 -07008826status_t AudioFlinger::MmapThread::exitStandby()
8827{
8828 status_t ret = mHalStream->start();
8829 if (ret != NO_ERROR) {
8830 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8831 return ret;
8832 }
Andy Hungcf10d742020-04-28 15:38:24 -07008833 if (mStandby) {
8834 mThreadMetrics.logBeginInterval();
8835 mStandby = false;
8836 }
Eric Laurent331679c2018-04-16 17:03:16 -07008837 return NO_ERROR;
8838}
8839
Eric Laurenta54f1282017-07-01 19:39:32 -07008840status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008841 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008842 audio_port_handle_t *handle)
8843{
Eric Laurenta54f1282017-07-01 19:39:32 -07008844 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8845 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008846 if (mHalStream == 0) {
8847 return NO_INIT;
8848 }
8849
8850 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008851
Eric Laurenta54f1282017-07-01 19:39:32 -07008852 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008853 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008854 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008855 }
8856
8857 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8858
8859 audio_io_handle_t io = mId;
8860 if (isOutput()) {
8861 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8862 config.sample_rate = mSampleRate;
8863 config.channel_mask = mChannelMask;
8864 config.format = mFormat;
8865 audio_stream_type_t stream = streamType();
8866 audio_output_flags_t flags =
8867 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008868 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008869 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008870 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8871 mSessionId,
8872 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008873 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008874 client.clientUid,
8875 &config,
8876 flags,
8877 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008878 &portId,
8879 &secondaryOutputs);
8880 ALOGD_IF(!secondaryOutputs.empty(),
8881 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008882 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008883 audio_config_base_t config;
8884 config.sample_rate = mSampleRate;
8885 config.channel_mask = mChannelMask;
8886 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008887 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008888 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07008889 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07008890 mSessionId,
8891 client.clientPid,
8892 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008893 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008894 &config,
8895 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8896 &deviceId,
8897 &portId);
8898 }
8899 // APM should not chose a different input or output stream for the same set of attributes
8900 // and audo configuration
8901 if (ret != NO_ERROR || io != mId) {
8902 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8903 __FUNCTION__, ret, io, mId);
8904 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008905 }
8906
8907 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008908 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008909 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008910 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008911 }
8912
Eric Laurent331679c2018-04-16 17:03:16 -07008913 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008914 // abort if start is rejected by audio policy manager
8915 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008916 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008917 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008918 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008919 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008920 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008921 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008922 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008923 }
Eric Laurent331679c2018-04-16 17:03:16 -07008924 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008925 } else {
8926 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008927 }
8928 return PERMISSION_DENIED;
8929 }
8930
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008931 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07008932 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
8933 mChannelMask, mSessionId, isOutput(), client.clientUid,
8934 client.clientPid, IPCThreadState::self()->getCallingPid(),
8935 portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008936
Eric Laurent4eb58f12018-12-07 16:41:02 -08008937 if (isOutput()) {
8938 // force volume update when a new track is added
8939 mHalVolFloat = -1.0f;
8940 } else if (!track->isSilenced_l()) {
8941 for (const sp<MmapTrack> &t : mActiveTracks) {
8942 if (t->isSilenced_l() && t->uid() != client.clientUid)
8943 t->invalidate();
8944 }
8945 }
8946
8947
Eric Laurent6acd1d42017-01-04 14:23:29 -08008948 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008949 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008950 if (chain != 0) {
8951 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8952 chain->incTrackCnt();
8953 chain->incActiveTrackCnt();
8954 }
8955
Andy Hungc2b11cb2020-04-22 09:04:01 -07008956 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08008957 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008958 broadcast_l();
8959
Eric Laurenta54f1282017-07-01 19:39:32 -07008960 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008961
8962 return NO_ERROR;
8963}
8964
8965status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8966{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008967 ALOGV("%s handle %d", __FUNCTION__, handle);
8968
8969 if (mHalStream == 0) {
8970 return NO_INIT;
8971 }
8972
Eric Laurenta54f1282017-07-01 19:39:32 -07008973 if (handle == mPortId) {
8974 mHalStream->stop();
8975 return NO_ERROR;
8976 }
8977
Eric Laurent331679c2018-04-16 17:03:16 -07008978 Mutex::Autolock _l(mLock);
8979
Eric Laurent6acd1d42017-01-04 14:23:29 -08008980 sp<MmapTrack> track;
8981 for (const sp<MmapTrack> &t : mActiveTracks) {
8982 if (handle == t->portId()) {
8983 track = t;
8984 break;
8985 }
8986 }
8987 if (track == 0) {
8988 return BAD_VALUE;
8989 }
8990
8991 mActiveTracks.remove(track);
8992
Eric Laurent331679c2018-04-16 17:03:16 -07008993 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008994 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008995 AudioSystem::stopOutput(track->portId());
8996 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008997 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008998 AudioSystem::stopInput(track->portId());
8999 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009000 }
Eric Laurent331679c2018-04-16 17:03:16 -07009001 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009002
9003 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9004 if (chain != 0) {
9005 chain->decActiveTrackCnt();
9006 chain->decTrackCnt();
9007 }
9008
9009 broadcast_l();
9010
Eric Laurent6acd1d42017-01-04 14:23:29 -08009011 return NO_ERROR;
9012}
9013
Eric Laurent18b57012017-02-13 16:23:52 -08009014status_t AudioFlinger::MmapThread::standby()
9015{
9016 ALOGV("%s", __FUNCTION__);
9017
9018 if (mHalStream == 0) {
9019 return NO_INIT;
9020 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009021 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009022 return INVALID_OPERATION;
9023 }
9024 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009025 if (!mStandby) {
9026 mThreadMetrics.logEndInterval();
9027 mStandby = true;
9028 }
Eric Laurent18b57012017-02-13 16:23:52 -08009029 releaseWakeLock();
9030 return NO_ERROR;
9031}
9032
Eric Laurent6acd1d42017-01-04 14:23:29 -08009033
9034void AudioFlinger::MmapThread::readHalParameters_l()
9035{
9036 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9037 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9038 mFormat = mHALFormat;
9039 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9040 result = mHalStream->getFrameSize(&mFrameSize);
9041 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009042 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9043 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009044 result = mHalStream->getBufferSize(&mBufferSize);
9045 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9046 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009047
Andy Hungcf10d742020-04-28 15:38:24 -07009048 // TODO: make a readHalParameters call?
9049 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009050 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9051 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9052 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9053 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9054 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9055 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9056 /*
9057 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9058 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9059 (int32_t)mHapticChannelMask)
9060 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9061 (int32_t)mHapticChannelCount)
9062 */
9063 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9064 formatToString(mHALFormat).c_str())
9065 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9066 (int32_t)mFrameCount) // sic - added HAL
9067 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009068}
9069
9070bool AudioFlinger::MmapThread::threadLoop()
9071{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009072 checkSilentMode_l();
9073
9074 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9075
9076 while (!exitPending())
9077 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009078 Vector< sp<EffectChain> > effectChains;
9079
Andy Hung13850be2019-03-14 11:33:09 -07009080 { // under Thread lock
9081 Mutex::Autolock _l(mLock);
9082
Eric Laurent6acd1d42017-01-04 14:23:29 -08009083 if (mSignalPending) {
9084 // A signal was raised while we were unlocked
9085 mSignalPending = false;
9086 } else {
9087 if (mConfigEvents.isEmpty()) {
9088 // we're about to wait, flush the binder command buffer
9089 IPCThreadState::self()->flushCommands();
9090
9091 if (exitPending()) {
9092 break;
9093 }
9094
Eric Laurent6acd1d42017-01-04 14:23:29 -08009095 // wait until we have something to do...
9096 ALOGV("%s going to sleep", myName.string());
9097 mWaitWorkCV.wait(mLock);
9098 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009099
9100 checkSilentMode_l();
9101
9102 continue;
9103 }
9104 }
9105
9106 processConfigEvents_l();
9107
9108 processVolume_l();
9109
9110 checkInvalidTracks_l();
9111
9112 mActiveTracks.updatePowerState(this);
9113
Kevin Rocard069c2712018-03-29 19:09:14 -07009114 updateMetadata_l();
9115
Eric Laurent6acd1d42017-01-04 14:23:29 -08009116 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009117 } // release Thread lock
9118
Eric Laurent6acd1d42017-01-04 14:23:29 -08009119 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009120 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009121 }
Andy Hung13850be2019-03-14 11:33:09 -07009122
9123 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009124 unlockEffectChains(effectChains);
9125 // Effect chains will be actually deleted here if they were removed from
9126 // mEffectChains list during mixing or effects processing
9127 }
9128
9129 threadLoop_exit();
9130
9131 if (!mStandby) {
9132 threadLoop_standby();
9133 mStandby = true;
9134 }
9135
Eric Laurent6acd1d42017-01-04 14:23:29 -08009136 ALOGV("Thread %p type %d exiting", this, mType);
9137 return false;
9138}
9139
9140// checkForNewParameter_l() must be called with ThreadBase::mLock held
9141bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9142 status_t& status)
9143{
9144 AudioParameter param = AudioParameter(keyValuePair);
9145 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009146 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009147 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009148 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009149 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009150 if (sendToHal) {
9151 status = mHalStream->setParameters(keyValuePair);
9152 } else {
9153 status = NO_ERROR;
9154 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009155
9156 return false;
9157}
9158
9159String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9160{
9161 Mutex::Autolock _l(mLock);
9162 String8 out_s8;
9163 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9164 return out_s8;
9165 }
9166 return String8();
9167}
9168
Eric Laurent09f1ed22019-04-24 17:45:17 -07009169void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9170 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009171 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9172
9173 desc->mIoHandle = mId;
9174
9175 switch (event) {
9176 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009177 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009178 case AUDIO_INPUT_CONFIG_CHANGED:
9179 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009180 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009181 case AUDIO_OUTPUT_CONFIG_CHANGED:
9182 desc->mPatch = mPatch;
9183 desc->mChannelMask = mChannelMask;
9184 desc->mSamplingRate = mSampleRate;
9185 desc->mFormat = mFormat;
9186 desc->mFrameCount = mFrameCount;
9187 desc->mFrameCountHAL = mFrameCount;
9188 desc->mLatency = 0;
9189 break;
9190
9191 case AUDIO_INPUT_CLOSED:
9192 case AUDIO_OUTPUT_CLOSED:
9193 default:
9194 break;
9195 }
9196 mAudioFlinger->ioConfigChanged(event, desc, pid);
9197}
9198
9199status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9200 audio_patch_handle_t *handle)
9201{
9202 status_t status = NO_ERROR;
9203
9204 // store new device and send to effects
9205 audio_devices_t type = AUDIO_DEVICE_NONE;
9206 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009207 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9208 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9209 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009210 if (isOutput()) {
9211 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009212 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9213 && !mAudioHwDev->supportsAudioPatches(),
9214 "Enumerated device type(%#x) must not be used "
9215 "as it does not support audio patches",
9216 patch->sinks[i].ext.device.type);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009217 type |= patch->sinks[i].ext.device.type;
jiabinc52b1ff2019-10-31 17:20:42 -07009218 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9219 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009220 }
9221 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009222 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009223 } else {
9224 type = patch->sources[0].ext.device.type;
9225 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009226 numDevices = mPatch.num_sources;
9227 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
9228 sourceDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009229 }
9230
9231 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009232 if (isOutput()) {
9233 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9234 } else {
9235 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9236 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009237 }
9238
jiabinc52b1ff2019-10-31 17:20:42 -07009239 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009240 // store new source and send to effects
9241 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9242 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9243 for (size_t i = 0; i < mEffectChains.size(); i++) {
9244 mEffectChains[i]->setAudioSource_l(mAudioSource);
9245 }
9246 }
9247 }
9248
9249 if (mAudioHwDev->supportsAudioPatches()) {
9250 status = mHalDevice->createAudioPatch(patch->num_sources,
9251 patch->sources,
9252 patch->num_sinks,
9253 patch->sinks,
9254 handle);
9255 } else {
9256 char *address;
9257 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9258 //FIXME: we only support address on first sink with HAL version < 3.0
9259 address = audio_device_address_to_parameter(
9260 patch->sinks[0].ext.device.type,
9261 patch->sinks[0].ext.device.address);
9262 } else {
9263 address = (char *)calloc(1, 1);
9264 }
9265 AudioParameter param = AudioParameter(String8(address));
9266 free(address);
9267 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9268 if (!isOutput()) {
9269 param.addInt(String8(AudioParameter::keyInputSource),
9270 (int)patch->sinks[0].ext.mix.usecase.source);
9271 }
9272 status = mHalStream->setParameters(param.toString());
9273 *handle = AUDIO_PATCH_HANDLE_NONE;
9274 }
9275
jiabinc52b1ff2019-10-31 17:20:42 -07009276 if (numDevices == 0 || mDeviceId != deviceId) {
9277 if (isOutput()) {
9278 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9279 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009280 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009281 } else {
9282 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9283 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9284 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009285 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009286 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009287 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009288 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009289 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009290 }
jiabinc52b1ff2019-10-31 17:20:42 -07009291 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009292 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009293 }
9294 return status;
9295}
9296
9297status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9298{
9299 status_t status = NO_ERROR;
9300
jiabinc52b1ff2019-10-31 17:20:42 -07009301 mPatch = audio_patch{};
9302 mOutDeviceTypeAddrs.clear();
9303 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009304
9305 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9306 supportsAudioPatches : false;
9307
9308 if (supportsAudioPatches) {
9309 status = mHalDevice->releaseAudioPatch(handle);
9310 } else {
9311 AudioParameter param;
9312 param.addInt(String8(AudioParameter::keyRouting), 0);
9313 status = mHalStream->setParameters(param.toString());
9314 }
9315 return status;
9316}
9317
Mikhail Naganovdc769682018-05-04 15:34:08 -07009318void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009319{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009320 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009321 if (isOutput()) {
9322 config->role = AUDIO_PORT_ROLE_SOURCE;
9323 config->ext.mix.hw_module = mAudioHwDev->handle();
9324 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9325 } else {
9326 config->role = AUDIO_PORT_ROLE_SINK;
9327 config->ext.mix.hw_module = mAudioHwDev->handle();
9328 config->ext.mix.usecase.source = mAudioSource;
9329 }
9330}
9331
9332status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9333{
9334 audio_session_t session = chain->sessionId();
9335
9336 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9337 // Attach all tracks with same session ID to this chain.
9338 // indicate all active tracks in the chain
9339 for (const sp<MmapTrack> &track : mActiveTracks) {
9340 if (session == track->sessionId()) {
9341 chain->incTrackCnt();
9342 chain->incActiveTrackCnt();
9343 }
9344 }
9345
9346 chain->setThread(this);
9347 chain->setInBuffer(nullptr);
9348 chain->setOutBuffer(nullptr);
9349 chain->syncHalEffectsState();
9350
9351 mEffectChains.add(chain);
9352 checkSuspendOnAddEffectChain_l(chain);
9353 return NO_ERROR;
9354}
9355
9356size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9357{
9358 audio_session_t session = chain->sessionId();
9359
9360 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9361
9362 for (size_t i = 0; i < mEffectChains.size(); i++) {
9363 if (chain == mEffectChains[i]) {
9364 mEffectChains.removeAt(i);
9365 // detach all active tracks from the chain
9366 // detach all tracks with same session ID from this chain
9367 for (const sp<MmapTrack> &track : mActiveTracks) {
9368 if (session == track->sessionId()) {
9369 chain->decActiveTrackCnt();
9370 chain->decTrackCnt();
9371 }
9372 }
9373 break;
9374 }
9375 }
9376 return mEffectChains.size();
9377}
9378
Eric Laurent6acd1d42017-01-04 14:23:29 -08009379void AudioFlinger::MmapThread::threadLoop_standby()
9380{
9381 mHalStream->standby();
9382}
9383
9384void AudioFlinger::MmapThread::threadLoop_exit()
9385{
Phil Burk7dce7282017-09-27 13:51:41 -07009386 // Do not call callback->onTearDown() because it is redundant for thread exit
9387 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009388}
9389
9390status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9391{
9392 return BAD_VALUE;
9393}
9394
9395bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9396{
9397 return false;
9398}
9399
9400status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9401 const effect_descriptor_t *desc, audio_session_t sessionId)
9402{
9403 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009404 if (audio_is_global_session(sessionId)) {
9405 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009406 desc->name, mThreadName);
9407 return BAD_VALUE;
9408 }
9409
9410 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9411 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9412 desc->name);
9413 return BAD_VALUE;
9414 }
9415 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009416 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9417 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009418 return BAD_VALUE;
9419 }
9420
9421 // Only allow effects without processing load or latency
9422 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9423 return BAD_VALUE;
9424 }
9425
jiabineb3bda02020-06-30 14:07:03 -07009426 if (EffectModule::isHapticGenerator(&desc->type)) {
9427 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9428 return BAD_VALUE;
9429 }
9430
Eric Laurent6acd1d42017-01-04 14:23:29 -08009431 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009432}
9433
9434void AudioFlinger::MmapThread::checkInvalidTracks_l()
9435{
9436 for (const sp<MmapTrack> &track : mActiveTracks) {
9437 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009438 sp<MmapStreamCallback> callback = mCallback.promote();
9439 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009440 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009441 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009442 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009443 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9444 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9445 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009446 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009447 }
9448 }
9449}
9450
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009451void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009452{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009453 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9454 mAttr.content_type, mAttr.usage, mAttr.source);
9455 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009456 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009457 dprintf(fd, " No active clients\n");
9458 }
9459}
9460
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009461void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009462{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009463 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009464 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009465 dprintf(fd, " %zu Tracks\n", numtracks);
9466 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009467 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009468 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009469 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009470 for (size_t i = 0; i < numtracks ; ++i) {
9471 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009472 result.append(prefix);
9473 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009474 }
9475 } else {
9476 dprintf(fd, "\n");
9477 }
9478 write(fd, result.string(), result.size());
9479}
9480
9481AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9482 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009483 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009484 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009485 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009486 mStreamVolume(1.0),
9487 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009488 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009489{
9490 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9491 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9492 mMasterVolume = audioFlinger->masterVolume_l();
9493 mMasterMute = audioFlinger->masterMute_l();
9494 if (mAudioHwDev) {
9495 if (mAudioHwDev->canSetMasterVolume()) {
9496 mMasterVolume = 1.0;
9497 }
9498
9499 if (mAudioHwDev->canSetMasterMute()) {
9500 mMasterMute = false;
9501 }
9502 }
9503}
9504
9505void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9506 audio_stream_type_t streamType,
9507 audio_session_t sessionId,
9508 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009509 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009510 audio_port_handle_t portId)
9511{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009512 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009513 mStreamType = streamType;
9514}
9515
9516AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9517{
9518 Mutex::Autolock _l(mLock);
9519 AudioStreamOut *output = mOutput;
9520 mOutput = NULL;
9521 return output;
9522}
9523
9524void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9525{
9526 Mutex::Autolock _l(mLock);
9527 // Don't apply master volume in SW if our HAL can do it for us.
9528 if (mAudioHwDev &&
9529 mAudioHwDev->canSetMasterVolume()) {
9530 mMasterVolume = 1.0;
9531 } else {
9532 mMasterVolume = value;
9533 }
9534}
9535
9536void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9537{
9538 Mutex::Autolock _l(mLock);
9539 // Don't apply master mute in SW if our HAL can do it for us.
9540 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9541 mMasterMute = false;
9542 } else {
9543 mMasterMute = muted;
9544 }
9545}
9546
9547void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9548{
9549 Mutex::Autolock _l(mLock);
9550 if (stream == mStreamType) {
9551 mStreamVolume = value;
9552 broadcast_l();
9553 }
9554}
9555
9556float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9557{
9558 Mutex::Autolock _l(mLock);
9559 if (stream == mStreamType) {
9560 return mStreamVolume;
9561 }
9562 return 0.0f;
9563}
9564
9565void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9566{
9567 Mutex::Autolock _l(mLock);
9568 if (stream == mStreamType) {
9569 mStreamMute= muted;
9570 broadcast_l();
9571 }
9572}
9573
9574void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9575{
9576 Mutex::Autolock _l(mLock);
9577 if (streamType == mStreamType) {
9578 for (const sp<MmapTrack> &track : mActiveTracks) {
9579 track->invalidate();
9580 }
9581 broadcast_l();
9582 }
9583}
9584
9585void AudioFlinger::MmapPlaybackThread::processVolume_l()
9586{
9587 float volume;
9588
9589 if (mMasterMute || mStreamMute) {
9590 volume = 0;
9591 } else {
9592 volume = mMasterVolume * mStreamVolume;
9593 }
9594
9595 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009596
9597 // Convert volumes from float to 8.24
9598 uint32_t vol = (uint32_t)(volume * (1 << 24));
9599
9600 // Delegate volume control to effect in track effect chain if needed
9601 // only one effect chain can be present on DirectOutputThread, so if
9602 // there is one, the track is connected to it
9603 if (!mEffectChains.isEmpty()) {
9604 mEffectChains[0]->setVolume_l(&vol, &vol);
9605 volume = (float)vol / (1 << 24);
9606 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009607 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009608 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9609 mHalVolFloat = volume; // HW volume control worked, so update value.
9610 mNoCallbackWarningCount = 0;
9611 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009612 sp<MmapStreamCallback> callback = mCallback.promote();
9613 if (callback != 0) {
9614 int channelCount;
9615 if (isOutput()) {
9616 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9617 } else {
9618 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9619 }
9620 Vector<float> values;
9621 for (int i = 0; i < channelCount; i++) {
9622 values.add(volume);
9623 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009624 mHalVolFloat = volume; // SW volume control worked, so update value.
9625 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009626 mLock.unlock();
9627 callback->onVolumeChanged(mChannelMask, values);
9628 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009629 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009630 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9631 ALOGW("Could not set MMAP stream volume: no volume callback!");
9632 mNoCallbackWarningCount++;
9633 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009634 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009635 }
9636 }
9637}
9638
Kevin Rocard069c2712018-03-29 19:09:14 -07009639void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9640{
9641 if (mOutput == nullptr || mOutput->stream == nullptr ||
9642 !mActiveTracks.readAndClearHasChanged()) {
9643 return;
9644 }
9645 StreamOutHalInterface::SourceMetadata metadata;
9646 for (const sp<MmapTrack> &track : mActiveTracks) {
9647 // No track is invalid as this is called after prepareTrack_l in the same critical section
9648 metadata.tracks.push_back({
9649 .usage = track->attributes().usage,
9650 .content_type = track->attributes().content_type,
9651 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9652 });
9653 }
9654 mOutput->stream->updateSourceMetadata(metadata);
9655}
9656
Eric Laurent6acd1d42017-01-04 14:23:29 -08009657void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9658{
9659 if (!mMasterMute) {
9660 char value[PROPERTY_VALUE_MAX];
9661 if (property_get("ro.audio.silent", value, "0") > 0) {
9662 char *endptr;
9663 unsigned long ul = strtoul(value, &endptr, 0);
9664 if (*endptr == '\0' && ul != 0) {
9665 ALOGD("Silence is golden");
9666 // The setprop command will not allow a property to be changed after
9667 // the first time it is set, so we don't have to worry about un-muting.
9668 setMasterMute_l(true);
9669 }
9670 }
9671 }
9672}
9673
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009674void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9675{
9676 MmapThread::toAudioPortConfig(config);
9677 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9678 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9679 config->flags.output = mOutput->flags;
9680 }
9681}
9682
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009683void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009684{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009685 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009686
Glenn Kastend3bb6452016-12-05 18:14:37 -08009687 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9688 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009689 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9690}
9691
9692AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9693 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009694 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009695 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009696 mInput(input)
9697{
9698 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9699 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9700}
9701
Eric Laurent331679c2018-04-16 17:03:16 -07009702status_t AudioFlinger::MmapCaptureThread::exitStandby()
9703{
Phil Burkf054fc32018-12-06 09:45:59 -08009704 {
9705 // mInput might have been cleared by clearInput()
9706 Mutex::Autolock _l(mLock);
9707 if (mInput != nullptr && mInput->stream != nullptr) {
9708 mInput->stream->setGain(1.0f);
9709 }
9710 }
Eric Laurent331679c2018-04-16 17:03:16 -07009711 return MmapThread::exitStandby();
9712}
9713
Eric Laurent6acd1d42017-01-04 14:23:29 -08009714AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9715{
9716 Mutex::Autolock _l(mLock);
9717 AudioStreamIn *input = mInput;
9718 mInput = NULL;
9719 return input;
9720}
Kevin Rocard069c2712018-03-29 19:09:14 -07009721
Eric Laurent331679c2018-04-16 17:03:16 -07009722
9723void AudioFlinger::MmapCaptureThread::processVolume_l()
9724{
9725 bool changed = false;
9726 bool silenced = false;
9727
9728 sp<MmapStreamCallback> callback = mCallback.promote();
9729 if (callback == 0) {
9730 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9731 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9732 mNoCallbackWarningCount++;
9733 }
9734 }
9735
9736 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9737 // track is silenced and unmute otherwise
9738 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9739 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9740 changed = true;
9741 silenced = mActiveTracks[i]->isSilenced_l();
9742 }
9743 }
9744
9745 if (changed) {
9746 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9747 }
9748}
9749
Kevin Rocard069c2712018-03-29 19:09:14 -07009750void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9751{
9752 if (mInput == nullptr || mInput->stream == nullptr ||
9753 !mActiveTracks.readAndClearHasChanged()) {
9754 return;
9755 }
9756 StreamInHalInterface::SinkMetadata metadata;
9757 for (const sp<MmapTrack> &track : mActiveTracks) {
9758 // No track is invalid as this is called after prepareTrack_l in the same critical section
9759 metadata.tracks.push_back({
9760 .source = track->attributes().source,
9761 .gain = 1, // capture tracks do not have volumes
9762 });
9763 }
9764 mInput->stream->updateSinkMetadata(metadata);
9765}
9766
Eric Laurent5ada82e2019-08-29 17:53:54 -07009767void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -07009768{
9769 Mutex::Autolock _l(mLock);
9770 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07009771 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -07009772 mActiveTracks[i]->setSilenced_l(silenced);
9773 broadcast_l();
9774 }
9775 }
9776}
9777
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009778void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9779{
9780 MmapThread::toAudioPortConfig(config);
9781 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9782 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9783 config->flags.input = mInput->flags;
9784 }
9785}
9786
Glenn Kasten63238ef2015-03-02 15:50:29 -08009787} // namespace android