blob: 90b59b30e67ee460dcdf8bd531ce2013ba354d16 [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
yucliuc9c49cd2020-07-13 16:25:21 -07002359 // Set DIRECT flag if current thread is DirectOutputThread. This can
2360 // happen when the playback is rerouted to direct output thread by
2361 // dynamic audio policy.
2362 // Do NOT report the flag changes back to client, since the client
2363 // doesn't explicitly request a direct flag.
2364 audio_output_flags_t trackFlags = *flags;
2365 if (mType == DIRECT) {
2366 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2367 }
2368
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002369 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002370 channelMask, frameCount,
2371 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
yucliuc9c49cd2020-07-13 16:25:21 -07002372 sessionId, creatorPid, uid, trackFlags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002373
Glenn Kasten03003332013-08-06 15:40:54 -07002374 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2375 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002376 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002377 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002378 goto Exit;
2379 }
2380 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002381 {
2382 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2383 if (callback.get() != nullptr) {
2384 mAudioTrackCallbacks.emplace(callback);
2385 }
2386 }
Eric Laurent81784c32012-11-19 14:55:58 -08002387
2388 sp<EffectChain> chain = getEffectChain_l(sessionId);
2389 if (chain != 0) {
2390 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2391 track->setMainBuffer(chain->inBuffer());
2392 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2393 chain->incTrackCnt();
2394 }
2395
Eric Laurent05067782016-06-01 18:27:28 -07002396 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002397 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2398 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2399 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002400 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002401 }
2402 }
2403
2404 lStatus = NO_ERROR;
2405
2406Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002407 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002408 return track;
2409}
2410
Andy Hung1bc088a2018-02-09 15:57:31 -08002411template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002412ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2413{
Andy Hungc0691382018-09-12 18:01:57 -07002414 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002415 const ssize_t index = mTracks.remove(track);
2416 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002417 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002418 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002419 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002420 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002421 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002422 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002423 }
2424 return index;
2425}
2426
Eric Laurent81784c32012-11-19 14:55:58 -08002427uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2428{
2429 return latency;
2430}
2431
2432uint32_t AudioFlinger::PlaybackThread::latency() const
2433{
2434 Mutex::Autolock _l(mLock);
2435 return latency_l();
2436}
2437uint32_t AudioFlinger::PlaybackThread::latency_l() const
2438{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002439 uint32_t latency;
2440 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2441 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002442 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002443 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002444}
2445
2446void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2447{
2448 Mutex::Autolock _l(mLock);
2449 // Don't apply master volume in SW if our HAL can do it for us.
2450 if (mOutput && mOutput->audioHwDev &&
2451 mOutput->audioHwDev->canSetMasterVolume()) {
2452 mMasterVolume = 1.0;
2453 } else {
2454 mMasterVolume = value;
2455 }
2456}
2457
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002458void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2459{
2460 mMasterBalance.store(balance);
2461}
2462
Eric Laurent81784c32012-11-19 14:55:58 -08002463void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2464{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002465 if (isDuplicating()) {
2466 return;
2467 }
Eric Laurent81784c32012-11-19 14:55:58 -08002468 Mutex::Autolock _l(mLock);
2469 // Don't apply master mute in SW if our HAL can do it for us.
2470 if (mOutput && mOutput->audioHwDev &&
2471 mOutput->audioHwDev->canSetMasterMute()) {
2472 mMasterMute = false;
2473 } else {
2474 mMasterMute = muted;
2475 }
2476}
2477
2478void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2479{
2480 Mutex::Autolock _l(mLock);
2481 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002482 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002483}
2484
2485void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2486{
2487 Mutex::Autolock _l(mLock);
2488 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002489 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002490}
2491
2492float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2493{
2494 Mutex::Autolock _l(mLock);
2495 return mStreamTypes[stream].volume;
2496}
2497
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002498void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2499{
2500 mOutput->stream->setVolume(left, right);
2501}
2502
Eric Laurent81784c32012-11-19 14:55:58 -08002503// addTrack_l() must be called with ThreadBase::mLock held
2504status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2505{
2506 status_t status = ALREADY_EXISTS;
2507
Eric Laurent81784c32012-11-19 14:55:58 -08002508 if (mActiveTracks.indexOf(track) < 0) {
2509 // the track is newly added, make sure it fills up all its
2510 // buffers before playing. This is to ensure the client will
2511 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002512 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002513 TrackBase::track_state state = track->mState;
2514 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002515 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002516 mLock.lock();
2517 // abort track was stopped/paused while we released the lock
2518 if (state != track->mState) {
2519 if (status == NO_ERROR) {
2520 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002521 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002522 mLock.lock();
2523 }
2524 return INVALID_OPERATION;
2525 }
2526 // abort if start is rejected by audio policy manager
2527 if (status != NO_ERROR) {
2528 return PERMISSION_DENIED;
2529 }
2530#ifdef ADD_BATTERY_DATA
2531 // to track the speaker usage
2532 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2533#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002534 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002535 }
2536
Eric Laurent51716182016-02-29 18:00:56 -08002537 // set retry count for buffer fill
2538 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002539 if (track->isStopping_1()) {
2540 track->mRetryCount = kMaxTrackStopRetriesOffload;
2541 } else {
2542 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2543 }
2544 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002545 } else {
2546 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002547 track->mFillingUpStatus =
2548 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002549 }
2550
jiabineb3bda02020-06-30 14:07:03 -07002551 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2552 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2553 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2554 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002555 // Unlock due to VibratorService will lock for this call and will
2556 // call Tracks.mute/unmute which also require thread's lock.
2557 mLock.unlock();
2558 const int intensity = AudioFlinger::onExternalVibrationStart(
2559 track->getExternalVibration());
2560 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002561 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002562 // Haptic playback should be enabled by vibrator service.
2563 if (track->getHapticPlaybackEnabled()) {
2564 // Disable haptic playback of all active track to ensure only
2565 // one track playing haptic if current track should play haptic.
2566 for (const auto &t : mActiveTracks) {
2567 t->setHapticPlaybackEnabled(false);
2568 }
jiabin245cdd92018-12-07 17:55:15 -08002569 }
jiabine70bc7f2020-06-30 22:07:55 -07002570
2571 // Set haptic intensity for effect
2572 if (chain != nullptr) {
2573 chain->setHapticIntensity_l(track->id(), intensity);
2574 }
jiabin245cdd92018-12-07 17:55:15 -08002575 }
2576
Eric Laurent81784c32012-11-19 14:55:58 -08002577 track->mResetDone = false;
2578 track->mPresentationCompleteFrames = 0;
2579 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002580 if (chain != 0) {
2581 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2582 track->sessionId());
2583 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002584 }
2585
Andy Hungc2b11cb2020-04-22 09:04:01 -07002586 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002587 status = NO_ERROR;
2588 }
2589
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002590 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002591 return status;
2592}
2593
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002595{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002596 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002597 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002598 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2599 track->mState = TrackBase::STOPPED;
2600 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002601 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002602 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002604 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002605
2606 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002607}
2608
2609void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2610{
2611 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002612
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002613 String8 result;
2614 track->appendDump(result, false /* active */);
2615 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002616
Eric Laurent81784c32012-11-19 14:55:58 -08002617 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002618 if (track->isFastTrack()) {
2619 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002620 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002621 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2622 mFastTrackAvailMask |= 1 << index;
2623 // redundant as track is about to be destroyed, for dumpsys only
2624 track->mFastIndex = -1;
2625 }
2626 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2627 if (chain != 0) {
2628 chain->decTrackCnt();
2629 }
2630}
2631
2632String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2633{
Eric Laurent81784c32012-11-19 14:55:58 -08002634 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002635 String8 out_s8;
2636 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2637 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002638 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002639 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002640}
2641
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002642status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2643 Mutex::Autolock _l(mLock);
2644 if (mOutput == nullptr || mOutput->stream == nullptr) {
2645 return NO_INIT;
2646 }
2647 return mOutput->stream->selectPresentation(presentationId, programId);
2648}
2649
Eric Laurent09f1ed22019-04-24 17:45:17 -07002650void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2651 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002652 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2653 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002654
Eric Laurent73e26b62015-04-27 16:55:58 -07002655 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002656
2657 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002658 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002659 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002660 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002661 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002662 desc->mChannelMask = mChannelMask;
2663 desc->mSamplingRate = mSampleRate;
2664 desc->mFormat = mFormat;
2665 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002666 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002667 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002668 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002669 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002670 case AUDIO_CLIENT_STARTED:
2671 desc->mPatch = mPatch;
2672 desc->mPortId = portId;
2673 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002674 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002675 default:
2676 break;
2677 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002678 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002679}
2680
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002681void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002683 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002684}
2685
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002686void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002688 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002689}
2690
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002691void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002692{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002693 mCallbackThread->setAsyncError();
2694}
2695
jiabinf6eb4c32020-02-25 14:06:25 -08002696void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2697 const std::basic_string<uint8_t>& metadataBs)
2698{
2699 std::thread([this, metadataBs]() {
2700 audio_utils::metadata::Data metadata =
2701 audio_utils::metadata::dataFromByteString(metadataBs);
2702 if (metadata.empty()) {
2703 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2704 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2705 (int)metadataBs.size());
2706 return;
2707 }
2708
2709 audio_utils::metadata::ByteString metaDataStr =
2710 audio_utils::metadata::byteStringFromData(metadata);
2711 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2712 Mutex::Autolock _l(mAudioTrackCbLock);
2713 for (const auto& callback : mAudioTrackCallbacks) {
2714 callback->onCodecFormatChanged(metadataVec);
2715 }
2716 }).detach();
2717}
2718
Eric Laurent3b4529e2013-09-05 18:09:19 -07002719void AudioFlinger::PlaybackThread::resetWriteBlocked(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 ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2724 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002725 mWaitWorkCV.signal();
2726 }
2727}
2728
Eric Laurent3b4529e2013-09-05 18:09:19 -07002729void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002730{
2731 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002732 // reject out of sequence requests
2733 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002734 // Register discontinuity when HW drain is completed because that can cause
2735 // the timestamp frame position to reset to 0 for direct and offload threads.
2736 // (Out of sequence requests are ignored, since the discontinuity would be handled
2737 // elsewhere, e.g. in flush).
2738 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002739 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002740 mWaitWorkCV.signal();
2741 }
2742}
2743
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002744void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002745{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002746 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002747 mSampleRate = mOutput->getSampleRate();
2748 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002749 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002750 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002751 }
Andy Hung9a592762014-07-21 21:56:01 -07002752 if ((mType == MIXER || mType == DUPLICATING)
2753 && !isValidPcmSinkChannelMask(mChannelMask)) {
2754 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2755 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002756 }
Andy Hunge5412692014-05-16 11:25:07 -07002757 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002758 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002759
2760 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002761 status_t result = mOutput->stream->getFormat(&mHALFormat);
2762 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002763 // Get format from the shim, which will be different than the HAL format
2764 // if playing compressed audio over HDMI passthrough.
2765 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002766 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002767 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002768 }
Andy Hung6146c082014-03-18 11:56:15 -07002769 if ((mType == MIXER || mType == DUPLICATING)
2770 && !isValidPcmSinkFormat(mFormat)) {
2771 LOG_FATAL("HAL format %#x not supported for mixed output",
2772 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002773 }
Phil Burk062e67a2015-02-11 13:40:50 -08002774 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002775 result = mOutput->stream->getBufferSize(&mBufferSize);
2776 LOG_ALWAYS_FATAL_IF(result != OK,
2777 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002778 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002779 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002780 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002781 mFrameCount);
2782 }
2783
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002784 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2785 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002786 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002787 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002788 }
2789 }
2790
Eric Laurentd1f69b02014-12-15 14:33:13 -08002791 mHwSupportsPause = false;
2792 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002793 bool supportsPause = false, supportsResume = false;
2794 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2795 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002796 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002797 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002798 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002799 } else if (supportsResume) {
2800 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002801 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002802 }
2803 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002804 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2805 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2806 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002807
Andy Hungfbfc3952015-01-15 13:33:51 -08002808 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2809 // For best precision, we use float instead of the associated output
2810 // device format (typically PCM 16 bit).
2811
2812 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2813 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2814 mBufferSize = mFrameSize * mFrameCount;
2815
2816 // TODO: We currently use the associated output device channel mask and sample rate.
2817 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2818 // (if a valid mask) to avoid premature downmix.
2819 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2820 // instead of the output device sample rate to avoid loss of high frequency information.
2821 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2822 }
2823
Andy Hung09a50072014-02-27 14:30:47 -08002824 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002825 double multiplier = 1.0;
2826 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2827 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002828 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2829 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002830
Eric Laurent81784c32012-11-19 14:55:58 -08002831 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2832 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2833 maxNormalFrameCount = maxNormalFrameCount & ~15;
2834 if (maxNormalFrameCount < minNormalFrameCount) {
2835 maxNormalFrameCount = minNormalFrameCount;
2836 }
2837 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2838 if (multiplier <= 1.0) {
2839 multiplier = 1.0;
2840 } else if (multiplier <= 2.0) {
2841 if (2 * mFrameCount <= maxNormalFrameCount) {
2842 multiplier = 2.0;
2843 } else {
2844 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2845 }
2846 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002847 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002848 }
2849 }
2850 mNormalFrameCount = multiplier * mFrameCount;
2851 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002852 if (mType == MIXER || mType == DUPLICATING) {
2853 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2854 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002855 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002856 mNormalFrameCount);
2857
Andy Hung08fb1742015-05-31 23:22:10 -07002858 // Check if we want to throttle the processing to no more than 2x normal rate
2859 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002860 mThreadThrottleTimeMs = 0;
2861 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002862 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2863
Andy Hung010a1a12014-03-13 13:57:33 -07002864 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2865 // Originally this was int16_t[] array, need to remove legacy implications.
2866 free(mSinkBuffer);
2867 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002868 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2869 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2870 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002871 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002872
Andy Hung69aed5f2014-02-25 17:24:40 -08002873 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2874 // drives the output.
2875 free(mMixerBuffer);
2876 mMixerBuffer = NULL;
2877 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002878 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002879 mMixerBufferSize = mNormalFrameCount * mChannelCount
2880 * audio_bytes_per_sample(mMixerBufferFormat);
2881 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2882 }
Andy Hung98ef9782014-03-04 14:46:50 -08002883 free(mEffectBuffer);
2884 mEffectBuffer = NULL;
2885 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002886 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002887 mEffectBufferSize = mNormalFrameCount * mChannelCount
2888 * audio_bytes_per_sample(mEffectBufferFormat);
2889 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2890 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002891
jiabin245cdd92018-12-07 17:55:15 -08002892 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2893 mChannelMask &= ~mHapticChannelMask;
2894 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2895 mChannelCount -= mHapticChannelCount;
2896
Eric Laurent81784c32012-11-19 14:55:58 -08002897 // force reconfiguration of effect chains and engines to take new buffer size and audio
2898 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002899 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002900 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2901 // matter.
2902 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2903 Vector< sp<EffectChain> > effectChains = mEffectChains;
2904 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002905 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2906 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002907 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08002908
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002909 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07002910 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08002911 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2912 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2913 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2914 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2915 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2916 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2917 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2918 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2919 (int32_t)mHapticChannelMask)
2920 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2921 (int32_t)mHapticChannelCount)
2922 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
2923 formatToString(mHALFormat).c_str())
2924 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
2925 (int32_t)mFrameCount) // sic - added HAL
2926 ;
2927 uint32_t latencyMs;
2928 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2929 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2930 }
2931 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08002932}
2933
Kevin Rocard069c2712018-03-29 19:09:14 -07002934void AudioFlinger::PlaybackThread::updateMetadata_l()
2935{
Kevin Rocard12381092018-04-11 09:19:59 -07002936 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2937 return; // That should not happen
2938 }
2939 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2940 for (const sp<Track> &track : mActiveTracks) {
2941 // Do not short-circuit as all hasChanged states must be reset
2942 // as all the metadata are going to be sent
2943 hasChanged |= track->readAndClearHasChanged();
2944 }
2945 if (!hasChanged) {
2946 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002947 }
2948 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002949 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002950 for (const sp<Track> &track : mActiveTracks) {
2951 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002952 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002953 }
Kevin Rocard12381092018-04-11 09:19:59 -07002954 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002955}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002956
Kevin Rocard12381092018-04-11 09:19:59 -07002957void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2958 const StreamOutHalInterface::SourceMetadata& metadata)
2959{
2960 mOutput->stream->updateSourceMetadata(metadata);
2961};
2962
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002963status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002964{
2965 if (halFrames == NULL || dspFrames == NULL) {
2966 return BAD_VALUE;
2967 }
2968 Mutex::Autolock _l(mLock);
2969 if (initCheck() != NO_ERROR) {
2970 return INVALID_OPERATION;
2971 }
Andy Hung818e7a32016-02-16 18:08:07 -08002972 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002973 *halFrames = framesWritten;
2974
2975 if (isSuspended()) {
2976 // return an estimation of rendered frames when the output is suspended
2977 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002978 *dspFrames = (uint32_t)
2979 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002980 return NO_ERROR;
2981 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002982 status_t status;
2983 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002984 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002985 *dspFrames = (size_t)frames;
2986 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002987 }
2988}
2989
Glenn Kastend848eb42016-03-08 13:42:11 -08002990uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002991{
2992 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2993 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2994 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2995 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2996 }
2997 for (size_t i = 0; i < mTracks.size(); i++) {
2998 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002999 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003000 return AudioSystem::getStrategyForStream(track->streamType());
3001 }
3002 }
3003 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3004}
3005
3006
Phil Burk062e67a2015-02-11 13:40:50 -08003007AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003008{
3009 Mutex::Autolock _l(mLock);
3010 return mOutput;
3011}
3012
Phil Burk062e67a2015-02-11 13:40:50 -08003013AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003014{
3015 Mutex::Autolock _l(mLock);
3016 AudioStreamOut *output = mOutput;
3017 mOutput = NULL;
3018 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3019 // must push a NULL and wait for ack
3020 mOutputSink.clear();
3021 mPipeSink.clear();
3022 mNormalSink.clear();
3023 return output;
3024}
3025
3026// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003027sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003028{
3029 if (mOutput == NULL) {
3030 return NULL;
3031 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003032 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003033}
3034
3035uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3036{
3037 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3038}
3039
3040status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3041{
3042 if (!isValidSyncEvent(event)) {
3043 return BAD_VALUE;
3044 }
3045
3046 Mutex::Autolock _l(mLock);
3047
3048 for (size_t i = 0; i < mTracks.size(); ++i) {
3049 sp<Track> track = mTracks[i];
3050 if (event->triggerSession() == track->sessionId()) {
3051 (void) track->setSyncEvent(event);
3052 return NO_ERROR;
3053 }
3054 }
3055
3056 return NAME_NOT_FOUND;
3057}
3058
3059bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3060{
3061 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3062}
3063
3064void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3065 const Vector< sp<Track> >& tracksToRemove)
3066{
Andy Hungfe726a62018-09-27 15:17:25 -07003067 // Miscellaneous track cleanup when removed from the active list,
3068 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003069#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003070 for (const auto& track : tracksToRemove) {
3071 if (track->isExternalTrack()) {
3072 // to track the speaker usage
3073 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003074 }
3075 }
Andy Hungfe726a62018-09-27 15:17:25 -07003076#else
3077 (void)tracksToRemove; // suppress unused warning
3078#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003079}
3080
3081void AudioFlinger::PlaybackThread::checkSilentMode_l()
3082{
3083 if (!mMasterMute) {
3084 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003085 if (mOutDeviceTypeAddrs.empty()) {
3086 ALOGD("ro.audio.silent is ignored since no output device is set");
3087 return;
3088 }
jiabinc52b1ff2019-10-31 17:20:42 -07003089 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003090 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3091 return;
3092 }
Eric Laurent81784c32012-11-19 14:55:58 -08003093 if (property_get("ro.audio.silent", value, "0") > 0) {
3094 char *endptr;
3095 unsigned long ul = strtoul(value, &endptr, 0);
3096 if (*endptr == '\0' && ul != 0) {
3097 ALOGD("Silence is golden");
3098 // The setprop command will not allow a property to be changed after
3099 // the first time it is set, so we don't have to worry about un-muting.
3100 setMasterMute_l(true);
3101 }
3102 }
3103 }
3104}
3105
3106// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003108{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003109 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003110 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003111 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003112 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003113
3114 // If an NBAIO sink is present, use it to write the normal mixer's submix
3115 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003116
Andy Hung010a1a12014-03-13 13:57:33 -07003117 const size_t count = mBytesRemaining / mFrameSize;
3118
Simon Wilson2d590962012-11-29 15:18:50 -08003119 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003120 // update the setpoint when AudioFlinger::mScreenState changes
3121 uint32_t screenState = AudioFlinger::mScreenState;
3122 if (screenState != mScreenState) {
3123 mScreenState = screenState;
3124 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3125 if (pipe != NULL) {
3126 pipe->setAvgFrames((mScreenState & 1) ?
3127 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3128 }
3129 }
Andy Hung010a1a12014-03-13 13:57:33 -07003130 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003131 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003132 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003133 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003134#ifdef TEE_SINK
3135 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3136#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003137 } else {
3138 bytesWritten = framesWritten;
3139 }
3140 // otherwise use the HAL / AudioStreamOut directly
3141 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003142 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003143
Eric Laurentbfb1b832013-01-07 09:53:42 -08003144 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003145 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3146 mWriteAckSequence += 2;
3147 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003148 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003149 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003150 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003151 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003152 // FIXME We should have an implementation of timestamps for direct output threads.
3153 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003154 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003155 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003156
Eric Laurentbfb1b832013-01-07 09:53:42 -08003157 if (mUseAsyncWrite &&
3158 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3159 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003160 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003161 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003162 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003163 }
Eric Laurent81784c32012-11-19 14:55:58 -08003164 }
3165
Eric Laurent81784c32012-11-19 14:55:58 -08003166 mNumWrites++;
3167 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003168 if (mStandby) {
3169 mThreadMetrics.logBeginInterval();
3170 mStandby = false;
3171 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003172 return bytesWritten;
3173}
3174
3175void AudioFlinger::PlaybackThread::threadLoop_drain()
3176{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003177 bool supportsDrain = false;
3178 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003179 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3180 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003181 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3182 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003183 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003184 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003185 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003186 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003187 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003188 }
3189}
3190
3191void AudioFlinger::PlaybackThread::threadLoop_exit()
3192{
Eric Laurent275e8e92014-11-30 15:14:47 -08003193 {
3194 Mutex::Autolock _l(mLock);
3195 for (size_t i = 0; i < mTracks.size(); i++) {
3196 sp<Track> track = mTracks[i];
3197 track->invalidate();
3198 }
Andy Hungdae27702016-10-31 14:01:16 -07003199 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3200 // After we exit there are no more track changes sent to BatteryNotifier
3201 // because that requires an active threadLoop.
3202 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3203 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003204 }
Eric Laurent81784c32012-11-19 14:55:58 -08003205}
3206
3207/*
3208The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003209 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003210 - mActiveSleepTimeUs from activeSleepTimeUs()
3211 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003212 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3213 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003214 - maxPeriod from frame count and sample rate (MIXER only)
3215
3216The parameters that affect these derived values are:
3217 - frame count
3218 - frame size
3219 - sample rate
3220 - device type: A2DP or not
3221 - device latency
3222 - format: PCM or not
3223 - active sleep time
3224 - idle sleep time
3225*/
3226
3227void AudioFlinger::PlaybackThread::cacheParameters_l()
3228{
Andy Hung25c2dac2014-02-27 14:56:00 -08003229 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003230 mActiveSleepTimeUs = activeSleepTimeUs();
3231 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003232
3233 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3234 // truncating audio when going to standby.
3235 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003236 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003237 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3238 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3239 }
3240 }
Eric Laurent81784c32012-11-19 14:55:58 -08003241}
3242
Eric Laurent13084622016-05-17 10:51:49 -07003243bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003244{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003245 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003246 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003247 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003248 size_t size = mTracks.size();
3249 for (size_t i = 0; i < size; i++) {
3250 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003251 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003252 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003253 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003254 }
3255 }
Eric Laurent13084622016-05-17 10:51:49 -07003256 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003257}
3258
Haynes Mathew George05317d22016-05-03 16:34:26 -07003259void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3260{
3261 Mutex::Autolock _l(mLock);
3262 invalidateTracks_l(streamType);
3263}
3264
Eric Laurent81784c32012-11-19 14:55:58 -08003265status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3266{
Glenn Kastend848eb42016-03-08 13:42:11 -08003267 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003268 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003269 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003270 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3271 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3272 &halInBuffer);
3273 if (result != OK) return result;
3274 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003275 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003276 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003277 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003278 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003279 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003280 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003281 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003282 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003283 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003284 &halInBuffer);
3285 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003286#ifdef FLOAT_EFFECT_CHAIN
3287 buffer = halInBuffer->audioBuffer()->f32;
3288#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003289 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003290#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003291 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3292 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003293 }
3294
3295 // Attach all tracks with same session ID to this chain.
3296 for (size_t i = 0; i < mTracks.size(); ++i) {
3297 sp<Track> track = mTracks[i];
3298 if (session == track->sessionId()) {
3299 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3300 buffer);
3301 track->setMainBuffer(buffer);
3302 chain->incTrackCnt();
3303 }
3304 }
3305
3306 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003307 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003308 if (session == track->sessionId()) {
3309 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3310 chain->incActiveTrackCnt();
3311 }
3312 }
3313 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003314 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003315 chain->setInBuffer(halInBuffer);
3316 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003317 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3318 // chains list in order to be processed last as it contains output device effects.
3319 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3320 // processing effects specific to an output stream before effects applied to all streams
3321 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003322 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3323 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003324 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003325 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003326 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003327 // Effect chain for other sessions are inserted at beginning of effect
3328 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003329 // sessions is not important.
3330 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003331 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3332 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003333 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003334 size_t size = mEffectChains.size();
3335 size_t i = 0;
3336 for (i = 0; i < size; i++) {
3337 if (mEffectChains[i]->sessionId() < session) {
3338 break;
3339 }
3340 }
3341 mEffectChains.insertAt(chain, i);
3342 checkSuspendOnAddEffectChain_l(chain);
3343
3344 return NO_ERROR;
3345}
3346
3347size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3348{
Glenn Kastend848eb42016-03-08 13:42:11 -08003349 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003350
3351 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3352
3353 for (size_t i = 0; i < mEffectChains.size(); i++) {
3354 if (chain == mEffectChains[i]) {
3355 mEffectChains.removeAt(i);
3356 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003357 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003358 if (session == track->sessionId()) {
3359 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3360 chain.get(), session);
3361 chain->decActiveTrackCnt();
3362 }
3363 }
3364
3365 // detach all tracks with same session ID from this chain
3366 for (size_t i = 0; i < mTracks.size(); ++i) {
3367 sp<Track> track = mTracks[i];
3368 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003369 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003370 chain->decTrackCnt();
3371 }
3372 }
3373 break;
3374 }
3375 }
3376 return mEffectChains.size();
3377}
3378
3379status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003380 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003381{
3382 Mutex::Autolock _l(mLock);
3383 return attachAuxEffect_l(track, EffectId);
3384}
3385
3386status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003387 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003388{
3389 status_t status = NO_ERROR;
3390
3391 if (EffectId == 0) {
3392 track->setAuxBuffer(0, NULL);
3393 } else {
3394 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3395 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3396 if (effect != 0) {
3397 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3398 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3399 } else {
3400 status = INVALID_OPERATION;
3401 }
3402 } else {
3403 status = BAD_VALUE;
3404 }
3405 }
3406 return status;
3407}
3408
3409void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3410{
3411 for (size_t i = 0; i < mTracks.size(); ++i) {
3412 sp<Track> track = mTracks[i];
3413 if (track->auxEffectId() == effectId) {
3414 attachAuxEffect_l(track, 0);
3415 }
3416 }
3417}
3418
3419bool AudioFlinger::PlaybackThread::threadLoop()
3420{
Glenn Kasten388d5712017-04-07 14:38:41 -07003421 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003422
Eric Laurent81784c32012-11-19 14:55:58 -08003423 Vector< sp<Track> > tracksToRemove;
3424
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003425 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003426 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
3427 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003428
3429 // MIXER
3430 nsecs_t lastWarning = 0;
3431
3432 // DUPLICATING
3433 // FIXME could this be made local to while loop?
3434 writeFrames = 0;
3435
3436 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003437 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003438
3439 if (mType == MIXER) {
3440 sleepTimeShift = 0;
3441 }
3442
3443 CpuStats cpuStats;
3444 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3445
3446 acquireWakeLock();
3447
Glenn Kasteneef598c2017-04-03 14:41:13 -07003448 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3449 // thread associated with this PlaybackThread.
3450 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3451 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003452 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3453 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003454 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003455 const char *logString = NULL;
3456
rago1bb90822017-05-02 18:31:48 -07003457 // Estimated time for next buffer to be written to hal. This is used only on
3458 // suspended mode (for now) to help schedule the wait time until next iteration.
3459 nsecs_t timeLoopNextNs = 0;
3460
Eric Laurent664539d2013-09-23 18:24:31 -07003461 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003462
Andy Hungf3234512018-07-03 14:51:47 -07003463 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3464 // TODO: add confirmation checks:
3465 // 1) DIRECT threads and linear PCM format really resets to 0?
3466 // 2) Is frame count really valid if not linear pcm?
3467 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3468 if (mType == OFFLOAD || mType == DIRECT) {
3469 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3470 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003471 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003472
Andy Hung446f4df2019-02-21 12:26:41 -08003473 // loopCount is used for statistics and diagnostics.
3474 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003475 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003476 // Log merge requests are performed during AudioFlinger binder transactions, but
3477 // that does not cover audio playback. It's requested here for that reason.
3478 mAudioFlinger->requestLogMerge();
3479
Eric Laurent81784c32012-11-19 14:55:58 -08003480 cpuStats.sample(myName);
3481
3482 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003483 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003484 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003485
Andy Hung2dbffc22018-08-08 18:50:41 -07003486 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3487 //
jiabinc52b1ff2019-10-31 17:20:42 -07003488 // Note: we access outDeviceTypes() outside of mLock.
3489 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003490 // Here, we try for the AF lock, but do not block on it as the latency
3491 // is more informational.
3492 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3493 std::vector<PatchPanel::SoftwarePatch> swPatches;
3494 double latencyMs;
3495 status_t status = INVALID_OPERATION;
3496 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3497 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3498 && swPatches.size() > 0) {
3499 status = swPatches[0].getLatencyMs_l(&latencyMs);
3500 downstreamPatchHandle = swPatches[0].getPatchHandle();
3501 }
3502 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003503 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003504 lastDownstreamPatchHandle = downstreamPatchHandle;
3505 }
3506 if (status == OK) {
3507 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003508 // latency of 5 seconds).
3509 const double minLatency = 0., maxLatency = 5000.;
3510 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003511 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003512 } else {
3513 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003514 if (latencyMs < minLatency) latencyMs = minLatency;
3515 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003516 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003517 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003518 }
3519 mAudioFlinger->mLock.unlock();
3520 }
3521 } else {
3522 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3523 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003524 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003525 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3526 }
3527 }
3528
Eric Laurent81784c32012-11-19 14:55:58 -08003529 { // scope for mLock
3530
3531 Mutex::Autolock _l(mLock);
3532
Eric Laurent021cf962014-05-13 10:18:14 -07003533 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003534
Glenn Kasteneef598c2017-04-03 14:41:13 -07003535 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003536 if (logString != NULL) {
3537 mNBLogWriter->logTimestamp();
3538 mNBLogWriter->log(logString);
3539 logString = NULL;
3540 }
3541
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003542 // Collect timestamp statistics for the Playback Thread types that support it.
3543 if (mType == MIXER
3544 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003545 || mType == DIRECT
3546 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003547 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003548 // and associate with the sink frames written out. We need
3549 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003550 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003551 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003552 if (mStandby) {
3553 mTimestampVerifier.discontinuity();
3554 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3555 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3556 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3557 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003558
3559 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003560 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
Andy Hungc8fddf32018-08-08 18:32:37 -07003561 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3562 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3563 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3564 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3565 = correctedTimestamp.mFrames;
3566 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3567 = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10003568 ALOGVV("TS_AFTER: %d %lld %lld", id(),
Andy Hungc8fddf32018-08-08 18:32:37 -07003569 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3570 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003571
3572 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003573 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003574 const int64_t newPosition =
3575 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003576 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003577 // prevent retrograde
3578 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3579 newPosition,
3580 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3581 - mSuspendedFrames));
3582 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003583 }
3584
Andy Hung818e7a32016-02-16 18:08:07 -08003585 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003586 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003587
3588 // We keep track of the last valid kernel position in case we are in underrun
3589 // and the normal mixer period is the same as the fast mixer period, or there
3590 // is some error from the HAL.
3591 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3592 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3593 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3594 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3595 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3596
3597 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3598 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3599 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3600 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003601 }
3602
3603 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3604 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003605 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003606 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003607 }
3608
Andy Hung818e7a32016-02-16 18:08:07 -08003609 // copy over kernel info
3610 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003611 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3612 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003613 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3614 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003615 } else {
3616 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003617 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003618
Andy Hungc54b1ff2016-02-23 14:07:07 -08003619 // mFramesWritten for non-offloaded tracks are contiguous
3620 // even after standby() is called. This is useful for the track frame
3621 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003622 bool serverLocationUpdate = false;
3623 if (mFramesWritten != lastFramesWritten) {
3624 serverLocationUpdate = true;
3625 lastFramesWritten = mFramesWritten;
3626 }
3627 // Only update timestamps if there is a meaningful change.
3628 // Either the kernel timestamp must be valid or we have written something.
3629 if (kernelLocationUpdate || serverLocationUpdate) {
3630 if (serverLocationUpdate) {
3631 // use the time before we called the HAL write - it is a bit more accurate
3632 // to when the server last read data than the current time here.
3633 //
Andy Hung446f4df2019-02-21 12:26:41 -08003634 // If we haven't written anything, mLastIoBeginNs will be -1
Andy Hung69488c42016-05-16 18:43:33 -07003635 // and we use systemTime().
3636 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
Andy Hung446f4df2019-02-21 12:26:41 -08003637 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
3638 ? systemTime() : mLastIoBeginNs;
Andy Hung69488c42016-05-16 18:43:33 -07003639 }
Andy Hungdae27702016-10-31 14:01:16 -07003640
3641 for (const sp<Track> &t : mActiveTracks) {
3642 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003643 t->updateTrackFrameInfo(
3644 t->mAudioTrackServerProxy->framesReleased(),
3645 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003646 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003647 mTimestamp);
3648 }
Andy Hunge10393e2015-06-12 13:59:33 -07003649 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003650 }
Andy Hunge6c37112019-02-26 17:38:10 -08003651
3652 if (audio_has_proportional_frames(mFormat)) {
3653 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
3654 if (latencyMs != 0.) { // note 0. means timestamp is empty.
3655 mLatencyMs.add(latencyMs);
3656 }
3657 }
3658
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003659 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003660#if 0
3661 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003662 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003663 timespec ts;
3664 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003665 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003666 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003667 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003668 }
3669 ++z;
3670#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003671 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003672 if (mSignalPending) {
3673 // A signal was raised while we were unlocked
3674 mSignalPending = false;
3675 } else if (waitingAsyncCallback_l()) {
3676 if (exitPending()) {
3677 break;
3678 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003679 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003680 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003681 releaseWakeLock_l();
3682 released = true;
3683 }
Andy Hung10cbff12017-02-21 17:30:14 -08003684
3685 const int64_t waitNs = computeWaitTimeNs_l();
3686 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3687 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3688 if (status == TIMED_OUT) {
3689 mSignalPending = true; // if timeout recheck everything
3690 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003691 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003692 if (released) {
3693 acquireWakeLock_l();
3694 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003695 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3696 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003697
3698 continue;
3699 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003700 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003701 isSuspended()) {
3702 // put audio hardware into standby after short delay
3703 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003704
3705 threadLoop_standby();
3706
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003707 // This is where we go into standby
3708 if (!mStandby) {
3709 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003710 mThreadMetrics.logEndInterval();
3711 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003712 }
Andy Hungd0979812019-02-21 15:51:44 -08003713 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003714 }
3715
Eric Tan39ec8d62018-07-24 09:49:29 -07003716 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003717 // we're about to wait, flush the binder command buffer
3718 IPCThreadState::self()->flushCommands();
3719
3720 clearOutputTracks();
3721
3722 if (exitPending()) {
3723 break;
3724 }
3725
3726 releaseWakeLock_l();
3727 // wait until we have something to do...
3728 ALOGV("%s going to sleep", myName.string());
3729 mWaitWorkCV.wait(mLock);
3730 ALOGV("%s waking up", myName.string());
3731 acquireWakeLock_l();
3732
3733 mMixerStatus = MIXER_IDLE;
3734 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3735 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003736 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003737 checkSilentMode_l();
3738
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003739 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3740 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003741 if (mType == MIXER) {
3742 sleepTimeShift = 0;
3743 }
3744
3745 continue;
3746 }
3747 }
Eric Laurent81784c32012-11-19 14:55:58 -08003748 // mMixerStatusIgnoringFastTracks is also updated internally
3749 mMixerStatus = prepareTracks_l(&tracksToRemove);
3750
Andy Hungdae27702016-10-31 14:01:16 -07003751 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003752
Kevin Rocard069c2712018-03-29 19:09:14 -07003753 updateMetadata_l();
3754
Eric Laurent81784c32012-11-19 14:55:58 -08003755 // prevent any changes in effect chain list and in each effect chain
3756 // during mixing and effect process as the audio buffers could be deleted
3757 // or modified if an effect is created or deleted
3758 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003759
3760 // Determine which session to pick up haptic data.
3761 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003762 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003763 // TODO: Write haptic data directly to sink buffer when mixing.
3764 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3765 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003766 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3767 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3768 activeHapticSessionId = track->sessionId();
3769 break;
3770 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003771 if (track->getHapticPlaybackEnabled()) {
3772 activeHapticSessionId = track->sessionId();
3773 break;
3774 }
3775 }
3776 }
3777
Andy Hungc1646382019-04-30 16:12:10 -07003778 // Acquire a local copy of active tracks with lock (release w/o lock).
3779 //
3780 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3781 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3782 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3783 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003784 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003785
Eric Laurentbfb1b832013-01-07 09:53:42 -08003786 if (mBytesRemaining == 0) {
3787 mCurrentWriteLength = 0;
3788 if (mMixerStatus == MIXER_TRACKS_READY) {
3789 // threadLoop_mix() sets mCurrentWriteLength
3790 threadLoop_mix();
3791 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3792 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003793 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003794 // must be written to HAL
3795 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003796 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003797 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003798
3799 // Tally underrun frames as we are inserting 0s here.
3800 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003801 if (track->mFillingUpStatus == Track::FS_ACTIVE
3802 && !track->isStopped()
3803 && !track->isPaused()
3804 && !track->isTerminated()) {
3805 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3806 __func__, track->id(), track->getTrackStateAsString(),
3807 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003808 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3809 }
3810 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003811 }
3812 }
Andy Hung98ef9782014-03-04 14:46:50 -08003813 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003814 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003815 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3816 // or mSinkBuffer (if there are no effects).
3817 //
3818 // This is done pre-effects computation; if effects change to
3819 // support higher precision, this needs to move.
3820 //
3821 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003822 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003823 if (mMixerBufferValid) {
3824 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3825 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3826
Andy Hung2ddee192015-12-18 17:34:44 -08003827 // mono blend occurs for mixer threads only (not direct or offloaded)
3828 // and is handled here if we're going directly to the sink.
3829 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003830 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3831 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003832 }
3833
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003834 if (!hasFastMixer()) {
3835 // Balance must take effect after mono conversion.
3836 // We do it here if there is no FastMixer.
3837 // mBalance detects zero balance within the class for speed (not needed here).
3838 mBalance.setBalance(mMasterBalance.load());
3839 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3840 }
3841
Andy Hung98ef9782014-03-04 14:46:50 -08003842 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003843 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3844
3845 // If we're going directly to the sink and there are haptic channels,
3846 // we should adjust channels as the sample data is partially interleaved
3847 // in this case.
3848 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3849 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3850 mChannelCount + mHapticChannelCount,
3851 audio_bytes_per_sample(format),
3852 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3853 }
Andy Hung98ef9782014-03-04 14:46:50 -08003854 }
3855
Eric Laurentbfb1b832013-01-07 09:53:42 -08003856 mBytesRemaining = mCurrentWriteLength;
3857 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003858 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3859 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3860 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3861 mBytesWritten += mBytesRemaining;
3862 mFramesWritten += framesRemaining;
3863 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003864 mBytesRemaining = 0;
3865 }
Eric Laurent81784c32012-11-19 14:55:58 -08003866
Eric Laurentbfb1b832013-01-07 09:53:42 -08003867 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003868 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003869 for (size_t i = 0; i < effectChains.size(); i ++) {
3870 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003871 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003872 if (activeHapticSessionId != AUDIO_SESSION_NONE
3873 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003874 // Haptic data is active in this case, copy it directly from
3875 // in buffer to out buffer.
3876 const size_t audioBufferSize = mNormalFrameCount
3877 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3878 memcpy_by_audio_format(
3879 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3880 EFFECT_BUFFER_FORMAT,
3881 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3882 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3883 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003884 }
Eric Laurent81784c32012-11-19 14:55:58 -08003885 }
3886 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003887 // Process effect chains for offloaded thread even if no audio
3888 // was read from audio track: process only updates effect state
3889 // and thus does have to be synchronized with audio writes but may have
3890 // to be called while waiting for async write callback
3891 if (mType == OFFLOAD) {
3892 for (size_t i = 0; i < effectChains.size(); i ++) {
3893 effectChains[i]->process_l();
3894 }
3895 }
Eric Laurent81784c32012-11-19 14:55:58 -08003896
Andy Hung98ef9782014-03-04 14:46:50 -08003897 // Only if the Effects buffer is enabled and there is data in the
3898 // Effects buffer (buffer valid), we need to
3899 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003900 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003901 if (mEffectBufferValid) {
3902 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003903
3904 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003905 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3906 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003907 }
3908
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003909 if (!hasFastMixer()) {
3910 // Balance must take effect after mono conversion.
3911 // We do it here if there is no FastMixer.
3912 // mBalance detects zero balance within the class for speed (not needed here).
3913 mBalance.setBalance(mMasterBalance.load());
3914 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3915 }
3916
Andy Hung98ef9782014-03-04 14:46:50 -08003917 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003918 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3919 // The sample data is partially interleaved when haptic channels exist,
3920 // we need to adjust channels here.
3921 if (mHapticChannelCount > 0) {
3922 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3923 mChannelCount + mHapticChannelCount,
3924 audio_bytes_per_sample(mFormat),
3925 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3926 }
Andy Hung98ef9782014-03-04 14:46:50 -08003927 }
3928
Eric Laurent81784c32012-11-19 14:55:58 -08003929 // enable changes in effect chain
3930 unlockEffectChains(effectChains);
3931
Eric Laurentbfb1b832013-01-07 09:53:42 -08003932 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003933 // mSleepTimeUs == 0 means we must write to audio hardware
3934 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003935 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003936 // writePeriodNs is updated >= 0 when ret > 0.
3937 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003938 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003939 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003940 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003941 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003942 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003943 if (ret < 0) {
3944 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003945 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003946 mBytesWritten += ret;
3947 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003948 const int64_t frames = ret / mFrameSize;
3949 mFramesWritten += frames;
3950
3951 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3952 // process information relating to write time.
3953 if (audio_has_proportional_frames(mFormat)) {
3954 // we are in a continuous mixing cycle
3955 if (mMixerStatus == MIXER_TRACKS_READY &&
3956 loopCount == lastLoopCountWritten + 1) {
3957
3958 const double jitterMs =
3959 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3960 {frames, writePeriodNs},
3961 {0, 0} /* lastTimestamp */, mSampleRate);
3962 const double processMs =
3963 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3964
3965 Mutex::Autolock _l(mLock);
3966 mIoJitterMs.add(jitterMs);
3967 mProcessTimeMs.add(processMs);
3968 }
3969
3970 // write blocked detection
3971 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3972 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3973 mNumDelayedWrites++;
3974 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3975 ATRACE_NAME("underrun");
3976 ALOGW("write blocked for %lld msecs, "
3977 "%d delayed writes, thread %d",
3978 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3979 mNumDelayedWrites, mId);
3980 lastWarning = lastIoEndNs;
3981 }
3982 }
3983 }
3984 // update timing info.
3985 mLastIoBeginNs = lastIoBeginNs;
3986 mLastIoEndNs = lastIoEndNs;
3987 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003988 }
3989 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3990 (mMixerStatus == MIXER_DRAIN_ALL)) {
3991 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003992 }
Andy Hung08fb1742015-05-31 23:22:10 -07003993 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003994
3995 if (mThreadThrottle
3996 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003997 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003998 // Limit MixerThread data processing to no more than twice the
3999 // expected processing rate.
4000 //
4001 // This helps prevent underruns with NuPlayer and other applications
4002 // which may set up buffers that are close to the minimum size, or use
4003 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4004 //
4005 // The throttle smooths out sudden large data drains from the device,
4006 // e.g. when it comes out of standby, which often causes problems with
4007 // (1) mixer threads without a fast mixer (which has its own warm-up)
4008 // (2) minimum buffer sized tracks (even if the track is full,
4009 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004010 //
4011 // Total time spent in last processing cycle equals time spent in
4012 // 1. threadLoop_write, as well as time spent in
4013 // 2. threadLoop_mix (significant for heavy mixing, especially
4014 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004015
Andy Hung446f4df2019-02-21 12:26:41 -08004016 // it's OK if deltaMs is an overestimate.
4017
4018 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004019
Ivan Lozanoea04d392017-11-07 14:37:07 -08004020 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004021 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004022 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004023
Andy Hung08fb1742015-05-31 23:22:10 -07004024 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004025 // notify of throttle start on verbose log
4026 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4027 "mixer(%p) throttle begin:"
4028 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004029 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004030 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004031 // Throttle must be attributed to the previous mixer loop's write time
4032 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004033 // This also ensures proper timing statistics.
4034 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004035 } else {
4036 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4037 if (diff > 0) {
4038 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004039 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004040 ALOGD_IF(!isSingleDeviceType(
4041 outDeviceTypes(), audio_is_a2dp_out_device) &&
4042 !isSingleDeviceType(
4043 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004044 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004045 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4046 }
Andy Hung08fb1742015-05-31 23:22:10 -07004047 }
4048 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004049 }
Eric Laurent81784c32012-11-19 14:55:58 -08004050
Eric Laurentbfb1b832013-01-07 09:53:42 -08004051 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004052 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004053 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004054 // suspended requires accurate metering of sleep time.
4055 if (isSuspended()) {
4056 // advance by expected sleepTime
4057 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4058 const nsecs_t nowNs = systemTime();
4059
4060 // compute expected next time vs current time.
4061 // (negative deltas are treated as delays).
4062 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4063 if (deltaNs < -kMaxNextBufferDelayNs) {
4064 // Delays longer than the max allowed trigger a reset.
4065 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4066 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4067 timeLoopNextNs = nowNs + deltaNs;
4068 } else if (deltaNs < 0) {
4069 // Delays within the max delay allowed: zero the delta/sleepTime
4070 // to help the system catch up in the next iteration(s)
4071 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4072 deltaNs = 0;
4073 }
4074 // update sleep time (which is >= 0)
4075 mSleepTimeUs = deltaNs / 1000;
4076 }
Eric Laurente93cc032016-05-05 10:15:10 -07004077 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4078 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004079 }
Glenn Kastene7754022014-10-31 12:11:26 -07004080 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004081 }
Eric Laurent81784c32012-11-19 14:55:58 -08004082 }
4083
4084 // Finally let go of removed track(s), without the lock held
4085 // since we can't guarantee the destructors won't acquire that
4086 // same lock. This will also mutate and push a new fast mixer state.
4087 threadLoop_removeTracks(tracksToRemove);
4088 tracksToRemove.clear();
4089
4090 // FIXME I don't understand the need for this here;
4091 // it was in the original code but maybe the
4092 // assignment in saveOutputTracks() makes this unnecessary?
4093 clearOutputTracks();
4094
4095 // Effect chains will be actually deleted here if they were removed from
4096 // mEffectChains list during mixing or effects processing
4097 effectChains.clear();
4098
4099 // FIXME Note that the above .clear() is no longer necessary since effectChains
4100 // is now local to this block, but will keep it for now (at least until merge done).
4101 }
4102
Eric Laurentbfb1b832013-01-07 09:53:42 -08004103 threadLoop_exit();
4104
Eric Laurentcf817a22014-08-04 20:36:31 -07004105 if (!mStandby) {
4106 threadLoop_standby();
4107 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004108 }
4109
4110 releaseWakeLock();
4111
4112 ALOGV("Thread %p type %d exiting", this, mType);
4113 return false;
4114}
4115
Eric Laurentbfb1b832013-01-07 09:53:42 -08004116// removeTracks_l() must be called with ThreadBase::mLock held
4117void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4118{
Andy Hungfe726a62018-09-27 15:17:25 -07004119 for (const auto& track : tracksToRemove) {
4120 mActiveTracks.remove(track);
4121 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4122 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4123 if (chain != 0) {
4124 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4125 __func__, track->id(), chain.get(), track->sessionId());
4126 chain->decActiveTrackCnt();
4127 }
4128 // If an external client track, inform APM we're no longer active, and remove if needed.
4129 // We do this under lock so that the state is consistent if the Track is destroyed.
4130 if (track->isExternalTrack()) {
4131 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004132 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004133 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004134 }
4135 }
Andy Hungfe726a62018-09-27 15:17:25 -07004136 if (track->isTerminated()) {
4137 // remove from our tracks vector
4138 removeTrack_l(track);
4139 }
jiabineb3bda02020-06-30 14:07:03 -07004140 if (mHapticChannelCount > 0 &&
4141 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4142 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004143 mLock.unlock();
4144 // Unlock due to VibratorService will lock for this call and will
4145 // call Tracks.mute/unmute which also require thread's lock.
4146 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4147 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004148
4149 // When the track is stop, set the haptic intensity as MUTE
4150 // for the HapticGenerator effect.
4151 if (chain != nullptr) {
4152 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4153 }
jiabin245cdd92018-12-07 17:55:15 -08004154 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004155 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004156}
Eric Laurent81784c32012-11-19 14:55:58 -08004157
Eric Laurentaccc1472013-09-20 09:36:34 -07004158status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4159{
4160 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004161 ExtendedTimestamp ets;
4162 status_t status = mNormalSink->getTimestamp(ets);
4163 if (status == NO_ERROR) {
4164 status = ets.getBestTimestamp(&timestamp);
4165 }
4166 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004167 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004168 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07004169 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004170 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07004171 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11004172 if (mDownstreamLatencyStatMs.getN() > 0) {
4173 const uint32_t positionOffset =
4174 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4175 if (positionOffset > timestamp.mPosition) {
4176 timestamp.mPosition = 0;
4177 } else {
4178 timestamp.mPosition -= positionOffset;
4179 }
4180 }
Eric Laurentaccc1472013-09-20 09:36:34 -07004181 return NO_ERROR;
4182 }
4183 }
4184 return INVALID_OPERATION;
4185}
Eric Laurent1c333e22014-05-20 10:48:17 -07004186
Eric Laurenteab90452019-06-24 15:17:46 -07004187// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4188// still applied by the mixer.
4189// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4190// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4191// if more than one track are active
4192status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4193{
4194 status_t result = NO_ERROR;
4195 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4196 if (*volume != mLeftVolFloat) {
4197 result = mOutput->stream->setVolume(*volume, *volume);
4198 ALOGE_IF(result != OK,
4199 "Error when setting output stream volume: %d", result);
4200 if (result == NO_ERROR) {
4201 mLeftVolFloat = *volume;
4202 }
4203 }
4204 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4205 // remove stream volume contribution from software volume.
4206 if (mLeftVolFloat == *volume) {
4207 *volume = 1.0f;
4208 }
4209 }
4210 return result;
4211}
4212
Eric Laurent054d9d32015-04-24 08:48:48 -07004213status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4214 audio_patch_handle_t *handle)
4215{
Andy Hungf60abce2016-08-26 11:37:54 -07004216 status_t status;
4217 if (property_get_bool("af.patch_park", false /* default_value */)) {
4218 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4219 // or if HAL does not properly lock against access.
4220 AutoPark<FastMixer> park(mFastMixer);
4221 status = PlaybackThread::createAudioPatch_l(patch, handle);
4222 } else {
4223 status = PlaybackThread::createAudioPatch_l(patch, handle);
4224 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004225 return status;
4226}
4227
Eric Laurent1c333e22014-05-20 10:48:17 -07004228status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4229 audio_patch_handle_t *handle)
4230{
4231 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004232
4233 // store new device and send to effects
4234 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004235 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004236 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004237 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4238 && !mOutput->audioHwDev->supportsAudioPatches(),
4239 "Enumerated device type(%#x) must not be used "
4240 "as it does not support audio patches",
4241 patch->sinks[i].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004242 type |= patch->sinks[i].ext.device.type;
jiabinc52b1ff2019-10-31 17:20:42 -07004243 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4244 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004245 }
4246
François Gaffie0c280aa2018-07-25 10:02:15 +02004247 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004248#ifdef ADD_BATTERY_DATA
4249 // when changing the audio output device, call addBatteryData to notify
4250 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004251 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004252 uint32_t params = 0;
4253 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004254 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004255 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004256 }
4257
Eric Laurent054d9d32015-04-24 08:48:48 -07004258 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004259 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004260 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4261 }
4262
4263 if (params != 0) {
4264 addBatteryData(params);
4265 }
4266 }
4267#endif
4268
4269 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004270 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004271 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004272
jiabinc52b1ff2019-10-31 17:20:42 -07004273 // mPatch.num_sinks is not set when the thread is created so that
4274 // the first patch creation triggers an ioConfigChanged callback
4275 bool configChanged = (mPatch.num_sinks == 0) ||
4276 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004277 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004278 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004279 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004280
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004281 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004282 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4283 status = hwDevice->createAudioPatch(patch->num_sources,
4284 patch->sources,
4285 patch->num_sinks,
4286 patch->sinks,
4287 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004288 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004289 char *address;
4290 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4291 //FIXME: we only support address on first sink with HAL version < 3.0
4292 address = audio_device_address_to_parameter(
4293 patch->sinks[0].ext.device.type,
4294 patch->sinks[0].ext.device.address);
4295 } else {
4296 address = (char *)calloc(1, 1);
4297 }
4298 AudioParameter param = AudioParameter(String8(address));
4299 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004300 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004301 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004302 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004303 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004304 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004305
4306 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004307 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004308 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004309 // also dispatch to active AudioTracks for MediaMetrics
4310 for (const auto &track : mActiveTracks) {
4311 track->logEndInterval();
4312 track->logBeginInterval(patchSinksAsString);
4313 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004314
Eric Laurente8726fe2015-06-26 09:39:24 -07004315 if (configChanged) {
4316 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4317 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004318 return status;
4319}
4320
Eric Laurent054d9d32015-04-24 08:48:48 -07004321status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4322{
Andy Hungf60abce2016-08-26 11:37:54 -07004323 status_t status;
4324 if (property_get_bool("af.patch_park", false /* default_value */)) {
4325 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4326 // or if HAL does not properly lock against access.
4327 AutoPark<FastMixer> park(mFastMixer);
4328 status = PlaybackThread::releaseAudioPatch_l(handle);
4329 } else {
4330 status = PlaybackThread::releaseAudioPatch_l(handle);
4331 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004332 return status;
4333}
4334
Eric Laurent1c333e22014-05-20 10:48:17 -07004335status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4336{
4337 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004338
jiabinc52b1ff2019-10-31 17:20:42 -07004339 mPatch = audio_patch{};
4340 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004341
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004342 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004343 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4344 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004345 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004346 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004347 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004348 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004349 }
4350 return status;
4351}
4352
Eric Laurent83b88082014-06-20 18:31:16 -07004353void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4354{
4355 Mutex::Autolock _l(mLock);
4356 mTracks.add(track);
4357}
4358
4359void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4360{
4361 Mutex::Autolock _l(mLock);
4362 destroyTrack_l(track);
4363}
4364
Mikhail Naganovdc769682018-05-04 15:34:08 -07004365void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004366{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004367 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004368 config->role = AUDIO_PORT_ROLE_SOURCE;
4369 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4370 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004371 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4372 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4373 config->flags.output = mOutput->flags;
4374 }
Eric Laurent83b88082014-06-20 18:31:16 -07004375}
4376
Eric Laurent81784c32012-11-19 14:55:58 -08004377// ----------------------------------------------------------------------------
4378
4379AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004380 audio_io_handle_t id, bool systemReady, type_t type)
4381 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004382 // mAudioMixer below
4383 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004384 mFastMixerFutex(0),
4385 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004386 // mOutputSink below
4387 // mPipeSink below
4388 // mNormalSink below
4389{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004390 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004391 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004392 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004393 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004394 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4395 mNormalFrameCount);
4396 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4397
Andy Hungfbfc3952015-01-15 13:33:51 -08004398 if (type == DUPLICATING) {
4399 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4400 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4401 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4402 return;
4403 }
Eric Laurent81784c32012-11-19 14:55:58 -08004404 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004405 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004406 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004407 const NBAIO_Format offers[1] = {Format_from_SR_C(
4408 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004409#if !LOG_NDEBUG
4410 ssize_t index =
4411#else
4412 (void)
4413#endif
4414 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004415 ALOG_ASSERT(index == 0);
4416
4417 // initialize fast mixer depending on configuration
4418 bool initFastMixer;
4419 switch (kUseFastMixer) {
4420 case FastMixer_Never:
4421 initFastMixer = false;
4422 break;
4423 case FastMixer_Always:
4424 initFastMixer = true;
4425 break;
4426 case FastMixer_Static:
4427 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004428 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4429 // where the period is less than an experimentally determined threshold that can be
4430 // scheduled reliably with CFS. However, the BT A2DP HAL is
4431 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4432 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004433 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004434 break;
4435 }
Andy Hungfda69402017-02-15 14:33:12 -08004436 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4437 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4438 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004439 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004440 audio_format_t fastMixerFormat;
4441 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4442 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4443 } else {
4444 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4445 }
4446 if (mFormat != fastMixerFormat) {
4447 // change our Sink format to accept our intermediate precision
4448 mFormat = fastMixerFormat;
4449 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004450 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004451 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4452 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4453 }
Eric Laurent81784c32012-11-19 14:55:58 -08004454
4455 // create a MonoPipe to connect our submix to FastMixer
4456 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004457
Andy Hung1258c1a2014-05-23 21:22:17 -07004458 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004459 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004460 format.mFormat = fastMixerFormat;
4461 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4462
Eric Laurent81784c32012-11-19 14:55:58 -08004463 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4464 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4465 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4466 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4467 const NBAIO_Format offers[1] = {format};
4468 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004469#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004470 ssize_t index =
4471#else
4472 (void)
4473#endif
4474 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004475 ALOG_ASSERT(index == 0);
4476 monoPipe->setAvgFrames((mScreenState & 1) ?
4477 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4478 mPipeSink = monoPipe;
4479
Eric Laurent81784c32012-11-19 14:55:58 -08004480 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004481 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004482 FastMixerStateQueue *sq = mFastMixer->sq();
4483#ifdef STATE_QUEUE_DUMP
4484 sq->setObserverDump(&mStateQueueObserverDump);
4485 sq->setMutatorDump(&mStateQueueMutatorDump);
4486#endif
4487 FastMixerState *state = sq->begin();
4488 FastTrack *fastTrack = &state->mFastTracks[0];
4489 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4490 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4491 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004492 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4493 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004494 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004495 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004496 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004497 fastTrack->mGeneration++;
4498 state->mFastTracksGen++;
4499 state->mTrackMask = 1;
4500 // fast mixer will use the HAL output sink
4501 state->mOutputSink = mOutputSink.get();
4502 state->mOutputSinkGen++;
4503 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004504 // specify sink channel mask when haptic channel mask present as it can not
4505 // be calculated directly from channel count
4506 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4507 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004508 state->mCommand = FastMixerState::COLD_IDLE;
4509 // already done in constructor initialization list
4510 //mFastMixerFutex = 0;
4511 state->mColdFutexAddr = &mFastMixerFutex;
4512 state->mColdGen++;
4513 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004514 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4515 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004516 sq->end();
4517 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4518
Eric Tan0513b5d2018-09-17 10:32:48 -07004519 NBLog::thread_info_t info;
4520 info.id = mId;
4521 info.type = NBLog::FASTMIXER;
4522 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4523
Eric Laurent81784c32012-11-19 14:55:58 -08004524 // start the fast mixer
4525 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4526 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004527 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004528 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004529
4530#ifdef AUDIO_WATCHDOG
4531 // create and start the watchdog
4532 mAudioWatchdog = new AudioWatchdog();
4533 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4534 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4535 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004536 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004537#endif
Andy Hung8946a282018-04-19 20:04:56 -07004538 } else {
4539#ifdef TEE_SINK
4540 // Only use the MixerThread tee if there is no FastMixer.
4541 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4542 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4543#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004544 }
4545
4546 switch (kUseFastMixer) {
4547 case FastMixer_Never:
4548 case FastMixer_Dynamic:
4549 mNormalSink = mOutputSink;
4550 break;
4551 case FastMixer_Always:
4552 mNormalSink = mPipeSink;
4553 break;
4554 case FastMixer_Static:
4555 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4556 break;
4557 }
4558}
4559
4560AudioFlinger::MixerThread::~MixerThread()
4561{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004562 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004563 FastMixerStateQueue *sq = mFastMixer->sq();
4564 FastMixerState *state = sq->begin();
4565 if (state->mCommand == FastMixerState::COLD_IDLE) {
4566 int32_t old = android_atomic_inc(&mFastMixerFutex);
4567 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004568 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004569 }
4570 }
4571 state->mCommand = FastMixerState::EXIT;
4572 sq->end();
4573 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4574 mFastMixer->join();
4575 // Though the fast mixer thread has exited, it's state queue is still valid.
4576 // We'll use that extract the final state which contains one remaining fast track
4577 // corresponding to our sub-mix.
4578 state = sq->begin();
4579 ALOG_ASSERT(state->mTrackMask == 1);
4580 FastTrack *fastTrack = &state->mFastTracks[0];
4581 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4582 delete fastTrack->mBufferProvider;
4583 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004584 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004585#ifdef AUDIO_WATCHDOG
4586 if (mAudioWatchdog != 0) {
4587 mAudioWatchdog->requestExit();
4588 mAudioWatchdog->requestExitAndWait();
4589 mAudioWatchdog.clear();
4590 }
4591#endif
4592 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004593 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004594 delete mAudioMixer;
4595}
4596
4597
4598uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4599{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004600 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004601 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4602 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4603 }
4604 return latency;
4605}
4606
Eric Laurentbfb1b832013-01-07 09:53:42 -08004607ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004608{
4609 // FIXME we should only do one push per cycle; confirm this is true
4610 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004611 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004612 FastMixerStateQueue *sq = mFastMixer->sq();
4613 FastMixerState *state = sq->begin();
4614 if (state->mCommand != FastMixerState::MIX_WRITE &&
4615 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4616 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004617
4618 // FIXME workaround for first HAL write being CPU bound on some devices
4619 ATRACE_BEGIN("write");
4620 mOutput->write((char *)mSinkBuffer, 0);
4621 ATRACE_END();
4622
Eric Laurent81784c32012-11-19 14:55:58 -08004623 int32_t old = android_atomic_inc(&mFastMixerFutex);
4624 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004625 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004626 }
4627#ifdef AUDIO_WATCHDOG
4628 if (mAudioWatchdog != 0) {
4629 mAudioWatchdog->resume();
4630 }
4631#endif
4632 }
4633 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004634#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004635 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004636 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004637#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004638 sq->end();
4639 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4640 if (kUseFastMixer == FastMixer_Dynamic) {
4641 mNormalSink = mPipeSink;
4642 }
4643 } else {
4644 sq->end(false /*didModify*/);
4645 }
4646 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004647 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004648}
4649
4650void AudioFlinger::MixerThread::threadLoop_standby()
4651{
4652 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004653 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004654 FastMixerStateQueue *sq = mFastMixer->sq();
4655 FastMixerState *state = sq->begin();
4656 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004657 // Report any frames trapped in the Monopipe
4658 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4659 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4660 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4661 "monoPipeWritten:%lld monoPipeLeft:%lld",
4662 (long long)mFramesWritten, (long long)mSuspendedFrames,
4663 (long long)mPipeSink->framesWritten(), pipeFrames);
4664 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4665
Eric Laurent81784c32012-11-19 14:55:58 -08004666 state->mCommand = FastMixerState::COLD_IDLE;
4667 state->mColdFutexAddr = &mFastMixerFutex;
4668 state->mColdGen++;
4669 mFastMixerFutex = 0;
4670 sq->end();
4671 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4672 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4673 if (kUseFastMixer == FastMixer_Dynamic) {
4674 mNormalSink = mOutputSink;
4675 }
4676#ifdef AUDIO_WATCHDOG
4677 if (mAudioWatchdog != 0) {
4678 mAudioWatchdog->pause();
4679 }
4680#endif
4681 } else {
4682 sq->end(false /*didModify*/);
4683 }
4684 }
4685 PlaybackThread::threadLoop_standby();
4686}
4687
Eric Laurentbfb1b832013-01-07 09:53:42 -08004688bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4689{
4690 return false;
4691}
4692
4693bool AudioFlinger::PlaybackThread::shouldStandby_l()
4694{
4695 return !mStandby;
4696}
4697
4698bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4699{
4700 Mutex::Autolock _l(mLock);
4701 return waitingAsyncCallback_l();
4702}
4703
Eric Laurent81784c32012-11-19 14:55:58 -08004704// shared by MIXER and DIRECT, overridden by DUPLICATING
4705void AudioFlinger::PlaybackThread::threadLoop_standby()
4706{
4707 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004708 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004709 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004710 // discard any pending drain or write ack by incrementing sequence
4711 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4712 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004713 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004714 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4715 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004716 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004717 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004718}
4719
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004720void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4721{
4722 ALOGV("signal playback thread");
4723 broadcast_l();
4724}
4725
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004726void AudioFlinger::PlaybackThread::onAsyncError()
4727{
4728 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4729 invalidateTracks((audio_stream_type_t)i);
4730 }
4731}
4732
Eric Laurent81784c32012-11-19 14:55:58 -08004733void AudioFlinger::MixerThread::threadLoop_mix()
4734{
Eric Laurent81784c32012-11-19 14:55:58 -08004735 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004736 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004737 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004738 // increase sleep time progressively when application underrun condition clears.
4739 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4740 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4741 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004742 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004743 sleepTimeShift--;
4744 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004745 mSleepTimeUs = 0;
4746 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004747 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004748
Eric Laurent81784c32012-11-19 14:55:58 -08004749}
4750
4751void AudioFlinger::MixerThread::threadLoop_sleepTime()
4752{
4753 // If no tracks are ready, sleep once for the duration of an output
4754 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004755 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004756 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004757 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4758 // Using the Monopipe availableToWrite, we estimate the
4759 // sleep time to retry for more data (before we underrun).
4760 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4761 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4762 const size_t pipeFrames = monoPipe->maxFrames();
4763 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4764 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4765 const size_t framesDelay = std::min(
4766 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4767 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4768 pipeFrames, framesLeft, framesDelay);
4769 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4770 } else {
4771 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4772 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4773 mSleepTimeUs = kMinThreadSleepTimeUs;
4774 }
4775 // reduce sleep time in case of consecutive application underruns to avoid
4776 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4777 // duration we would end up writing less data than needed by the audio HAL if
4778 // the condition persists.
4779 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4780 sleepTimeShift++;
4781 }
Eric Laurent81784c32012-11-19 14:55:58 -08004782 }
4783 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004784 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004785 }
4786 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004787 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4788 // before effects processing or output.
4789 if (mMixerBufferValid) {
4790 memset(mMixerBuffer, 0, mMixerBufferSize);
4791 } else {
4792 memset(mSinkBuffer, 0, mSinkBufferSize);
4793 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004794 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004795 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4796 "anticipated start");
4797 }
4798 // TODO add standby time extension fct of effect tail
4799}
4800
4801// prepareTracks_l() must be called with ThreadBase::mLock held
4802AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4803 Vector< sp<Track> > *tracksToRemove)
4804{
Andy Hungc0691382018-09-12 18:01:57 -07004805 // clean up deleted track ids in AudioMixer before allocating new tracks
4806 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4807 // for each trackId, destroy it in the AudioMixer
4808 if (mAudioMixer->exists(trackId)) {
4809 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004810 }
4811 });
Andy Hungc0691382018-09-12 18:01:57 -07004812 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004813
4814 mixer_state mixerStatus = MIXER_IDLE;
4815 // find out which tracks need to be processed
4816 size_t count = mActiveTracks.size();
4817 size_t mixedTracks = 0;
4818 size_t tracksWithEffect = 0;
4819 // counts only _active_ fast tracks
4820 size_t fastTracks = 0;
4821 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4822
4823 float masterVolume = mMasterVolume;
4824 bool masterMute = mMasterMute;
4825
4826 if (masterMute) {
4827 masterVolume = 0;
4828 }
4829 // Delegate master volume control to effect in output mix effect chain if needed
4830 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4831 if (chain != 0) {
4832 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4833 chain->setVolume_l(&v, &v);
4834 masterVolume = (float)((v + (1 << 23)) >> 24);
4835 chain.clear();
4836 }
4837
4838 // prepare a new state to push
4839 FastMixerStateQueue *sq = NULL;
4840 FastMixerState *state = NULL;
4841 bool didModify = false;
4842 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004843 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004844 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004845 sq = mFastMixer->sq();
4846 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004847 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004848 }
4849
Andy Hung69aed5f2014-02-25 17:24:40 -08004850 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004851 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004852
Andy Hungbd3b2b02018-05-21 10:53:11 -07004853 // DeferredOperations handles statistics after setting mixerStatus.
4854 class DeferredOperations {
4855 public:
Andy Hungea840382020-05-05 21:50:17 -07004856 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4857 : mMixerStatus(mixerStatus)
4858 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07004859
4860 // when leaving scope, tally frames properly.
4861 ~DeferredOperations() {
4862 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4863 // because that is when the underrun occurs.
4864 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07004865 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08004866 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004867 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07004868 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07004869 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004870 }
4871 }
Andy Hungea840382020-05-05 21:50:17 -07004872 // send the max underrun frames for this mixer period
4873 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004874 }
4875
4876 // tallyUnderrunFrames() is called to update the track counters
4877 // with the number of underrun frames for a particular mixer period.
4878 // We defer tallying until we know the final mixer status.
4879 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4880 mUnderrunFrames.emplace_back(track, underrunFrames);
4881 }
4882
4883 private:
4884 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07004885 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07004886 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07004887 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004888 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07004889
jiabin245cdd92018-12-07 17:55:15 -08004890 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004891 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004892 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004893
4894 // this const just means the local variable doesn't change
4895 Track* const track = t.get();
4896
4897 // process fast tracks
4898 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004899 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4900 "%s(%d): FastTrack(%d) present without FastMixer",
4901 __func__, id(), track->id());
4902
jiabin245cdd92018-12-07 17:55:15 -08004903 if (track->getHapticPlaybackEnabled()) {
4904 noFastHapticTrack = false;
4905 }
Eric Laurent81784c32012-11-19 14:55:58 -08004906
4907 // It's theoretically possible (though unlikely) for a fast track to be created
4908 // and then removed within the same normal mix cycle. This is not a problem, as
4909 // the track never becomes active so it's fast mixer slot is never touched.
4910 // The converse, of removing an (active) track and then creating a new track
4911 // at the identical fast mixer slot within the same normal mix cycle,
4912 // is impossible because the slot isn't marked available until the end of each cycle.
4913 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004914 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004915 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4916 FastTrack *fastTrack = &state->mFastTracks[j];
4917
4918 // Determine whether the track is currently in underrun condition,
4919 // and whether it had a recent underrun.
4920 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4921 FastTrackUnderruns underruns = ftDump->mUnderruns;
4922 uint32_t recentFull = (underruns.mBitFields.mFull -
4923 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4924 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4925 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4926 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4927 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4928 uint32_t recentUnderruns = recentPartial + recentEmpty;
4929 track->mObservedUnderruns = underruns;
4930 // don't count underruns that occur while stopping or pausing
4931 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004932 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004933 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4934 recentUnderruns > 0) {
4935 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004936 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004937 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004938 // Immediately account for FastTrack underruns.
4939 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004940
4941 // This is similar to the state machine for normal tracks,
4942 // with a few modifications for fast tracks.
4943 bool isActive = true;
4944 switch (track->mState) {
4945 case TrackBase::STOPPING_1:
4946 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004947 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004948 track->mState = TrackBase::STOPPING_2;
4949 }
4950 break;
4951 case TrackBase::PAUSING:
4952 // ramp down is not yet implemented
4953 track->setPaused();
4954 break;
4955 case TrackBase::RESUMING:
4956 // ramp up is not yet implemented
4957 track->mState = TrackBase::ACTIVE;
4958 break;
4959 case TrackBase::ACTIVE:
4960 if (recentFull > 0 || recentPartial > 0) {
4961 // track has provided at least some frames recently: reset retry count
4962 track->mRetryCount = kMaxTrackRetries;
4963 }
4964 if (recentUnderruns == 0) {
4965 // no recent underruns: stay active
4966 break;
4967 }
4968 // there has recently been an underrun of some kind
4969 if (track->sharedBuffer() == 0) {
4970 // were any of the recent underruns "empty" (no frames available)?
4971 if (recentEmpty == 0) {
4972 // no, then ignore the partial underruns as they are allowed indefinitely
4973 break;
4974 }
4975 // there has recently been an "empty" underrun: decrement the retry counter
4976 if (--(track->mRetryCount) > 0) {
4977 break;
4978 }
4979 // indicate to client process that the track was disabled because of underrun;
4980 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004981 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004982 // remove from active list, but state remains ACTIVE [confusing but true]
4983 isActive = false;
4984 break;
4985 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004986 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004987 case TrackBase::STOPPING_2:
4988 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004989 case TrackBase::STOPPED:
4990 case TrackBase::FLUSHED: // flush() while active
4991 // Check for presentation complete if track is inactive
4992 // We have consumed all the buffers of this track.
4993 // This would be incomplete if we auto-paused on underrun
4994 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004995 uint32_t latency = 0;
4996 status_t result = mOutput->stream->getLatency(&latency);
4997 ALOGE_IF(result != OK,
4998 "Error when retrieving output stream latency: %d", result);
4999 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005000 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005001 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5002 // track stays in active list until presentation is complete
5003 break;
5004 }
5005 }
5006 if (track->isStopping_2()) {
5007 track->mState = TrackBase::STOPPED;
5008 }
5009 if (track->isStopped()) {
5010 // Can't reset directly, as fast mixer is still polling this track
5011 // track->reset();
5012 // So instead mark this track as needing to be reset after push with ack
5013 resetMask |= 1 << i;
5014 }
5015 isActive = false;
5016 break;
5017 case TrackBase::IDLE:
5018 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005019 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005020 }
5021
5022 if (isActive) {
5023 // was it previously inactive?
5024 if (!(state->mTrackMask & (1 << j))) {
5025 ExtendedAudioBufferProvider *eabp = track;
5026 VolumeProvider *vp = track;
5027 fastTrack->mBufferProvider = eabp;
5028 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005029 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005030 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005031 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005032 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08005033 fastTrack->mGeneration++;
5034 state->mTrackMask |= 1 << j;
5035 didModify = true;
5036 // no acknowledgement required for newly active tracks
5037 }
Kevin Rocard12381092018-04-11 09:19:59 -07005038 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005039 float volume;
5040 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5041 volume = 0.f;
5042 } else {
5043 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5044 }
5045
5046 handleVoipVolume_l(&volume);
5047
Eric Laurent81784c32012-11-19 14:55:58 -08005048 // cache the combined master volume and stream type volume for fast mixer; this
5049 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005050 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005051 proxy->framesReleased()).first;
5052 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005053 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005054 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5055 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5056 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005057
Kevin Rocard12381092018-04-11 09:19:59 -07005058 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005059 ++fastTracks;
5060 } else {
5061 // was it previously active?
5062 if (state->mTrackMask & (1 << j)) {
5063 fastTrack->mBufferProvider = NULL;
5064 fastTrack->mGeneration++;
5065 state->mTrackMask &= ~(1 << j);
5066 didModify = true;
5067 // If any fast tracks were removed, we must wait for acknowledgement
5068 // because we're about to decrement the last sp<> on those tracks.
5069 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5070 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005071 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5072 // AudioTrack may start (which may not be with a start() but with a write()
5073 // after underrun) and immediately paused or released. In that case the
5074 // FastTrack state hasn't had time to update.
5075 // TODO Remove the ALOGW when this theory is confirmed.
5076 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005077 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5078 j, track->mState, state->mTrackMask, recentUnderruns,
5079 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005080 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005081 }
5082 tracksToRemove->add(track);
5083 // Avoids a misleading display in dumpsys
5084 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5085 }
jiabin245cdd92018-12-07 17:55:15 -08005086 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5087 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5088 didModify = true;
5089 }
Eric Laurent81784c32012-11-19 14:55:58 -08005090 continue;
5091 }
5092
5093 { // local variable scope to avoid goto warning
5094
5095 audio_track_cblk_t* cblk = track->cblk();
5096
5097 // The first time a track is added we wait
5098 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005099 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005100
5101 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005102 // use the trackId as the AudioMixer name.
5103 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005104 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005105 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005106 track->mChannelMask,
5107 track->mFormat,
5108 track->mSessionId);
5109 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005110 ALOGW("%s(): AudioMixer cannot create track(%d)"
5111 " mask %#x, format %#x, sessionId %d",
5112 __func__, trackId,
5113 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005114 tracksToRemove->add(track);
5115 track->invalidate(); // consider it dead.
5116 continue;
5117 }
5118 }
5119
Eric Laurent81784c32012-11-19 14:55:58 -08005120 // make sure that we have enough frames to mix one full buffer.
5121 // enforce this condition only once to enable draining the buffer in case the client
5122 // app does not call stop() and relies on underrun to stop:
5123 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5124 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005125 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005126 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005127 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005128
5129 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005130 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005131 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5132 // add frames already consumed but not yet released by the resampler
5133 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005134 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005135
Eric Laurent81784c32012-11-19 14:55:58 -08005136 uint32_t minFrames = 1;
5137 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5138 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005139 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005140 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005141
5142 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005143 if (ATRACE_ENABLED()) {
5144 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005145 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005146 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005147 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005148 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005149 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005150 !track->isPaused() && !track->isTerminated())
5151 {
Andy Hungc0691382018-09-12 18:01:57 -07005152 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005153
5154 mixedTracks++;
5155
Andy Hung69aed5f2014-02-25 17:24:40 -08005156 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5157 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005158 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005159 if (track->mainBuffer() != mSinkBuffer &&
5160 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005161 if (mEffectBufferEnabled) {
5162 mEffectBufferValid = true; // Later can set directly.
5163 }
Eric Laurent81784c32012-11-19 14:55:58 -08005164 chain = getEffectChain_l(track->sessionId());
5165 // Delegate volume control to effect in track effect chain if needed
5166 if (chain != 0) {
5167 tracksWithEffect++;
5168 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005169 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005170 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005171 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005172 }
5173 }
5174
5175
5176 int param = AudioMixer::VOLUME;
5177 if (track->mFillingUpStatus == Track::FS_FILLED) {
5178 // no ramp for the first volume setting
5179 track->mFillingUpStatus = Track::FS_ACTIVE;
5180 if (track->mState == TrackBase::RESUMING) {
5181 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005182 // If a new track is paused immediately after start, do not ramp on resume.
5183 if (cblk->mServer != 0) {
5184 param = AudioMixer::RAMP_VOLUME;
5185 }
Eric Laurent81784c32012-11-19 14:55:58 -08005186 }
Andy Hungc0691382018-09-12 18:01:57 -07005187 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005188 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005189 // FIXME should not make a decision based on mServer
5190 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005191 // If the track is stopped before the first frame was mixed,
5192 // do not apply ramp
5193 param = AudioMixer::RAMP_VOLUME;
5194 }
5195
5196 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005197 uint32_t vl, vr; // in U8.24 integer format
5198 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005199 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005200 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005201 // Always fetch volumeshaper volume to ensure state is updated.
5202 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5203 const float vh = track->getVolumeHandler()->getVolume(
5204 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005205
Eric Laurenteab90452019-06-24 15:17:46 -07005206 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5207 v = 0;
5208 }
5209
5210 handleVoipVolume_l(&v);
5211
5212 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005213 vl = vr = 0;
5214 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005215 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005216 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005217 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005218 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5219 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005220 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005221 if (vlf > GAIN_FLOAT_UNITY) {
5222 ALOGV("Track left volume out of range: %.3g", vlf);
5223 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005224 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005225 if (vrf > GAIN_FLOAT_UNITY) {
5226 ALOGV("Track right volume out of range: %.3g", vrf);
5227 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005228 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005229 // now apply the master volume and stream type volume and shaper volume
5230 vlf *= v * vh;
5231 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005232 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005233 // then derive vl and vr as U8.24 versions for the effect chain
5234 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5235 vl = (uint32_t) (scaleto8_24 * vlf);
5236 vr = (uint32_t) (scaleto8_24 * vrf);
5237 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005238 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005239 // send level comes from shared memory and so may be corrupt
5240 if (sendLevel > MAX_GAIN_INT) {
5241 ALOGV("Track send level out of range: %04X", sendLevel);
5242 sendLevel = MAX_GAIN_INT;
5243 }
Andy Hung6be49402014-05-30 10:42:03 -07005244 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5245 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005246 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005247
Kevin Rocard12381092018-04-11 09:19:59 -07005248 track->setFinalVolume((vrf + vlf) / 2.f);
5249
Eric Laurent81784c32012-11-19 14:55:58 -08005250 // Delegate volume control to effect in track effect chain if needed
5251 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5252 // Do not ramp volume if volume is controlled by effect
5253 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005254 // Update remaining floating point volume levels
5255 vlf = (float)vl / (1 << 24);
5256 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005257 track->mHasVolumeController = true;
5258 } else {
5259 // force no volume ramp when volume controller was just disabled or removed
5260 // from effect chain to avoid volume spike
5261 if (track->mHasVolumeController) {
5262 param = AudioMixer::VOLUME;
5263 }
5264 track->mHasVolumeController = false;
5265 }
5266
Eric Laurent81784c32012-11-19 14:55:58 -08005267 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005268 mAudioMixer->setBufferProvider(trackId, track);
5269 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005270
Andy Hungc0691382018-09-12 18:01:57 -07005271 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5272 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5273 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005274 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005275 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005276 AudioMixer::TRACK,
5277 AudioMixer::FORMAT, (void *)track->format());
5278 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005279 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005280 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005281 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005282 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005283 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005284 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005285 AudioMixer::MIXER_CHANNEL_MASK,
5286 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005287 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005288 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005289 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005290 if (reqSampleRate == 0) {
5291 reqSampleRate = mSampleRate;
5292 } else if (reqSampleRate > maxSampleRate) {
5293 reqSampleRate = maxSampleRate;
5294 }
Eric Laurent81784c32012-11-19 14:55:58 -08005295 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005296 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005297 AudioMixer::RESAMPLE,
5298 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005299 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005300
Andy Hung333ab962019-05-28 20:23:35 -07005301 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005302 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005303 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005304 AudioMixer::TIMESTRETCH,
5305 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005306 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005307
Andy Hung69aed5f2014-02-25 17:24:40 -08005308 /*
5309 * Select the appropriate output buffer for the track.
5310 *
Andy Hung98ef9782014-03-04 14:46:50 -08005311 * Tracks with effects go into their own effects chain buffer
5312 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005313 *
5314 * Other tracks can use mMixerBuffer for higher precision
5315 * channel accumulation. If this buffer is enabled
5316 * (mMixerBufferEnabled true), then selected tracks will accumulate
5317 * into it.
5318 *
5319 */
5320 if (mMixerBufferEnabled
5321 && (track->mainBuffer() == mSinkBuffer
5322 || track->mainBuffer() == mMixerBuffer)) {
5323 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005324 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005325 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005326 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005327 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005328 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005329 AudioMixer::TRACK,
5330 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5331 // TODO: override track->mainBuffer()?
5332 mMixerBufferValid = true;
5333 } else {
5334 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005335 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005336 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005337 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005338 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005339 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005340 AudioMixer::TRACK,
5341 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5342 }
Eric Laurent81784c32012-11-19 14:55:58 -08005343 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005344 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005345 AudioMixer::TRACK,
5346 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005347 mAudioMixer->setParameter(
5348 trackId,
5349 AudioMixer::TRACK,
5350 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005351 mAudioMixer->setParameter(
5352 trackId,
5353 AudioMixer::TRACK,
5354 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005355
5356 // reset retry count
5357 track->mRetryCount = kMaxTrackRetries;
5358
5359 // If one track is ready, set the mixer ready if:
5360 // - the mixer was not ready during previous round OR
5361 // - no other track is not ready
5362 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5363 mixerStatus != MIXER_TRACKS_ENABLED) {
5364 mixerStatus = MIXER_TRACKS_READY;
5365 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005366
5367 // Enable the next few lines to instrument a test for underrun log handling.
5368 // TODO: Remove when we have a better way of testing the underrun log.
5369#if 0
5370 static int i;
5371 if ((++i & 0xf) == 0) {
5372 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5373 }
5374#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005375 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005376 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005377 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005378 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5379 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005380 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005381 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005382 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005383
Eric Laurent81784c32012-11-19 14:55:58 -08005384 // clear effect chain input buffer if an active track underruns to avoid sending
5385 // previous audio buffer again to effects
5386 chain = getEffectChain_l(track->sessionId());
5387 if (chain != 0) {
5388 chain->clearInputBuffer();
5389 }
5390
Andy Hungc0691382018-09-12 18:01:57 -07005391 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005392 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5393 track->isStopped() || track->isPaused()) {
5394 // We have consumed all the buffers of this track.
5395 // Remove it from the list of active tracks.
5396 // TODO: use actual buffer filling status instead of latency when available from
5397 // audio HAL
5398 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005399 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005400 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5401 if (track->isStopped()) {
5402 track->reset();
5403 }
5404 tracksToRemove->add(track);
5405 }
5406 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005407 // No buffers for this track. Give it a few chances to
5408 // fill a buffer, then remove it from active list.
5409 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005410 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5411 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005412 tracksToRemove->add(track);
5413 // indicate to client process that the track was disabled because of underrun;
5414 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005415 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005416 // If one track is not ready, mark the mixer also not ready if:
5417 // - the mixer was ready during previous round OR
5418 // - no other track is ready
5419 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5420 mixerStatus != MIXER_TRACKS_READY) {
5421 mixerStatus = MIXER_TRACKS_ENABLED;
5422 }
5423 }
Andy Hungc0691382018-09-12 18:01:57 -07005424 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005425 }
5426
5427 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005428
5429 }
5430
jiabin245cdd92018-12-07 17:55:15 -08005431 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5432 // When there is no fast track playing haptic and FastMixer exists,
5433 // enabling the first FastTrack, which provides mixed data from normal
5434 // tracks, to play haptic data.
5435 FastTrack *fastTrack = &state->mFastTracks[0];
5436 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5437 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5438 didModify = true;
5439 }
5440 }
5441
Eric Laurent81784c32012-11-19 14:55:58 -08005442 // Push the new FastMixer state if necessary
5443 bool pauseAudioWatchdog = false;
5444 if (didModify) {
5445 state->mFastTracksGen++;
5446 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5447 if (kUseFastMixer == FastMixer_Dynamic &&
5448 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5449 state->mCommand = FastMixerState::COLD_IDLE;
5450 state->mColdFutexAddr = &mFastMixerFutex;
5451 state->mColdGen++;
5452 mFastMixerFutex = 0;
5453 if (kUseFastMixer == FastMixer_Dynamic) {
5454 mNormalSink = mOutputSink;
5455 }
5456 // If we go into cold idle, need to wait for acknowledgement
5457 // so that fast mixer stops doing I/O.
5458 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5459 pauseAudioWatchdog = true;
5460 }
Eric Laurent81784c32012-11-19 14:55:58 -08005461 }
5462 if (sq != NULL) {
5463 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005464 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5465 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5466 // when bringing the output sink into standby.)
5467 //
5468 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5469 //
5470 // This occurs with BT suspend when we idle the FastMixer with
5471 // active tracks, which may be added or removed.
5472 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005473 }
5474#ifdef AUDIO_WATCHDOG
5475 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5476 mAudioWatchdog->pause();
5477 }
5478#endif
5479
5480 // Now perform the deferred reset on fast tracks that have stopped
5481 while (resetMask != 0) {
5482 size_t i = __builtin_ctz(resetMask);
5483 ALOG_ASSERT(i < count);
5484 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005485 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005486 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5487 track->reset();
5488 }
5489
Andy Hung80d03d22018-04-10 10:32:11 -07005490 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5491 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5492 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5493 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5494 // See also the implementation of destroyTrack_l().
5495 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005496 const int trackId = track->id();
5497 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5498 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005499 }
5500 }
5501
Eric Laurent81784c32012-11-19 14:55:58 -08005502 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005503 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005504
Eric Laurent97d547d2014-09-02 14:45:53 -07005505 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5506 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005507 }
5508
5509 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005510 // as long as there are effects we should clear the effects buffer, to avoid
5511 // passing a non-clean buffer to the effect chain
5512 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005513 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005514 // sink or mix buffer must be cleared if all tracks are connected to an
5515 // effect chain as in this case the mixer will not write to the sink or mix buffer
5516 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005517 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5518 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005519 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005520 if (mMixerBufferValid) {
5521 memset(mMixerBuffer, 0, mMixerBufferSize);
5522 // TODO: In testing, mSinkBuffer below need not be cleared because
5523 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5524 // after mixing.
5525 //
5526 // To enforce this guarantee:
5527 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5528 // (mixedTracks == 0 && fastTracks > 0))
5529 // must imply MIXER_TRACKS_READY.
5530 // Later, we may clear buffers regardless, and skip much of this logic.
5531 }
Andy Hung98ef9782014-03-04 14:46:50 -08005532 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005533 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005534 }
5535
5536 // if any fast tracks, then status is ready
5537 mMixerStatusIgnoringFastTracks = mixerStatus;
5538 if (fastTracks > 0) {
5539 mixerStatus = MIXER_TRACKS_READY;
5540 }
5541 return mixerStatus;
5542}
5543
Eric Laurentad7dd962016-09-22 12:38:37 -07005544// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005545uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005546{
5547 uint32_t trackCount = 0;
5548 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005549 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005550 trackCount++;
5551 }
5552 }
5553 return trackCount;
5554}
5555
Andy Hung1bc088a2018-02-09 15:57:31 -08005556// isTrackAllowed_l() must be called with ThreadBase::mLock held
5557bool AudioFlinger::MixerThread::isTrackAllowed_l(
5558 audio_channel_mask_t channelMask, audio_format_t format,
5559 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005560{
Andy Hung1bc088a2018-02-09 15:57:31 -08005561 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5562 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005563 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005564 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005565 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005566 ALOGW("%s: invalid format: %#x", __func__, format);
5567 return false;
5568 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005569 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005570 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5571 return false;
5572 }
5573 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005574}
5575
Eric Laurent10351942014-05-08 18:49:52 -07005576// checkForNewParameter_l() must be called with ThreadBase::mLock held
5577bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5578 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005579{
Eric Laurent81784c32012-11-19 14:55:58 -08005580 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005581 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005582
Eric Laurent10351942014-05-08 18:49:52 -07005583 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005584
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005585 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005586
Eric Laurent10351942014-05-08 18:49:52 -07005587 AudioParameter param = AudioParameter(keyValuePair);
5588 int value;
5589 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5590 reconfig = true;
5591 }
5592 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005593 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005594 status = BAD_VALUE;
5595 } else {
5596 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005597 reconfig = true;
5598 }
Eric Laurent10351942014-05-08 18:49:52 -07005599 }
5600 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005601 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005602 status = BAD_VALUE;
5603 } else {
5604 // no need to save value, since it's constant
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::keyFrameCount), value) == NO_ERROR) {
5609 // do not accept frame count changes if tracks are open as the track buffer
5610 // size depends on frame count and correct behavior would not be guaranteed
5611 // if frame count is changed after track creation
5612 if (!mTracks.isEmpty()) {
5613 status = INVALID_OPERATION;
5614 } else {
5615 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005616 }
Eric Laurent10351942014-05-08 18:49:52 -07005617 }
5618 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005619 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005620 }
Eric Laurent81784c32012-11-19 14:55:58 -08005621
Eric Laurent10351942014-05-08 18:49:52 -07005622 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005623 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005624 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005625 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005626 if (!mStandby) {
5627 mThreadMetrics.logEndInterval();
5628 mStandby = true;
5629 }
Eric Laurent10351942014-05-08 18:49:52 -07005630 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005631 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005632 }
Eric Laurent10351942014-05-08 18:49:52 -07005633 if (status == NO_ERROR && reconfig) {
5634 readOutputParameters_l();
5635 delete mAudioMixer;
5636 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005637 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005638 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005639 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005640 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005641 track->mChannelMask,
5642 track->mFormat,
5643 track->mSessionId);
5644 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005645 "%s(): AudioMixer cannot create track(%d)"
5646 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005647 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005648 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005649 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005650 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005651 }
Eric Laurent81784c32012-11-19 14:55:58 -08005652 }
5653
Eric Laurent42537be2016-01-08 17:16:42 -08005654 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005655}
5656
5657
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005658void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005659{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005660 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005661 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005662 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005663 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005664 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5665 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5666 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005667 if (hasFastMixer()) {
5668 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5669
5670 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5671 // while we are dumping it. It may be inconsistent, but it won't mutate!
5672 // This is a large object so we place it on the heap.
5673 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005674 const std::unique_ptr<FastMixerDumpState> copy =
5675 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005676 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005677
5678#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005679 // Similar for state queue
5680 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5681 observerCopy.dump(fd);
5682 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5683 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005684#endif
5685
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005686#ifdef AUDIO_WATCHDOG
5687 if (mAudioWatchdog != 0) {
5688 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5689 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5690 wdCopy.dump(fd);
5691 }
5692#endif
5693
5694 } else {
5695 dprintf(fd, " No FastMixer\n");
5696 }
Eric Laurent81784c32012-11-19 14:55:58 -08005697}
5698
5699uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5700{
5701 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5702}
5703
5704uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5705{
5706 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5707}
5708
5709void AudioFlinger::MixerThread::cacheParameters_l()
5710{
5711 PlaybackThread::cacheParameters_l();
5712
5713 // FIXME: Relaxed timing because of a certain device that can't meet latency
5714 // Should be reduced to 2x after the vendor fixes the driver issue
5715 // increase threshold again due to low power audio mode. The way this warning
5716 // threshold is calculated and its usefulness should be reconsidered anyway.
5717 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5718}
5719
5720// ----------------------------------------------------------------------------
5721
5722AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005723 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5724 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005725{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005726 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005727}
5728
Eric Laurent81784c32012-11-19 14:55:58 -08005729AudioFlinger::DirectOutputThread::~DirectOutputThread()
5730{
5731}
5732
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005733void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005734{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005735 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005736 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5737 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5738}
5739
5740void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5741{
5742 Mutex::Autolock _l(mLock);
5743 if (mMasterBalance != balance) {
5744 mMasterBalance.store(balance);
5745 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5746 broadcast_l();
5747 }
5748}
5749
Eric Laurent5850c4c2016-11-10 13:04:31 -08005750void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005751{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005752 float left, right;
5753
Andy Hung333ab962019-05-28 20:23:35 -07005754 // Ensure volumeshaper state always advances even when muted.
5755 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5756 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5757 proxy->framesReleased());
5758 mVolumeShaperActive = shaperActive;
5759
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005760 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005761 left = right = 0;
5762 } else {
5763 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005764 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005765
Glenn Kastenc56f3422014-03-21 17:53:17 -07005766 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5767 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5768 if (left > GAIN_FLOAT_UNITY) {
5769 left = GAIN_FLOAT_UNITY;
5770 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005771 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005772 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5773 if (right > GAIN_FLOAT_UNITY) {
5774 right = GAIN_FLOAT_UNITY;
5775 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005776 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005777 }
5778
5779 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005780 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005781 if (left != mLeftVolFloat || right != mRightVolFloat) {
5782 mLeftVolFloat = left;
5783 mRightVolFloat = right;
5784
Eric Laurentbfb1b832013-01-07 09:53:42 -08005785 // Delegate volume control to effect in track effect chain if needed
5786 // only one effect chain can be present on DirectOutputThread, so if
5787 // there is one, the track is connected to it
5788 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005789 // if effect chain exists, volume is handled by it.
5790 // Convert volumes from float to 8.24
5791 uint32_t vl = (uint32_t)(left * (1 << 24));
5792 uint32_t vr = (uint32_t)(right * (1 << 24));
5793 // Direct/Offload effect chains set output volume in setVolume_l().
5794 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5795 } else {
5796 // otherwise we directly set the volume.
5797 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005798 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005799 }
5800 }
5801}
5802
Phil Burk43b4dcc2015-06-09 16:53:44 -07005803void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5804{
5805 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005806 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005807
Eric Laurent0f0631e2015-07-06 18:01:25 -07005808 if (previousTrack != 0 && latestTrack != 0) {
5809 if (mType == DIRECT) {
5810 if (previousTrack.get() != latestTrack.get()) {
5811 mFlushPending = true;
5812 }
5813 } else /* mType == OFFLOAD */ {
5814 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5815 mFlushPending = true;
5816 }
5817 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005818 } else if (previousTrack == 0) {
5819 // there could be an old track added back during track transition for direct
5820 // output, so always issues flush to flush data of the previous track if it
5821 // was already destroyed with HAL paused, then flush can resume the playback
5822 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005823 }
5824 PlaybackThread::onAddNewTrack_l();
5825}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005826
Eric Laurent81784c32012-11-19 14:55:58 -08005827AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5828 Vector< sp<Track> > *tracksToRemove
5829)
5830{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005831 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005832 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005833 bool doHwPause = false;
5834 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005835
5836 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005837 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005838 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005839 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005840 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005841 continue;
5842 }
5843
Eric Laurent5850c4c2016-11-10 13:04:31 -08005844 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005845#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005846 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005847#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005848 // Only consider last track started for volume and mixer state control.
5849 // In theory an older track could underrun and restart after the new one starts
5850 // but as we only care about the transition phase between two tracks on a
5851 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005852 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005853 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005854
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005855 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005856 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005857 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005858 doHwPause = true;
5859 mHwPaused = true;
5860 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005861 } else if (track->isFlushPending()) {
5862 track->flushAck();
5863 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005864 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005865 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005866 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005867 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005868 if (last) {
5869 mLeftVolFloat = mRightVolFloat = -1.0;
5870 if (mHwPaused) {
5871 doHwResume = true;
5872 mHwPaused = false;
5873 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005874 }
5875 }
5876
Eric Laurent81784c32012-11-19 14:55:58 -08005877 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005878 // for all its buffers to be filled before processing it.
5879 // Allow draining the buffer in case the client
5880 // app does not call stop() and relies on underrun to stop:
5881 // hence the test on (track->mRetryCount > 1).
5882 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005883 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005884 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005885 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005886 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005887 minFrames = mNormalFrameCount;
5888 } else {
5889 minFrames = 1;
5890 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005891
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005892 const size_t framesReady = track->framesReady();
5893 const int trackId = track->id();
5894 if (ATRACE_ENABLED()) {
5895 std::string traceName("nRdy");
5896 traceName += std::to_string(trackId);
5897 ATRACE_INT(traceName.c_str(), framesReady);
5898 }
5899 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005900 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005901 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005902 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005903
5904 if (track->mFillingUpStatus == Track::FS_FILLED) {
5905 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005906 if (last) {
5907 // make sure processVolume_l() will apply new volume even if 0
5908 mLeftVolFloat = mRightVolFloat = -1.0;
5909 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005910 if (!mHwSupportsPause) {
5911 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005912 }
5913 }
5914
5915 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005916 processVolume_l(track, last);
5917 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005918 sp<Track> previousTrack = mPreviousTrack.promote();
5919 if (previousTrack != 0) {
5920 if (track != previousTrack.get()) {
5921 // Flush any data still being written from last track
5922 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005923 // Invalidate previous track to force a seek when resuming.
5924 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005925 }
5926 }
5927 mPreviousTrack = track;
5928
Eric Laurentd595b7c2013-04-03 17:27:56 -07005929 // reset retry count
5930 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005931 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005932 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005933 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005934 doHwResume = true;
5935 mHwPaused = false;
5936 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005937 }
Eric Laurent81784c32012-11-19 14:55:58 -08005938 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005939 // clear effect chain input buffer if the last active track started underruns
5940 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005941 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005942 mEffectChains[0]->clearInputBuffer();
5943 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005944 if (track->isStopping_1()) {
5945 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005946 if (last && mHwPaused) {
5947 doHwResume = true;
5948 mHwPaused = false;
5949 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005950 }
5951 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5952 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005953 // We have consumed all the buffers of this track.
5954 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005955 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005956 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005957 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5958 } else {
5959 audioHALFrames = 0;
5960 }
5961
Andy Hung818e7a32016-02-16 18:08:07 -08005962 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005963 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005964 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08005965 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005966 if (track->isStopping_2()) {
5967 track->mState = TrackBase::STOPPED;
5968 }
Eric Laurent81784c32012-11-19 14:55:58 -08005969 if (track->isStopped()) {
5970 track->reset();
5971 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005972 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005973 }
5974 } else {
5975 // No buffers for this track. Give it a few chances to
5976 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005977 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005978 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005979 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005980 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005981 // indicate to client process that the track was disabled because of underrun;
5982 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005983 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005984 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005985 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5986 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005987 framesReady, minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005988 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005989 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005990 doHwPause = true;
5991 mHwPaused = true;
5992 }
Eric Laurent81784c32012-11-19 14:55:58 -08005993 }
5994 }
5995 }
5996 }
5997
Eric Laurentd1f69b02014-12-15 14:33:13 -08005998 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005999 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006000 for (size_t i = 0; i < mTracks.size(); i++) {
6001 if (mTracks[i]->isFlushPending()) {
6002 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006003 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006004 }
6005 }
6006 }
6007
6008 // make sure the pause/flush/resume sequence is executed in the right order.
6009 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6010 // before flush and then resume HW. This can happen in case of pause/flush/resume
6011 // if resume is received before pause is executed.
6012 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006013 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006014 status_t result = mOutput->stream->pause();
6015 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006016 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006017 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006018 flushHw_l();
6019 }
6020 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006021 status_t result = mOutput->stream->resume();
6022 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006023 }
Eric Laurent81784c32012-11-19 14:55:58 -08006024 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006025 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006026
6027 return mixerStatus;
6028}
6029
6030void AudioFlinger::DirectOutputThread::threadLoop_mix()
6031{
Eric Laurent81784c32012-11-19 14:55:58 -08006032 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006033 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006034 // output audio to hardware
6035 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006036 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006037 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006038 status_t status = mActiveTrack->getNextBuffer(&buffer);
6039 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006040 // no need to pad with 0 for compressed audio
6041 if (audio_has_proportional_frames(mFormat)) {
6042 memset(curBuf, 0, frameCount * mFrameSize);
6043 }
Eric Laurent81784c32012-11-19 14:55:58 -08006044 break;
6045 }
6046 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6047 frameCount -= buffer.frameCount;
6048 curBuf += buffer.frameCount * mFrameSize;
6049 mActiveTrack->releaseBuffer(&buffer);
6050 }
Andy Hung2098f272014-02-27 14:00:06 -08006051 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006052 mSleepTimeUs = 0;
6053 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006054 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006055}
6056
6057void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6058{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006059 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006060 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006061 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006062 return;
6063 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006064 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006065 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07006066 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006067 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006068 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006069 }
Phil Burkfdb3c072016-02-09 10:47:02 -08006070 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08006071 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006072 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006073 }
6074}
6075
Eric Laurentd1f69b02014-12-15 14:33:13 -08006076void AudioFlinger::DirectOutputThread::threadLoop_exit()
6077{
6078 {
6079 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006080 for (size_t i = 0; i < mTracks.size(); i++) {
6081 if (mTracks[i]->isFlushPending()) {
6082 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006083 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006084 }
6085 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006086 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006087 flushHw_l();
6088 }
6089 }
6090 PlaybackThread::threadLoop_exit();
6091}
6092
6093// must be called with thread mutex locked
6094bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6095{
6096 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006097 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006098
6099 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6100 // after a timeout and we will enter standby then.
6101 if (mTracks.size() > 0) {
6102 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006103 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6104 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006105 }
6106
Eric Laurent5cff4032015-05-26 13:49:58 -07006107 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006108}
6109
Eric Laurent10351942014-05-08 18:49:52 -07006110// checkForNewParameter_l() must be called with ThreadBase::mLock held
6111bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6112 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006113{
6114 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08006115 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006116
Eric Laurent10351942014-05-08 18:49:52 -07006117 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006118
Eric Laurent10351942014-05-08 18:49:52 -07006119 AudioParameter param = AudioParameter(keyValuePair);
6120 int value;
6121 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006122 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006123 }
Eric Laurent10351942014-05-08 18:49:52 -07006124 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6125 // do not accept frame count changes if tracks are open as the track buffer
6126 // size depends on frame count and correct behavior would not be garantied
6127 // if frame count is changed after track creation
6128 if (!mTracks.isEmpty()) {
6129 status = INVALID_OPERATION;
6130 } else {
6131 reconfig = true;
6132 }
6133 }
6134 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006135 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006136 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006137 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006138 if (!mStandby) {
6139 mThreadMetrics.logEndInterval();
6140 mStandby = true;
6141 }
Eric Laurent10351942014-05-08 18:49:52 -07006142 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006143 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006144 }
6145 if (status == NO_ERROR && reconfig) {
6146 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006147 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006148 }
6149 }
6150
Eric Laurent42537be2016-01-08 17:16:42 -08006151 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08006152}
6153
6154uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6155{
6156 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006157 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006158 time = PlaybackThread::activeSleepTimeUs();
6159 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006160 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006161 }
6162 return time;
6163}
6164
6165uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6166{
6167 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006168 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006169 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6170 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006171 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006172 }
6173 return time;
6174}
6175
6176uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6177{
6178 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006179 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006180 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6181 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006182 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006183 }
6184 return time;
6185}
6186
6187void AudioFlinger::DirectOutputThread::cacheParameters_l()
6188{
6189 PlaybackThread::cacheParameters_l();
6190
6191 // use shorter standby delay as on normal output to release
6192 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006193 // no delay on outputs with HW A/V sync
6194 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006195 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006196 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006197 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006198 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006199 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006200 }
Eric Laurent81784c32012-11-19 14:55:58 -08006201}
6202
Eric Laurente659ef42014-09-29 13:06:46 -07006203void AudioFlinger::DirectOutputThread::flushHw_l()
6204{
Phil Burk062e67a2015-02-11 13:40:50 -08006205 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006206 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006207 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07006208 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Sampath Shetty999f0e82020-01-15 10:19:06 +11006209 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006210}
6211
Andy Hung10cbff12017-02-21 17:30:14 -08006212int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6213 // If a VolumeShaper is active, we must wake up periodically to update volume.
6214 const int64_t NS_PER_MS = 1000000;
6215 return mVolumeShaperActive ?
6216 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6217}
6218
Eric Laurent81784c32012-11-19 14:55:58 -08006219// ----------------------------------------------------------------------------
6220
Eric Laurentbfb1b832013-01-07 09:53:42 -08006221AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006222 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006223 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006224 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006225 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006226 mDrainSequence(0),
6227 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006228{
6229}
6230
6231AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6232{
6233}
6234
6235void AudioFlinger::AsyncCallbackThread::onFirstRef()
6236{
6237 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6238}
6239
6240bool AudioFlinger::AsyncCallbackThread::threadLoop()
6241{
6242 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006243 uint32_t writeAckSequence;
6244 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006245 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006246
6247 {
6248 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006249 while (!((mWriteAckSequence & 1) ||
6250 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006251 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006252 exitPending())) {
6253 mWaitWorkCV.wait(mLock);
6254 }
6255
Eric Laurentbfb1b832013-01-07 09:53:42 -08006256 if (exitPending()) {
6257 break;
6258 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006259 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6260 mWriteAckSequence, mDrainSequence);
6261 writeAckSequence = mWriteAckSequence;
6262 mWriteAckSequence &= ~1;
6263 drainSequence = mDrainSequence;
6264 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006265 asyncError = mAsyncError;
6266 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006267 }
6268 {
Eric Laurent4de95592013-09-26 15:28:21 -07006269 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6270 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006271 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006272 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006273 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006274 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006275 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006276 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006277 if (asyncError) {
6278 playbackThread->onAsyncError();
6279 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006280 }
6281 }
6282 }
6283 return false;
6284}
6285
6286void AudioFlinger::AsyncCallbackThread::exit()
6287{
6288 ALOGV("AsyncCallbackThread::exit");
6289 Mutex::Autolock _l(mLock);
6290 requestExit();
6291 mWaitWorkCV.broadcast();
6292}
6293
Eric Laurent3b4529e2013-09-05 18:09:19 -07006294void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006295{
6296 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006297 // bit 0 is cleared
6298 mWriteAckSequence = sequence << 1;
6299}
6300
6301void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6302{
6303 Mutex::Autolock _l(mLock);
6304 // ignore unexpected callbacks
6305 if (mWriteAckSequence & 2) {
6306 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006307 mWaitWorkCV.signal();
6308 }
6309}
6310
Eric Laurent3b4529e2013-09-05 18:09:19 -07006311void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006312{
6313 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006314 // bit 0 is cleared
6315 mDrainSequence = sequence << 1;
6316}
6317
6318void AudioFlinger::AsyncCallbackThread::resetDraining()
6319{
6320 Mutex::Autolock _l(mLock);
6321 // ignore unexpected callbacks
6322 if (mDrainSequence & 2) {
6323 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006324 mWaitWorkCV.signal();
6325 }
6326}
6327
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006328void AudioFlinger::AsyncCallbackThread::setAsyncError()
6329{
6330 Mutex::Autolock _l(mLock);
6331 mAsyncError = true;
6332 mWaitWorkCV.signal();
6333}
6334
Eric Laurentbfb1b832013-01-07 09:53:42 -08006335
6336// ----------------------------------------------------------------------------
6337AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006338 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6339 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006340 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6341 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006342{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006343 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006344 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006345 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006346}
6347
Eric Laurentbfb1b832013-01-07 09:53:42 -08006348void AudioFlinger::OffloadThread::threadLoop_exit()
6349{
6350 if (mFlushPending || mHwPaused) {
6351 // If a flush is pending or track was paused, just discard buffered data
6352 flushHw_l();
6353 } else {
6354 mMixerStatus = MIXER_DRAIN_ALL;
6355 threadLoop_drain();
6356 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006357 if (mUseAsyncWrite) {
6358 ALOG_ASSERT(mCallbackThread != 0);
6359 mCallbackThread->exit();
6360 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006361 PlaybackThread::threadLoop_exit();
6362}
6363
6364AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6365 Vector< sp<Track> > *tracksToRemove
6366)
6367{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006368 size_t count = mActiveTracks.size();
6369
6370 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006371 bool doHwPause = false;
6372 bool doHwResume = false;
6373
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006374 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006375
Eric Laurentbfb1b832013-01-07 09:53:42 -08006376 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006377 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006378 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006379#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006380 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006381#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006382 // Only consider last track started for volume and mixer state control.
6383 // In theory an older track could underrun and restart after the new one starts
6384 // but as we only care about the transition phase between two tracks on a
6385 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006386 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006387 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006388
Haynes Mathew George7844f672014-01-15 12:32:55 -08006389 if (track->isInvalid()) {
6390 ALOGW("An invalidated track shouldn't be in active list");
6391 tracksToRemove->add(track);
6392 continue;
6393 }
6394
6395 if (track->mState == TrackBase::IDLE) {
6396 ALOGW("An idle track shouldn't be in active list");
6397 continue;
6398 }
6399
Eric Laurentbfb1b832013-01-07 09:53:42 -08006400 if (track->isPausing()) {
6401 track->setPaused();
6402 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006403 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006404 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006405 mHwPaused = true;
6406 }
6407 // If we were part way through writing the mixbuffer to
6408 // the HAL we must save this until we resume
6409 // BUG - this will be wrong if a different track is made active,
6410 // in that case we want to discard the pending data in the
6411 // mixbuffer and tell the client to present it again when the
6412 // track is resumed
6413 mPausedWriteLength = mCurrentWriteLength;
6414 mPausedBytesRemaining = mBytesRemaining;
6415 mBytesRemaining = 0; // stop writing
6416 }
6417 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006418 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006419 if (track->isStopping_1()) {
6420 track->mRetryCount = kMaxTrackStopRetriesOffload;
6421 } else {
6422 track->mRetryCount = kMaxTrackRetriesOffload;
6423 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006424 track->flushAck();
6425 if (last) {
6426 mFlushPending = true;
6427 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006428 } else if (track->isResumePending()){
6429 track->resumeAck();
6430 if (last) {
6431 if (mPausedBytesRemaining) {
6432 // Need to continue write that was interrupted
6433 mCurrentWriteLength = mPausedWriteLength;
6434 mBytesRemaining = mPausedBytesRemaining;
6435 mPausedBytesRemaining = 0;
6436 }
6437 if (mHwPaused) {
6438 doHwResume = true;
6439 mHwPaused = false;
6440 // threadLoop_mix() will handle the case that we need to
6441 // resume an interrupted write
6442 }
6443 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006444 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006445
Eric Laurent3df841a2016-07-15 15:15:40 -07006446 mLeftVolFloat = mRightVolFloat = -1.0;
6447
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006448 // Do not handle new data in this iteration even if track->framesReady()
6449 mixerStatus = MIXER_TRACKS_ENABLED;
6450 }
6451 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006452 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006453 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006454 if (track->mFillingUpStatus == Track::FS_FILLED) {
6455 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006456 if (last) {
6457 // make sure processVolume_l() will apply new volume even if 0
6458 mLeftVolFloat = mRightVolFloat = -1.0;
6459 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006460 }
6461
6462 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006463 sp<Track> previousTrack = mPreviousTrack.promote();
6464 if (previousTrack != 0) {
6465 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006466 // Flush any data still being written from last track
6467 mBytesRemaining = 0;
6468 if (mPausedBytesRemaining) {
6469 // Last track was paused so we also need to flush saved
6470 // mixbuffer state and invalidate track so that it will
6471 // re-submit that unwritten data when it is next resumed
6472 mPausedBytesRemaining = 0;
6473 // Invalidate is a bit drastic - would be more efficient
6474 // to have a flag to tell client that some of the
6475 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006476 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006477 }
6478 // flush data already sent to the DSP if changing audio session as audio
6479 // comes from a different source. Also invalidate previous track to force a
6480 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006481 if (previousTrack->sessionId() != track->sessionId()) {
6482 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006483 }
6484 }
6485 }
6486 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006487 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006488 if (track->isStopping_1()) {
6489 track->mRetryCount = kMaxTrackStopRetriesOffload;
6490 } else {
6491 track->mRetryCount = kMaxTrackRetriesOffload;
6492 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006493 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006494 mixerStatus = MIXER_TRACKS_READY;
6495 }
6496 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006497 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006498 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006499 if (--(track->mRetryCount) <= 0) {
6500 // Hardware buffer can hold a large amount of audio so we must
6501 // wait for all current track's data to drain before we say
6502 // that the track is stopped.
6503 if (mBytesRemaining == 0) {
6504 // Only start draining when all data in mixbuffer
6505 // has been written
6506 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6507 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6508 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6509 if (last && !mStandby) {
6510 // do not modify drain sequence if we are already draining. This happens
6511 // when resuming from pause after drain.
6512 if ((mDrainSequence & 1) == 0) {
6513 mSleepTimeUs = 0;
6514 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6515 mixerStatus = MIXER_DRAIN_TRACK;
6516 mDrainSequence += 2;
6517 }
6518 if (mHwPaused) {
6519 // It is possible to move from PAUSED to STOPPING_1 without
6520 // a resume so we must ensure hardware is running
6521 doHwResume = true;
6522 mHwPaused = false;
6523 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006524 }
6525 }
Eric Laurente93cc032016-05-05 10:15:10 -07006526 } else if (last) {
6527 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6528 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006529 }
6530 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006531 // Drain has completed or we are in standby, signal presentation complete
6532 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006533 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006534 uint32_t latency = 0;
6535 status_t result = mOutput->stream->getLatency(&latency);
6536 ALOGE_IF(result != OK,
6537 "Error when retrieving output stream latency: %d", result);
6538 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006539 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006540 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006541 track->presentationComplete(framesWritten, audioHALFrames);
6542 track->reset();
6543 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006544 // DIRECT and OFFLOADED stop resets frame counts.
6545 if (!mUseAsyncWrite) {
6546 // If we don't get explicit drain notification we must
6547 // register discontinuity regardless of whether this is
6548 // the previous (!last) or the upcoming (last) track
6549 // to avoid skipping the discontinuity.
6550 mTimestampVerifier.discontinuity();
6551 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006552 }
6553 } else {
6554 // No buffers for this track. Give it a few chances to
6555 // fill a buffer, then remove it from active list.
6556 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006557 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006558 uint64_t position = 0;
6559 struct timespec unused;
6560 // The running check restarts the retry counter at least once.
6561 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6562 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6563 running = true;
6564 mOffloadUnderrunPosition = position;
6565 }
6566 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006567 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6568 (long long)position, (long long)mOffloadUnderrunPosition);
6569 }
6570 if (running) { // still running, give us more time.
6571 track->mRetryCount = kMaxTrackRetriesOffload;
6572 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006573 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6574 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006575 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006576 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006577 // it will then automatically call start() when data is available
6578 track->disable();
6579 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006580 } else if (last){
6581 mixerStatus = MIXER_TRACKS_ENABLED;
6582 }
6583 }
6584 }
6585 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006586 if (track->isReady()) { // check ready to prevent premature start.
6587 processVolume_l(track, last);
6588 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006589 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006590
Eric Laurentea0fade2013-10-04 16:23:48 -07006591 // make sure the pause/flush/resume sequence is executed in the right order.
6592 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6593 // before flush and then resume HW. This can happen in case of pause/flush/resume
6594 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006595 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006596 status_t result = mOutput->stream->pause();
6597 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006598 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006599 if (mFlushPending) {
6600 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006601 }
Eric Laurentfd477972013-10-25 18:10:40 -07006602 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006603 status_t result = mOutput->stream->resume();
6604 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006605 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006606
Eric Laurentbfb1b832013-01-07 09:53:42 -08006607 // remove all the tracks that need to be...
6608 removeTracks_l(*tracksToRemove);
6609
6610 return mixerStatus;
6611}
6612
Eric Laurentbfb1b832013-01-07 09:53:42 -08006613// must be called with thread mutex locked
6614bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6615{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006616 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6617 mWriteAckSequence, mDrainSequence);
6618 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006619 return true;
6620 }
6621 return false;
6622}
6623
Eric Laurentbfb1b832013-01-07 09:53:42 -08006624bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6625{
6626 Mutex::Autolock _l(mLock);
6627 return waitingAsyncCallback_l();
6628}
6629
6630void AudioFlinger::OffloadThread::flushHw_l()
6631{
Eric Laurente659ef42014-09-29 13:06:46 -07006632 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006633 // Flush anything still waiting in the mixbuffer
6634 mCurrentWriteLength = 0;
6635 mBytesRemaining = 0;
6636 mPausedWriteLength = 0;
6637 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006638 // reset bytes written count to reflect that DSP buffers are empty after flush.
6639 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006640 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006641
Eric Laurentbfb1b832013-01-07 09:53:42 -08006642 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006643 // discard any pending drain or write ack by incrementing sequence
6644 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6645 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006646 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006647 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6648 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006649 }
6650}
6651
Haynes Mathew George05317d22016-05-03 16:34:26 -07006652void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6653{
6654 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006655 if (PlaybackThread::invalidateTracks_l(streamType)) {
6656 mFlushPending = true;
6657 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006658}
6659
Eric Laurentbfb1b832013-01-07 09:53:42 -08006660// ----------------------------------------------------------------------------
6661
Eric Laurent81784c32012-11-19 14:55:58 -08006662AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006663 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006664 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006665 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006666 mWaitTimeMs(UINT_MAX)
6667{
6668 addOutputTrack(mainThread);
6669}
6670
6671AudioFlinger::DuplicatingThread::~DuplicatingThread()
6672{
6673 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6674 mOutputTracks[i]->destroy();
6675 }
6676}
6677
6678void AudioFlinger::DuplicatingThread::threadLoop_mix()
6679{
6680 // mix buffers...
6681 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006682 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006683 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006684 if (mMixerBufferValid) {
6685 memset(mMixerBuffer, 0, mMixerBufferSize);
6686 } else {
6687 memset(mSinkBuffer, 0, mSinkBufferSize);
6688 }
Eric Laurent81784c32012-11-19 14:55:58 -08006689 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006690 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006691 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006692 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006693 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006694}
6695
6696void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6697{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006698 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006699 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006700 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006701 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006702 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006703 }
6704 } else if (mBytesWritten != 0) {
6705 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6706 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006707 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006708 } else {
6709 // flush remaining overflow buffers in output tracks
6710 writeFrames = 0;
6711 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006712 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006713 }
6714}
6715
Eric Laurentbfb1b832013-01-07 09:53:42 -08006716ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006717{
6718 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006719 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6720
6721 // Consider the first OutputTrack for timestamp and frame counting.
6722
6723 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6724 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6725 // we always claim success.
6726 if (i == 0) {
6727 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6728 ALOGD_IF(correction != 0 && writeFrames != 0,
6729 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6730 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6731 mFramesWritten -= correction;
6732 }
6733
6734 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006735 }
Andy Hungcf10d742020-04-28 15:38:24 -07006736 if (mStandby) {
6737 mThreadMetrics.logBeginInterval();
6738 mStandby = false;
6739 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006740 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006741}
6742
6743void AudioFlinger::DuplicatingThread::threadLoop_standby()
6744{
6745 // DuplicatingThread implements standby by stopping all tracks
6746 for (size_t i = 0; i < outputTracks.size(); i++) {
6747 outputTracks[i]->stop();
6748 }
6749}
6750
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006751void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006752{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006753 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006754
6755 std::stringstream ss;
6756 const size_t numTracks = mOutputTracks.size();
6757 ss << " " << numTracks << " OutputTracks";
6758 if (numTracks > 0) {
6759 ss << ":";
6760 for (const auto &track : mOutputTracks) {
6761 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006762 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006763 if (thread.get() != nullptr) {
6764 ss << thread.get() << ", " << thread->id();
6765 } else {
6766 ss << "null";
6767 }
6768 ss << ")";
6769 }
6770 }
6771 ss << "\n";
6772 std::string result = ss.str();
6773 write(fd, result.c_str(), result.size());
6774}
6775
Eric Laurent81784c32012-11-19 14:55:58 -08006776void AudioFlinger::DuplicatingThread::saveOutputTracks()
6777{
6778 outputTracks = mOutputTracks;
6779}
6780
6781void AudioFlinger::DuplicatingThread::clearOutputTracks()
6782{
6783 outputTracks.clear();
6784}
6785
6786void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6787{
6788 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006789 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6790 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6791 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6792 const size_t frameCount =
6793 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6794 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6795 // from different OutputTracks and their associated MixerThreads (e.g. one may
6796 // nearly empty and the other may be dropping data).
6797
6798 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006799 this,
6800 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006801 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006802 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006803 frameCount,
6804 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006805 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6806 if (status != NO_ERROR) {
6807 ALOGE("addOutputTrack() initCheck failed %d", status);
6808 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006809 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006810 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6811 mOutputTracks.add(outputTrack);
6812 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6813 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006814}
6815
6816void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6817{
6818 Mutex::Autolock _l(mLock);
6819 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6820 if (mOutputTracks[i]->thread() == thread) {
6821 mOutputTracks[i]->destroy();
6822 mOutputTracks.removeAt(i);
6823 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006824 if (thread->getOutput() == mOutput) {
6825 mOutput = NULL;
6826 }
Eric Laurent81784c32012-11-19 14:55:58 -08006827 return;
6828 }
6829 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006830 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006831}
6832
6833// caller must hold mLock
6834void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6835{
6836 mWaitTimeMs = UINT_MAX;
6837 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6838 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6839 if (strong != 0) {
6840 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6841 if (waitTimeMs < mWaitTimeMs) {
6842 mWaitTimeMs = waitTimeMs;
6843 }
6844 }
6845 }
6846}
6847
6848
6849bool AudioFlinger::DuplicatingThread::outputsReady(
6850 const SortedVector< sp<OutputTrack> > &outputTracks)
6851{
6852 for (size_t i = 0; i < outputTracks.size(); i++) {
6853 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6854 if (thread == 0) {
6855 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6856 outputTracks[i].get());
6857 return false;
6858 }
6859 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6860 // see note at standby() declaration
6861 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6862 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6863 thread.get());
6864 return false;
6865 }
6866 }
6867 return true;
6868}
6869
Kevin Rocard12381092018-04-11 09:19:59 -07006870void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6871 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006872{
Kevin Rocard12381092018-04-11 09:19:59 -07006873 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6874 outputTrack->setMetadatas(metadata.tracks);
6875 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006876}
6877
Eric Laurent81784c32012-11-19 14:55:58 -08006878uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6879{
6880 return (mWaitTimeMs * 1000) / 2;
6881}
6882
6883void AudioFlinger::DuplicatingThread::cacheParameters_l()
6884{
6885 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6886 updateWaitTime_l();
6887
6888 MixerThread::cacheParameters_l();
6889}
6890
Eric Laurent6acd1d42017-01-04 14:23:29 -08006891
Eric Laurent81784c32012-11-19 14:55:58 -08006892// ----------------------------------------------------------------------------
6893// Record
6894// ----------------------------------------------------------------------------
6895
6896AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6897 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006898 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006899 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006900 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07006901 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006902 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006903 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006904 mActiveTracks(&this->mLocalLog),
6905 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006906 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006907 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006908 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6909 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006910 // mFastCapture below
6911 , mFastCaptureFutex(0)
6912 // mInputSource
6913 // mPipeSink
6914 // mPipeSource
6915 , mPipeFramesP2(0)
6916 // mPipeMemory
6917 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006918 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006919 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006920{
Glenn Kastend7dca052015-03-05 16:05:54 -08006921 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6922 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006923
George Burgess IVa8f90c12020-05-14 11:27:19 -07006924 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07006925 mIsMsdDevice = strcmp(
6926 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6927 }
6928
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006929 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006930
Andy Hungc8fddf32018-08-08 18:32:37 -07006931 // TODO: We may also match on address as well as device type for
6932 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07006933 // TODO: This property should be ensure that only contains one single device type.
6934 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6935 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006936 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6937 : AUDIO_DEVICE_NONE));
6938
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006939 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006940 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006941 size_t numCounterOffers = 0;
6942 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006943#if !LOG_NDEBUG
6944 ssize_t index =
6945#else
6946 (void)
6947#endif
6948 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006949 ALOG_ASSERT(index == 0);
6950
6951 // initialize fast capture depending on configuration
6952 bool initFastCapture;
6953 switch (kUseFastCapture) {
6954 case FastCapture_Never:
6955 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006956 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006957 break;
6958 case FastCapture_Always:
6959 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006960 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006961 break;
6962 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006963 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006964 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6965 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6966 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006967 break;
6968 // case FastCapture_Dynamic:
6969 }
6970
6971 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006972 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006973 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006974 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6975 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006976 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006977 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006978 const sp<MemoryDealer> roHeap(readOnlyHeap());
6979 sp<IMemory> pipeMemory;
6980 if ((roHeap == 0) ||
6981 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07006982 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006983 ALOGE("not enough memory for pipe buffer size=%zu; "
6984 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6985 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6986 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006987 goto failed;
6988 }
6989 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6990 memset(pipeBuffer, 0, pipeSize);
6991 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6992 const NBAIO_Format offers[1] = {format};
6993 size_t numCounterOffers = 0;
6994 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6995 ALOG_ASSERT(index == 0);
6996 mPipeSink = pipe;
6997 PipeReader *pipeReader = new PipeReader(*pipe);
6998 numCounterOffers = 0;
6999 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7000 ALOG_ASSERT(index == 0);
7001 mPipeSource = pipeReader;
7002 mPipeFramesP2 = pipeFramesP2;
7003 mPipeMemory = pipeMemory;
7004
7005 // create fast capture
7006 mFastCapture = new FastCapture();
7007 FastCaptureStateQueue *sq = mFastCapture->sq();
7008#ifdef STATE_QUEUE_DUMP
7009 // FIXME
7010#endif
7011 FastCaptureState *state = sq->begin();
7012 state->mCblk = NULL;
7013 state->mInputSource = mInputSource.get();
7014 state->mInputSourceGen++;
7015 state->mPipeSink = pipe;
7016 state->mPipeSinkGen++;
7017 state->mFrameCount = mFrameCount;
7018 state->mCommand = FastCaptureState::COLD_IDLE;
7019 // already done in constructor initialization list
7020 //mFastCaptureFutex = 0;
7021 state->mColdFutexAddr = &mFastCaptureFutex;
7022 state->mColdGen++;
7023 state->mDumpState = &mFastCaptureDumpState;
7024#ifdef TEE_SINK
7025 // FIXME
7026#endif
7027 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7028 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7029 sq->end();
7030 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7031
7032 // start the fast capture
7033 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7034 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007035 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007036 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007037#ifdef AUDIO_WATCHDOG
7038 // FIXME
7039#endif
7040
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007041 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007042 }
Andy Hung8946a282018-04-19 20:04:56 -07007043#ifdef TEE_SINK
7044 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7045 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7046#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007047failed: ;
7048
7049 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007050}
7051
Eric Laurent81784c32012-11-19 14:55:58 -08007052AudioFlinger::RecordThread::~RecordThread()
7053{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007054 if (mFastCapture != 0) {
7055 FastCaptureStateQueue *sq = mFastCapture->sq();
7056 FastCaptureState *state = sq->begin();
7057 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7058 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7059 if (old == -1) {
7060 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7061 }
7062 }
7063 state->mCommand = FastCaptureState::EXIT;
7064 sq->end();
7065 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7066 mFastCapture->join();
7067 mFastCapture.clear();
7068 }
7069 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007070 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007071 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007072}
7073
7074void AudioFlinger::RecordThread::onFirstRef()
7075{
Glenn Kastend7dca052015-03-05 16:05:54 -08007076 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007077}
7078
Eric Laurent555530a2017-02-07 18:17:24 -08007079void AudioFlinger::RecordThread::preExit()
7080{
7081 ALOGV(" preExit()");
7082 Mutex::Autolock _l(mLock);
7083 for (size_t i = 0; i < mTracks.size(); i++) {
7084 sp<RecordTrack> track = mTracks[i];
7085 track->invalidate();
7086 }
7087 mActiveTracks.clear();
7088 mStartStopCond.broadcast();
7089}
7090
Eric Laurent81784c32012-11-19 14:55:58 -08007091bool AudioFlinger::RecordThread::threadLoop()
7092{
Eric Laurent81784c32012-11-19 14:55:58 -08007093 nsecs_t lastWarning = 0;
7094
7095 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007096
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007097reacquire_wakelock:
7098 sp<RecordTrack> activeTrack;
7099 {
7100 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007101 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007102 }
7103
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007104 // used to request a deferred sleep, to be executed later while mutex is unlocked
7105 uint32_t sleepUs = 0;
7106
Andy Hung446f4df2019-02-21 12:26:41 -08007107 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7108
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007109 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007110 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007111 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007112
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007113 // activeTracks accumulates a copy of a subset of mActiveTracks
7114 Vector< sp<RecordTrack> > activeTracks;
7115
Glenn Kasten735f45f2014-08-18 15:51:59 -07007116 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007117 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007118
Glenn Kasten735f45f2014-08-18 15:51:59 -07007119 // reference to a fast track which is about to be removed
7120 sp<RecordTrack> fastTrackToRemove;
7121
Eric Laurent33403f02020-05-29 18:35:06 -07007122 bool silenceFastCapture = false;
7123
Eric Laurent81784c32012-11-19 14:55:58 -08007124 { // scope for mLock
7125 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007126
Eric Laurent021cf962014-05-13 10:18:14 -07007127 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007128
Eric Laurent000a4192014-01-29 15:17:32 -08007129 // check exitPending here because checkForNewParameters_l() and
7130 // checkForNewParameters_l() can temporarily release mLock
7131 if (exitPending()) {
7132 break;
7133 }
7134
Eric Laurent5c25d562016-07-13 17:17:45 -07007135 // sleep with mutex unlocked
7136 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007137 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007138 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7139 ATRACE_END();
7140 sleepUs = 0;
7141 continue;
7142 }
7143
Glenn Kasten2b806402013-11-20 16:37:38 -08007144 // if no active track(s), then standby and release wakelock
7145 size_t size = mActiveTracks.size();
7146 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007147 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007148 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007149 releaseWakeLock_l();
7150 ALOGV("RecordThread: loop stopping");
7151 // go to sleep
7152 mWaitWorkCV.wait(mLock);
7153 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007154 goto reacquire_wakelock;
7155 }
7156
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007157 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007158 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007159 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007160
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007161 activeTrack = mActiveTracks[i];
7162 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007163 if (activeTrack->isFastTrack()) {
7164 ALOG_ASSERT(fastTrackToRemove == 0);
7165 fastTrackToRemove = activeTrack;
7166 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007167 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007168 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007169 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007170 continue;
7171 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007172
7173 TrackBase::track_state activeTrackState = activeTrack->mState;
7174 switch (activeTrackState) {
7175
7176 case TrackBase::PAUSING:
7177 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007178 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007179 doBroadcast = true;
7180 size--;
7181 continue;
7182
7183 case TrackBase::STARTING_1:
7184 sleepUs = 10000;
7185 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007186 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007187 continue;
7188
7189 case TrackBase::STARTING_2:
7190 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007191 if (mStandby) {
7192 mThreadMetrics.logBeginInterval();
7193 mStandby = false;
7194 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007195 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007196 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007197 break;
7198
7199 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007200 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007201 break;
7202
Andy Hungce685402018-10-05 17:23:27 -07007203 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7204 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7205 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007206 default:
Andy Hungce685402018-10-05 17:23:27 -07007207 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7208 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007209 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007210
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007211 if (activeTrack->isFastTrack()) {
7212 ALOG_ASSERT(!mFastTrackAvail);
7213 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007214 // if the active fast track is silenced either:
7215 // 1) silence the whole capture from fast capture buffer if this is
7216 // the only active track
7217 // 2) invalidate this track: this will cause the client to reconnect and possibly
7218 // be invalidated again until unsilenced
7219 if (activeTrack->isSilenced()) {
7220 if (size > 1) {
7221 activeTrack->invalidate();
7222 ALOG_ASSERT(fastTrackToRemove == 0);
7223 fastTrackToRemove = activeTrack;
7224 removeTrack_l(activeTrack);
7225 mActiveTracks.remove(activeTrack);
7226 size--;
7227 continue;
7228 } else {
7229 silenceFastCapture = true;
7230 }
7231 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007232 fastTrack = activeTrack;
7233 }
Eric Laurent33403f02020-05-29 18:35:06 -07007234
7235 activeTracks.add(activeTrack);
7236 i++;
7237
Glenn Kasten9e982352013-08-14 14:39:50 -07007238 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007239
Andy Hungdae27702016-10-31 14:01:16 -07007240 mActiveTracks.updatePowerState(this);
7241
Kevin Rocard069c2712018-03-29 19:09:14 -07007242 updateMetadata_l();
7243
Eric Laurent5c25d562016-07-13 17:17:45 -07007244 if (allStopped) {
7245 standbyIfNotAlreadyInStandby();
7246 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007247 if (doBroadcast) {
7248 mStartStopCond.broadcast();
7249 }
7250
7251 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007252 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007253 if (sleepUs == 0) {
7254 sleepUs = kRecordThreadSleepUs;
7255 }
7256 continue;
7257 }
7258 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007259
Eric Laurent81784c32012-11-19 14:55:58 -08007260 lockEffectChains_l(effectChains);
7261 }
7262
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007263 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007264
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007265 size_t size = effectChains.size();
7266 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007267 // thread mutex is not locked, but effect chain is locked
7268 effectChains[i]->process_l();
7269 }
7270
Glenn Kasten735f45f2014-08-18 15:51:59 -07007271 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007272 if (mFastCapture != 0) {
7273 FastCaptureStateQueue *sq = mFastCapture->sq();
7274 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007275 bool didModify = false;
7276 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007277 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7278 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7279 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7280 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7281 if (old == -1) {
7282 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7283 }
7284 }
7285 state->mCommand = FastCaptureState::READ_WRITE;
7286#if 0 // FIXME
7287 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007288 FastThreadDumpState::kSamplingNforLowRamDevice :
7289 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007290#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007291 didModify = true;
7292 }
7293 audio_track_cblk_t *cblkOld = state->mCblk;
7294 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7295 if (cblkNew != cblkOld) {
7296 state->mCblk = cblkNew;
7297 // block until acked if removing a fast track
7298 if (cblkOld != NULL) {
7299 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7300 }
7301 didModify = true;
7302 }
jiabin01c8f562018-07-19 17:47:28 -07007303 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7304 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7305 if (state->mFastPatchRecordBufferProvider != abp) {
7306 state->mFastPatchRecordBufferProvider = abp;
7307 state->mFastPatchRecordFormat = fastTrack == 0 ?
7308 AUDIO_FORMAT_INVALID : fastTrack->format();
7309 didModify = true;
7310 }
Eric Laurent33403f02020-05-29 18:35:06 -07007311 if (state->mSilenceCapture != silenceFastCapture) {
7312 state->mSilenceCapture = silenceFastCapture;
7313 didModify = true;
7314 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007315 sq->end(didModify);
7316 if (didModify) {
7317 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007318#if 0
7319 if (kUseFastCapture == FastCapture_Dynamic) {
7320 mNormalSource = mPipeSource;
7321 }
7322#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007323 }
7324 }
7325
Glenn Kasten735f45f2014-08-18 15:51:59 -07007326 // now run the fast track destructor with thread mutex unlocked
7327 fastTrackToRemove.clear();
7328
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007329 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7330 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7331 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7332 // If destination is non-contiguous, first read past the nominal end of buffer, then
7333 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007334
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007335 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007336 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007337 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007338
7339 // If an NBAIO source is present, use it to read the normal capture's data
7340 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007341 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007342
7343 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7344 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7345 // we immediately retry the read() to get data and prevent another overflow.
7346 for (int retries = 0; retries <= 2; ++retries) {
7347 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7348 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7349 framesToRead);
7350 if (framesRead != OVERRUN) break;
7351 }
7352
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007353 const ssize_t availableToRead = mPipeSource->availableToRead();
7354 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007355 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007356 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7357 "more frames to read than fifo size, %zd > %zu",
7358 availableToRead, mPipeFramesP2);
7359 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7360 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7361 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7362 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007363 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7364 }
7365 if (framesRead < 0) {
7366 status_t status = (status_t) framesRead;
7367 switch (status) {
7368 case OVERRUN:
7369 ALOGW("overrun on read from pipe");
7370 framesRead = 0;
7371 break;
7372 case NEGOTIATE:
7373 ALOGE("re-negotiation is needed");
7374 framesRead = -1; // Will cause an attempt to recover.
7375 break;
7376 default:
7377 ALOGE("unknown error %d on read from pipe", status);
7378 break;
7379 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007380 }
7381 // otherwise use the HAL / AudioStreamIn directly
7382 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007383 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007384 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007385 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007386 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007387 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007388 if (result < 0) {
7389 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007390 } else {
7391 framesRead = bytesRead / mFrameSize;
7392 }
7393 }
7394
Andy Hung446f4df2019-02-21 12:26:41 -08007395 const int64_t lastIoEndNs = systemTime(); // end IO timing
7396
Andy Hung3f0c9022016-01-15 17:49:46 -08007397 // Update server timestamp with server stats
7398 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007399 if (framesRead >= 0) {
7400 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7401 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7402 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007403
7404 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007405 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007406 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007407 if (mStandby) {
7408 mTimestampVerifier.discontinuity();
Mikhail Naganov2534b382019-09-25 13:05:02 -07007409 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007410 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7411
7412 mTimestampVerifier.add(position, time, mSampleRate);
7413
7414 // Correct timestamps
7415 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007416 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007417 id(), (long long)time, (long long)position);
7418 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7419 position = correctedTimestamp.mFrames;
7420 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007421 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007422 id(), (long long)time, (long long)position);
7423 }
7424
Andy Hung3f0c9022016-01-15 17:49:46 -08007425 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7426 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7427 // Note: In general record buffers should tend to be empty in
7428 // a properly running pipeline.
7429 //
7430 // Also, it is not advantageous to call get_presentation_position during the read
7431 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007432 } else {
7433 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007434 }
7435 }
Andy Hunge6c37112019-02-26 17:38:10 -08007436
7437 // From the timestamp, input read latency is negative output write latency.
7438 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7439 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7440 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7441 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7442 mLatencyMs.add(latencyMs);
7443 }
7444
Andy Hung3f0c9022016-01-15 17:49:46 -08007445 // Use this to track timestamp information
7446 // ALOGD("%s", mTimestamp.toString().c_str());
7447
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007448 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007449 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007450 // Force input into standby so that it tries to recover at next read attempt
7451 inputStandBy();
7452 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007453 }
7454 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007455 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007456 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007457 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007458 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007459
Andy Hung8946a282018-04-19 20:04:56 -07007460#ifdef TEE_SINK
7461 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7462#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007463 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007464 {
7465 size_t part1 = mRsmpInFramesP2 - rear;
7466 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007467 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007468 (framesRead - part1) * mFrameSize);
7469 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007470 }
7471 rear = mRsmpInRear += framesRead;
7472
7473 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007474
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007475 // loop over each active track
7476 for (size_t i = 0; i < size; i++) {
7477 activeTrack = activeTracks[i];
7478
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007479 // skip fast tracks, as those are handled directly by FastCapture
7480 if (activeTrack->isFastTrack()) {
7481 continue;
7482 }
7483
Andy Hung73c02e42015-03-29 01:13:58 -07007484 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007485 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7486
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007487 enum {
7488 OVERRUN_UNKNOWN,
7489 OVERRUN_TRUE,
7490 OVERRUN_FALSE
7491 } overrun = OVERRUN_UNKNOWN;
7492
7493 // loop over getNextBuffer to handle circular sink
7494 for (;;) {
7495
7496 activeTrack->mSink.frameCount = ~0;
7497 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7498 size_t framesOut = activeTrack->mSink.frameCount;
7499 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7500
Andy Hung73c02e42015-03-29 01:13:58 -07007501 // check available frames and handle overrun conditions
7502 // if the record track isn't draining fast enough.
7503 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007504 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007505 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7506 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007507 overrun = OVERRUN_TRUE;
7508 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007509 if (framesOut == 0 || framesIn == 0) {
7510 break;
7511 }
7512
Andy Hung6770c6f2015-04-07 13:43:36 -07007513 // Don't allow framesOut to be larger than what is possible with resampling
7514 // from framesIn.
7515 // This isn't strictly necessary but helps limit buffer resizing in
7516 // RecordBufferConverter. TODO: remove when no longer needed.
7517 framesOut = min(framesOut,
7518 destinationFramesPossible(
7519 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007520
7521 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007522 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007523 // straight from RecordThread buffer to RecordTrack buffer.
7524 AudioBufferProvider::Buffer buffer;
7525 buffer.frameCount = framesOut;
7526 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7527 if (status == OK && buffer.frameCount != 0) {
7528 ALOGV_IF(buffer.frameCount != framesOut,
7529 "%s() read less than expected (%zu vs %zu)",
7530 __func__, buffer.frameCount, framesOut);
7531 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007532 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007533 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7534 } else {
7535 framesOut = 0;
7536 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7537 __func__, status, buffer.frameCount);
7538 }
7539 } else {
7540 // process frames from the RecordThread buffer provider to the RecordTrack
7541 // buffer
7542 framesOut = activeTrack->mRecordBufferConverter->convert(
7543 activeTrack->mSink.raw,
7544 activeTrack->mResamplerBufferProvider,
7545 framesOut);
7546 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007547
7548 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7549 overrun = OVERRUN_FALSE;
7550 }
7551
7552 if (activeTrack->mFramesToDrop == 0) {
7553 if (framesOut > 0) {
7554 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007555 // Sanitize before releasing if the track has no access to the source data
7556 // An idle UID receives silence from non virtual devices until active
7557 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007558 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007559 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007560 activeTrack->releaseBuffer(&activeTrack->mSink);
7561 }
7562 } else {
7563 // FIXME could do a partial drop of framesOut
7564 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007565 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007566 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007567 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007568 }
7569 } else {
7570 activeTrack->mFramesToDrop += framesOut;
7571 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7572 activeTrack->mSyncStartEvent->isCancelled()) {
7573 ALOGW("Synced record %s, session %d, trigger session %d",
7574 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7575 activeTrack->sessionId(),
7576 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007577 activeTrack->mSyncStartEvent->triggerSession() :
7578 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007579 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007580 }
7581 }
7582 }
7583
7584 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007585 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007586 }
7587 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007588
7589 switch (overrun) {
7590 case OVERRUN_TRUE:
7591 // client isn't retrieving buffers fast enough
7592 if (!activeTrack->setOverflow()) {
7593 nsecs_t now = systemTime();
7594 // FIXME should lastWarning per track?
7595 if ((now - lastWarning) > kWarningThrottleNs) {
7596 ALOGW("RecordThread: buffer overflow");
7597 lastWarning = now;
7598 }
7599 }
7600 break;
7601 case OVERRUN_FALSE:
7602 activeTrack->clearOverflow();
7603 break;
7604 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007605 break;
7606 }
7607
Andy Hung3f0c9022016-01-15 17:49:46 -08007608 // update frame information and push timestamp out
7609 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007610 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007611 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7612 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007613 }
7614
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007615unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007616 // enable changes in effect chain
7617 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007618 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007619 if (audio_has_proportional_frames(mFormat)
7620 && loopCount == lastLoopCountRead + 1) {
7621 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7622 const double jitterMs =
7623 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7624 {framesRead, readPeriodNs},
7625 {0, 0} /* lastTimestamp */, mSampleRate);
7626 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7627
7628 Mutex::Autolock _l(mLock);
7629 mIoJitterMs.add(jitterMs);
7630 mProcessTimeMs.add(processMs);
7631 }
7632 // update timing info.
7633 mLastIoBeginNs = lastIoBeginNs;
7634 mLastIoEndNs = lastIoEndNs;
7635 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007636 }
7637
Glenn Kasten93e471f2013-08-19 08:40:07 -07007638 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007639
7640 {
7641 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007642 for (size_t i = 0; i < mTracks.size(); i++) {
7643 sp<RecordTrack> track = mTracks[i];
7644 track->invalidate();
7645 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007646 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007647 mStartStopCond.broadcast();
7648 }
7649
7650 releaseWakeLock();
7651
7652 ALOGV("RecordThread %p exiting", this);
7653 return false;
7654}
7655
Glenn Kasten93e471f2013-08-19 08:40:07 -07007656void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007657{
7658 if (!mStandby) {
7659 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007660 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007661 mStandby = true;
7662 }
7663}
7664
7665void AudioFlinger::RecordThread::inputStandBy()
7666{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007667 // Idle the fast capture if it's currently running
7668 if (mFastCapture != 0) {
7669 FastCaptureStateQueue *sq = mFastCapture->sq();
7670 FastCaptureState *state = sq->begin();
7671 if (!(state->mCommand & FastCaptureState::IDLE)) {
7672 state->mCommand = FastCaptureState::COLD_IDLE;
7673 state->mColdFutexAddr = &mFastCaptureFutex;
7674 state->mColdGen++;
7675 mFastCaptureFutex = 0;
7676 sq->end();
7677 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7678 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7679#if 0
7680 if (kUseFastCapture == FastCapture_Dynamic) {
7681 // FIXME
7682 }
7683#endif
7684#ifdef AUDIO_WATCHDOG
7685 // FIXME
7686#endif
7687 } else {
7688 sq->end(false /*didModify*/);
7689 }
7690 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007691 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007692 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007693
7694 // If going into standby, flush the pipe source.
7695 if (mPipeSource.get() != nullptr) {
7696 const ssize_t flushed = mPipeSource->flush();
7697 if (flushed > 0) {
7698 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7699 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7700 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7701 }
7702 }
Eric Laurent81784c32012-11-19 14:55:58 -08007703}
7704
Glenn Kasten05997e22014-03-13 15:08:33 -07007705// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007706sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007707 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007708 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007709 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007710 audio_format_t format,
7711 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007712 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007713 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007714 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007715 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007716 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007717 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007718 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007719 status_t *status,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007720 audio_port_handle_t portId,
7721 const String16& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08007722{
Glenn Kasten74935e42013-12-19 08:56:45 -08007723 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007724 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007725 sp<RecordTrack> track;
7726 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007727 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007728 audio_input_flags_t requestedFlags = *flags;
7729 uint32_t sampleRate;
7730
7731 lStatus = initCheck();
7732 if (lStatus != NO_ERROR) {
7733 ALOGE("createRecordTrack_l() audio driver not initialized");
7734 goto Exit;
7735 }
7736
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007737 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7738 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7739 lStatus = BAD_VALUE;
7740 goto Exit;
7741 }
7742
Eric Laurentf14db3c2017-12-08 14:20:36 -08007743 if (*pSampleRate == 0) {
7744 *pSampleRate = mSampleRate;
7745 }
7746 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007747
7748 // special case for FAST flag considered OK if fast capture is present
7749 if (hasFastCapture()) {
7750 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7751 }
7752
Eric Laurentf14db3c2017-12-08 14:20:36 -08007753 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007754 if ((*flags & inputFlags) != *flags) {
7755 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7756 " input flags (%08x)",
7757 *flags, inputFlags);
7758 *flags = (audio_input_flags_t)(*flags & inputFlags);
7759 }
Eric Laurent81784c32012-11-19 14:55:58 -08007760
Glenn Kasten90e58b12013-07-31 16:16:02 -07007761 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007762 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007763 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007764 // we formerly checked for a callback handler (non-0 tid),
7765 // but that is no longer required for TRANSFER_OBTAIN mode
7766 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007767 // Frame count is not specified (0), or is less than or equal the pipe depth.
7768 // It is OK to provide a higher capacity than requested.
7769 // We will force it to mPipeFramesP2 below.
7770 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007771 // PCM data
7772 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007773 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007774 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007775 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007776 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007777 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007778 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007779 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007780 hasFastCapture() &&
7781 // there are sufficient fast track slots available
7782 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007783 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007784 // check compatibility with audio effects.
7785 Mutex::Autolock _l(mLock);
7786 // Do not accept FAST flag if the session has software effects
7787 sp<EffectChain> chain = getEffectChain_l(sessionId);
7788 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007789 audio_input_flags_t old = *flags;
7790 chain->checkInputFlagCompatibility(flags);
7791 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007792 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7793 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007794 }
7795 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007796 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007797 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7798 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007799 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007800 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7801 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007802 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007803 this, frameCount, mFrameCount, mPipeFramesP2,
7804 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007805 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007806 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007807 }
7808 }
7809
Eric Laurentf14db3c2017-12-08 14:20:36 -08007810 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7811 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7812 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7813 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7814 lStatus = BAD_TYPE;
7815 goto Exit;
7816 }
7817
Glenn Kasten74105912014-07-03 12:28:53 -07007818 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007819 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007820 // fast track: frame count is exactly the pipe depth
7821 frameCount = mPipeFramesP2;
7822 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007823 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007824 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007825 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7826 // or 20 ms if there is a fast capture
7827 // TODO This could be a roundupRatio inline, and const
7828 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7829 * sampleRate + mSampleRate - 1) / mSampleRate;
7830 // minimum number of notification periods is at least kMinNotifications,
7831 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7832 static const size_t kMinNotifications = 3;
7833 static const uint32_t kMinMs = 30;
7834 // TODO This could be a roundupRatio inline
7835 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7836 // TODO This could be a roundupRatio inline
7837 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7838 maxNotificationFrames;
7839 const size_t minFrameCount = maxNotificationFrames *
7840 max(kMinNotifications, minNotificationsByMs);
7841 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007842 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7843 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007844 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007845 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007846 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007847 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007848
7849 { // scope for mLock
7850 Mutex::Autolock _l(mLock);
7851
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007852 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007853 format, channelMask, frameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007854 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, uid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007855 *flags, TrackBase::TYPE_DEFAULT, opPackageName, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007856
Glenn Kasten03003332013-08-06 15:40:54 -07007857 lStatus = track->initCheck();
7858 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007859 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007860 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007861 goto Exit;
7862 }
7863 mTracks.add(track);
7864
Eric Laurent05067782016-06-01 18:27:28 -07007865 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007866 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7867 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7868 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007869 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007870 }
Eric Laurent81784c32012-11-19 14:55:58 -08007871 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007872
Eric Laurent81784c32012-11-19 14:55:58 -08007873 lStatus = NO_ERROR;
7874
7875Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007876 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007877 return track;
7878}
7879
7880status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7881 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007882 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007883{
7884 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7885 sp<ThreadBase> strongMe = this;
7886 status_t status = NO_ERROR;
7887
7888 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007889 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007890 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007891 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007892 triggerSession,
7893 recordTrack->sessionId(),
7894 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007895 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007896 // Sync event can be cancelled by the trigger session if the track is not in a
7897 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007898 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007899 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007900 } else {
7901 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007902 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007903 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007904 }
7905 }
7906
7907 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007908 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007909 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007910 if (recordTrack->isInvalid()) {
7911 recordTrack->clearSyncStartEvent();
7912 return INVALID_OPERATION;
7913 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007914 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7915 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007916 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7917 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007918 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007919 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007920 } else {
7921 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007922 }
7923 return status;
7924 }
7925
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007926 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7927 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7928 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007929 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007930 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007931 status_t status = NO_ERROR;
7932 if (recordTrack->isExternalTrack()) {
7933 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007934 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007935 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007936 if (recordTrack->isInvalid()) {
7937 recordTrack->clearSyncStartEvent();
7938 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7939 recordTrack->mState = TrackBase::STARTING_2;
7940 // STARTING_2 forces destroy to call stopInput.
7941 }
7942 return INVALID_OPERATION;
7943 }
7944 if (recordTrack->mState != TrackBase::STARTING_1) {
7945 ALOGW("%s(%d): unsynchronized mState:%d change",
7946 __func__, recordTrack->id(), recordTrack->mState);
7947 // Someone else has changed state, let them take over,
7948 // leave mState in the new state.
7949 recordTrack->clearSyncStartEvent();
7950 return INVALID_OPERATION;
7951 }
7952 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007953 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007954 ALOGW("%s(%d): startInput failed, status %d",
7955 __func__, recordTrack->id(), status);
7956 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7957 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007958 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007959 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007960 return status;
7961 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07007962 sendIoConfigEvent_l(
7963 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08007964 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07007965
7966 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
7967
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007968 // Catch up with current buffer indices if thread is already running.
7969 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7970 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7971 // see previously buffered data before it called start(), but with greater risk of overrun.
7972
Andy Hung73c02e42015-03-29 01:13:58 -07007973 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007974 if (!recordTrack->isDirect()) {
7975 // clear any converter state as new data will be discontinuous
7976 recordTrack->mRecordBufferConverter->reset();
7977 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007978 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007979 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007980 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007981 return status;
7982 }
Eric Laurent81784c32012-11-19 14:55:58 -08007983}
7984
Eric Laurent81784c32012-11-19 14:55:58 -08007985void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7986{
7987 sp<SyncEvent> strongEvent = event.promote();
7988
7989 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007990 sp<RefBase> ptr = strongEvent->cookie().promote();
7991 if (ptr != 0) {
7992 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7993 recordTrack->handleSyncStartEvent(strongEvent);
7994 }
Eric Laurent81784c32012-11-19 14:55:58 -08007995 }
7996}
7997
Glenn Kastena8356f62013-07-25 14:37:52 -07007998bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007999 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008000 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008001 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008002 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008003 return false;
8004 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008005 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008006 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008007
Andy Hungabfab202019-03-07 19:45:54 -08008008 // NOTE: Waiting here is important to keep stop synchronous.
8009 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008010 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8011 mWaitWorkCV.broadcast(); // signal thread to stop
8012 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008013 }
Andy Hungce685402018-10-05 17:23:27 -07008014
8015 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008016 ALOGV("Record stopped OK");
8017 return true;
8018 }
Andy Hungce685402018-10-05 17:23:27 -07008019
8020 // don't handle anything - we've been invalidated or restarted and in a different state
8021 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8022 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008023 return false;
8024}
8025
Glenn Kasten0f11b512014-01-31 16:18:54 -08008026bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008027{
8028 return false;
8029}
8030
Glenn Kasten0f11b512014-01-31 16:18:54 -08008031status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008032{
8033#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8034 if (!isValidSyncEvent(event)) {
8035 return BAD_VALUE;
8036 }
8037
Glenn Kastend848eb42016-03-08 13:42:11 -08008038 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008039 status_t ret = NAME_NOT_FOUND;
8040
8041 Mutex::Autolock _l(mLock);
8042
8043 for (size_t i = 0; i < mTracks.size(); i++) {
8044 sp<RecordTrack> track = mTracks[i];
8045 if (eventSession == track->sessionId()) {
8046 (void) track->setSyncEvent(event);
8047 ret = NO_ERROR;
8048 }
8049 }
8050 return ret;
8051#else
8052 return BAD_VALUE;
8053#endif
8054}
8055
jiabin653cc0a2018-01-17 17:54:10 -08008056status_t AudioFlinger::RecordThread::getActiveMicrophones(
8057 std::vector<media::MicrophoneInfo>* activeMicrophones)
8058{
8059 ALOGV("RecordThread::getActiveMicrophones");
8060 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07008061 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8062 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008063}
8064
Paul McLean12340082019-03-19 09:35:05 -06008065status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8066 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008067{
Paul McLean12340082019-03-19 09:35:05 -06008068 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008069 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008070 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008071}
8072
Paul McLean12340082019-03-19 09:35:05 -06008073status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008074{
Paul McLean12340082019-03-19 09:35:05 -06008075 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008076 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06008077 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008078}
8079
Kevin Rocard069c2712018-03-29 19:09:14 -07008080void AudioFlinger::RecordThread::updateMetadata_l()
8081{
8082 if (mInput == nullptr || mInput->stream == nullptr ||
8083 !mActiveTracks.readAndClearHasChanged()) {
8084 return;
8085 }
8086 StreamInHalInterface::SinkMetadata metadata;
8087 for (const sp<RecordTrack> &track : mActiveTracks) {
8088 // No track is invalid as this is called after prepareTrack_l in the same critical section
8089 metadata.tracks.push_back({
8090 .source = track->attributes().source,
8091 .gain = 1, // capture tracks do not have volumes
8092 });
8093 }
8094 mInput->stream->updateSinkMetadata(metadata);
8095}
8096
Eric Laurent81784c32012-11-19 14:55:58 -08008097// destroyTrack_l() must be called with ThreadBase::mLock held
8098void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8099{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008100 track->terminate();
8101 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08008102 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008103 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008104 removeTrack_l(track);
8105 }
8106}
8107
8108void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8109{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008110 String8 result;
8111 track->appendDump(result, false /* active */);
8112 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8113
Eric Laurent81784c32012-11-19 14:55:58 -08008114 mTracks.remove(track);
8115 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008116 if (track->isFastTrack()) {
8117 ALOG_ASSERT(!mFastTrackAvail);
8118 mFastTrackAvail = true;
8119 }
Eric Laurent81784c32012-11-19 14:55:58 -08008120}
8121
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008122void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008123{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008124 AudioStreamIn *input = mInput;
8125 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8126 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008127 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008128 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008129 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008130 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008131 }
Andy Hungbfa64962017-06-12 14:43:19 -07008132
8133 if (input != nullptr) {
8134 dprintf(fd, " Hal stream dump:\n");
8135 (void)input->stream->dump(fd);
8136 }
8137
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008138 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008139 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008140
Glenn Kasten2f90c512015-12-02 11:40:09 -08008141 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8142 // while we are dumping it. It may be inconsistent, but it won't mutate!
8143 // This is a large object so we place it on the heap.
8144 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008145 const std::unique_ptr<FastCaptureDumpState> copy =
8146 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008147 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008148}
8149
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008150void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008151{
Eric Laurent81784c32012-11-19 14:55:58 -08008152 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008153 size_t numtracks = mTracks.size();
8154 size_t numactive = mActiveTracks.size();
8155 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008156 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008157 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008158 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008159 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008160 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008161 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008162 for (size_t i = 0; i < numtracks ; ++i) {
8163 sp<RecordTrack> track = mTracks[i];
8164 if (track != 0) {
8165 bool active = mActiveTracks.indexOf(track) >= 0;
8166 if (active) {
8167 numactiveseen++;
8168 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008169 result.append(prefix);
8170 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008171 }
Eric Laurent81784c32012-11-19 14:55:58 -08008172 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008173 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008174 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008175 }
8176
Marco Nelissenb2208842014-02-07 14:00:50 -08008177 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008178 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008179 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008180 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008181 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008182 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008183 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008184 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008185 result.append(prefix);
8186 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008187 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008188 }
Eric Laurent81784c32012-11-19 14:55:58 -08008189
8190 }
8191 write(fd, result.string(), result.size());
8192}
8193
Eric Laurent5ada82e2019-08-29 17:53:54 -07008194void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008195{
8196 Mutex::Autolock _l(mLock);
8197 for (size_t i = 0; i < mTracks.size() ; i++) {
8198 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008199 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008200 track->setSilenced(silenced);
8201 }
8202 }
8203}
Andy Hung73c02e42015-03-29 01:13:58 -07008204
8205void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8206{
8207 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8208 RecordThread *recordThread = (RecordThread *) threadBase.get();
8209 mRsmpInFront = recordThread->mRsmpInRear;
8210 mRsmpInUnrel = 0;
8211}
8212
8213void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8214 size_t *framesAvailable, bool *hasOverrun)
8215{
8216 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8217 RecordThread *recordThread = (RecordThread *) threadBase.get();
8218 const int32_t rear = recordThread->mRsmpInRear;
8219 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008220 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008221
8222 size_t framesIn;
8223 bool overrun = false;
8224 if (filled < 0) {
8225 // should not happen, but treat like a massive overrun and re-sync
8226 framesIn = 0;
8227 mRsmpInFront = rear;
8228 overrun = true;
8229 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8230 framesIn = (size_t) filled;
8231 } else {
8232 // client is not keeping up with server, but give it latest data
8233 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008234 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8235 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008236 overrun = true;
8237 }
8238 if (framesAvailable != NULL) {
8239 *framesAvailable = framesIn;
8240 }
8241 if (hasOverrun != NULL) {
8242 *hasOverrun = overrun;
8243 }
8244}
8245
Eric Laurent81784c32012-11-19 14:55:58 -08008246// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008247status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008248 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008249{
Andy Hung73c02e42015-03-29 01:13:58 -07008250 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008251 if (threadBase == 0) {
8252 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008253 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008254 return NOT_ENOUGH_DATA;
8255 }
8256 RecordThread *recordThread = (RecordThread *) threadBase.get();
8257 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008258 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008259 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008260 // FIXME should not be P2 (don't want to increase latency)
8261 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008262 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008263 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008264 front &= recordThread->mRsmpInFramesP2 - 1;
8265 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008266 if (part1 > (size_t) filled) {
8267 part1 = filled;
8268 }
8269 size_t ask = buffer->frameCount;
8270 ALOG_ASSERT(ask > 0);
8271 if (part1 > ask) {
8272 part1 = ask;
8273 }
8274 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008275 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008276 buffer->raw = NULL;
8277 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008278 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008279 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008280 }
8281
Andy Hung57446612015-04-19 23:56:46 -07008282 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008283 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008284 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008285 return NO_ERROR;
8286}
8287
8288// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008289void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8290 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008291{
Hongwei Wang95e37682019-04-12 11:13:36 -07008292 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008293 if (stepCount == 0) {
8294 return;
8295 }
Andy Hung73c02e42015-03-29 01:13:58 -07008296 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8297 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008298 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008299 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008300 buffer->frameCount = 0;
8301}
8302
Eric Laurentd8365c52017-07-16 15:27:05 -07008303void AudioFlinger::RecordThread::checkBtNrec()
8304{
8305 Mutex::Autolock _l(mLock);
8306 checkBtNrec_l();
8307}
8308
8309void AudioFlinger::RecordThread::checkBtNrec_l()
8310{
8311 // disable AEC and NS if the device is a BT SCO headset supporting those
8312 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008313 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008314 mAudioFlinger->btNrecIsOff();
8315 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8316 for (size_t i = 0; i < mEffectChains.size(); i++) {
8317 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8318 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8319 }
8320 }
8321}
8322
Andy Hung97a893e2015-03-29 01:03:07 -07008323
Eric Laurent10351942014-05-08 18:49:52 -07008324bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8325 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008326{
8327 bool reconfig = false;
8328
Eric Laurent10351942014-05-08 18:49:52 -07008329 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008330
Eric Laurent10351942014-05-08 18:49:52 -07008331 audio_format_t reqFormat = mFormat;
8332 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008333 // 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 -07008334 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8335
8336 AudioParameter param = AudioParameter(keyValuePair);
8337 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008338
8339 // scope for AutoPark extends to end of method
8340 AutoPark<FastCapture> park(mFastCapture);
8341
Eric Laurent10351942014-05-08 18:49:52 -07008342 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8343 // channel count change can be requested. Do we mandate the first client defines the
8344 // HAL sampling rate and channel count or do we allow changes on the fly?
8345 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8346 samplingRate = value;
8347 reconfig = true;
8348 }
8349 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008350 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008351 status = BAD_VALUE;
8352 } else {
8353 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008354 reconfig = true;
8355 }
Eric Laurent10351942014-05-08 18:49:52 -07008356 }
8357 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8358 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008359 if (!audio_is_input_channel(mask) ||
8360 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008361 status = BAD_VALUE;
8362 } else {
8363 channelMask = mask;
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::keyFrameCount), value) == NO_ERROR) {
8368 // do not accept frame count changes if tracks are open as the track buffer
8369 // size depends on frame count and correct behavior would not be guaranteed
8370 // if frame count is changed after track creation
8371 if (mActiveTracks.size() > 0) {
8372 status = INVALID_OPERATION;
8373 } else {
8374 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008375 }
Eric Laurent10351942014-05-08 18:49:52 -07008376 }
8377 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008378 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008379 }
8380 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8381 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008382 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008383 }
Glenn Kastene198c362013-08-13 09:13:36 -07008384
Eric Laurent10351942014-05-08 18:49:52 -07008385 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008386 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008387 if (status == INVALID_OPERATION) {
8388 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008389 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008390 }
8391 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008392 if (status == BAD_VALUE) {
8393 uint32_t sRate;
8394 audio_channel_mask_t channelMask;
8395 audio_format_t format;
8396 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8397 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8398 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8399 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8400 status = NO_ERROR;
8401 }
Eric Laurent81784c32012-11-19 14:55:58 -08008402 }
Eric Laurent10351942014-05-08 18:49:52 -07008403 if (status == NO_ERROR) {
8404 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008405 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008406 }
8407 }
Eric Laurent81784c32012-11-19 14:55:58 -08008408 }
Eric Laurent10351942014-05-08 18:49:52 -07008409
Eric Laurent81784c32012-11-19 14:55:58 -08008410 return reconfig;
8411}
8412
8413String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8414{
Eric Laurent81784c32012-11-19 14:55:58 -08008415 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008416 if (initCheck() == NO_ERROR) {
8417 String8 out_s8;
8418 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8419 return out_s8;
8420 }
Eric Laurent81784c32012-11-19 14:55:58 -08008421 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008422 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008423}
8424
Eric Laurent09f1ed22019-04-24 17:45:17 -07008425void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8426 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008427 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8428
8429 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008430
8431 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008432 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008433 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008434 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008435 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008436 desc->mChannelMask = mChannelMask;
8437 desc->mSamplingRate = mSampleRate;
8438 desc->mFormat = mFormat;
8439 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008440 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008441 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008442 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008443 case AUDIO_CLIENT_STARTED:
8444 desc->mPatch = mPatch;
8445 desc->mPortId = portId;
8446 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008447 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008448 default:
8449 break;
8450 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008451 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008452}
8453
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008454void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008455{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008456 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8457 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008458 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008459 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8460 if (audio_is_linear_pcm(mFormat)) {
8461 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8462 mChannelCount, FCC_8);
8463 } else {
8464 // Can have more that FCC_8 channels in encoded streams.
8465 ALOGI("HAL format %#x is not linear pcm", mFormat);
8466 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008467 result = mInput->stream->getFrameSize(&mFrameSize);
8468 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008469 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8470 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008471 result = mInput->stream->getBufferSize(&mBufferSize);
8472 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008473 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008474 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8475 "mBufferSize=%zu, mFrameCount=%zu",
8476 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008477 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008478 // 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 -07008479 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008480 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008481 // A larger value should allow more old data to be read after a track calls start(),
8482 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008483 //
8484 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008485 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008486 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008487 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008488 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008489
8490 // TODO optimize audio capture buffer sizes ...
8491 // Here we calculate the size of the sliding buffer used as a source
8492 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8493 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8494 // be better to have it derived from the pipe depth in the long term.
8495 // The current value is higher than necessary. However it should not add to latency.
8496
Glenn Kasten85948432013-08-19 12:09:05 -07008497 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008498 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8499 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008500 // if posix_memalign fails, will segv here.
8501 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008502
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008503 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8504 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008505
8506 audio_input_flags_t flags = mInput->flags;
8507 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8508 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8509 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8510 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8511 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8512 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8513 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8514 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8515 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008516}
8517
Glenn Kasten5f972c02014-01-13 09:59:31 -08008518uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008519{
8520 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008521 uint32_t result;
8522 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8523 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008524 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008525 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008526}
8527
Glenn Kastend848eb42016-03-08 13:42:11 -08008528KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008529{
Glenn Kastend848eb42016-03-08 13:42:11 -08008530 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008531 Mutex::Autolock _l(mLock);
8532 for (size_t j = 0; j < mTracks.size(); ++j) {
8533 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008534 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008535 if (ids.indexOfKey(sessionId) < 0) {
8536 ids.add(sessionId, true);
8537 }
8538 }
8539 return ids;
8540}
8541
8542AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8543{
8544 Mutex::Autolock _l(mLock);
8545 AudioStreamIn *input = mInput;
8546 mInput = NULL;
8547 return input;
8548}
8549
8550// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008551sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008552{
8553 if (mInput == NULL) {
8554 return NULL;
8555 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008556 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008557}
8558
8559status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8560{
Eric Laurent81784c32012-11-19 14:55:58 -08008561 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008562 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008563 chain->setInBuffer(NULL);
8564 chain->setOutBuffer(NULL);
8565
8566 checkSuspendOnAddEffectChain_l(chain);
8567
Eric Laurent1b928682014-10-02 19:41:47 -07008568 // make sure enabled pre processing effects state is communicated to the HAL as we
8569 // just moved them to a new input stream.
8570 chain->syncHalEffectsState();
8571
Eric Laurent81784c32012-11-19 14:55:58 -08008572 mEffectChains.add(chain);
8573
8574 return NO_ERROR;
8575}
8576
8577size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8578{
8579 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008580
8581 for (size_t i = 0; i < mEffectChains.size(); i++) {
8582 if (chain == mEffectChains[i]) {
8583 mEffectChains.removeAt(i);
8584 break;
8585 }
Eric Laurent81784c32012-11-19 14:55:58 -08008586 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008587 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008588}
8589
Eric Laurent1c333e22014-05-20 10:48:17 -07008590status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8591 audio_patch_handle_t *handle)
8592{
8593 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008594
8595 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008596 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008597 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008598 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008599 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008600 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008601 }
8602
Eric Laurentd8365c52017-07-16 15:27:05 -07008603 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008604
8605 // store new source and send to effects
8606 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8607 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008608 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008609 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008610 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008611 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008612
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008613 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008614 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8615 status = hwDevice->createAudioPatch(patch->num_sources,
8616 patch->sources,
8617 patch->num_sinks,
8618 patch->sinks,
8619 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008620 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008621 char *address;
8622 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8623 address = audio_device_address_to_parameter(
8624 patch->sources[0].ext.device.type,
8625 patch->sources[0].ext.device.address);
8626 } else {
8627 address = (char *)calloc(1, 1);
8628 }
8629 AudioParameter param = AudioParameter(String8(address));
8630 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008631 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008632 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008633 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008634 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008635 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008636 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008637 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008638
jiabinc52b1ff2019-10-31 17:20:42 -07008639 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008640 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008641 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008642 }
Eric Laurent296fb132015-05-01 11:38:42 -07008643
Andy Hungc2b11cb2020-04-22 09:04:01 -07008644 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008645 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008646 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008647 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008648 // also dispatch to active AudioRecords
8649 for (const auto &track : mActiveTracks) {
8650 track->logEndInterval();
8651 track->logBeginInterval(pathSourcesAsString);
8652 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008653 return status;
8654}
8655
8656status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8657{
8658 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008659
jiabinc52b1ff2019-10-31 17:20:42 -07008660 mPatch = audio_patch{};
8661 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008662
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008663 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008664 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8665 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008666 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008667 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008668 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008669 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008670 }
8671 return status;
8672}
8673
jiabinc52b1ff2019-10-31 17:20:42 -07008674void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8675{
8676 mOutDevices = outDevices;
8677 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8678 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008679 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008680 }
8681}
8682
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008683void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008684{
8685 Mutex::Autolock _l(mLock);
8686 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008687 if (record->getSource()) {
8688 mSource = record->getSource();
8689 }
Eric Laurent83b88082014-06-20 18:31:16 -07008690}
8691
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008692void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008693{
8694 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008695 if (mSource == record->getSource()) {
8696 mSource = mInput;
8697 }
Eric Laurent83b88082014-06-20 18:31:16 -07008698 destroyTrack_l(record);
8699}
8700
Mikhail Naganovdc769682018-05-04 15:34:08 -07008701void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008702{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008703 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008704 config->role = AUDIO_PORT_ROLE_SINK;
8705 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8706 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008707 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8708 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8709 config->flags.input = mInput->flags;
8710 }
Eric Laurent83b88082014-06-20 18:31:16 -07008711}
Eric Laurent1c333e22014-05-20 10:48:17 -07008712
Eric Laurent6acd1d42017-01-04 14:23:29 -08008713// ----------------------------------------------------------------------------
8714// Mmap
8715// ----------------------------------------------------------------------------
8716
8717AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8718 : mThread(thread)
8719{
Phil Burk9fabbf82017-08-03 12:02:00 -07008720 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008721}
8722
8723AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8724{
Phil Burk9fabbf82017-08-03 12:02:00 -07008725 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008726}
8727
8728status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8729 struct audio_mmap_buffer_info *info)
8730{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008731 return mThread->createMmapBuffer(minSizeFrames, info);
8732}
8733
8734status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8735{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008736 return mThread->getMmapPosition(position);
8737}
8738
Eric Laurenta54f1282017-07-01 19:39:32 -07008739status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008740 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008741
8742{
jiabind1f1cb62020-03-24 11:57:57 -07008743 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008744}
8745
8746status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8747{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008748 return mThread->stop(handle);
8749}
8750
Eric Laurent18b57012017-02-13 16:23:52 -08008751status_t AudioFlinger::MmapThreadHandle::standby()
8752{
Eric Laurent18b57012017-02-13 16:23:52 -08008753 return mThread->standby();
8754}
8755
Eric Laurent6acd1d42017-01-04 14:23:29 -08008756
8757AudioFlinger::MmapThread::MmapThread(
8758 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07008759 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07008760 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008761 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008762 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008763 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008764 mActiveTracks(&this->mLocalLog),
8765 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8766 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008767{
Eric Laurent18b57012017-02-13 16:23:52 -08008768 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008769 readHalParameters_l();
8770}
8771
8772AudioFlinger::MmapThread::~MmapThread()
8773{
Eric Laurent18b57012017-02-13 16:23:52 -08008774 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008775}
8776
8777void AudioFlinger::MmapThread::onFirstRef()
8778{
8779 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8780}
8781
8782void AudioFlinger::MmapThread::disconnect()
8783{
Eric Laurent331679c2018-04-16 17:03:16 -07008784 ActiveTracks<MmapTrack> activeTracks;
8785 {
8786 Mutex::Autolock _l(mLock);
8787 for (const sp<MmapTrack> &t : mActiveTracks) {
8788 activeTracks.add(t);
8789 }
8790 }
8791 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008792 stop(t->portId());
8793 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008794 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008795 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008796 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008797 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008798 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008799 }
8800}
8801
8802
8803void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8804 audio_stream_type_t streamType __unused,
8805 audio_session_t sessionId,
8806 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008807 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008808 audio_port_handle_t portId)
8809{
8810 mAttr = *attr;
8811 mSessionId = sessionId;
8812 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008813 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008814 mPortId = portId;
8815}
8816
8817status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8818 struct audio_mmap_buffer_info *info)
8819{
8820 if (mHalStream == 0) {
8821 return NO_INIT;
8822 }
Eric Laurent18b57012017-02-13 16:23:52 -08008823 mStandby = true;
8824 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008825 return mHalStream->createMmapBuffer(minSizeFrames, info);
8826}
8827
8828status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8829{
8830 if (mHalStream == 0) {
8831 return NO_INIT;
8832 }
8833 return mHalStream->getMmapPosition(position);
8834}
8835
Eric Laurent331679c2018-04-16 17:03:16 -07008836status_t AudioFlinger::MmapThread::exitStandby()
8837{
8838 status_t ret = mHalStream->start();
8839 if (ret != NO_ERROR) {
8840 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8841 return ret;
8842 }
Andy Hungcf10d742020-04-28 15:38:24 -07008843 if (mStandby) {
8844 mThreadMetrics.logBeginInterval();
8845 mStandby = false;
8846 }
Eric Laurent331679c2018-04-16 17:03:16 -07008847 return NO_ERROR;
8848}
8849
Eric Laurenta54f1282017-07-01 19:39:32 -07008850status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07008851 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008852 audio_port_handle_t *handle)
8853{
Eric Laurenta54f1282017-07-01 19:39:32 -07008854 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8855 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008856 if (mHalStream == 0) {
8857 return NO_INIT;
8858 }
8859
8860 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008861
Eric Laurenta54f1282017-07-01 19:39:32 -07008862 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008863 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008864 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008865 }
8866
8867 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8868
8869 audio_io_handle_t io = mId;
8870 if (isOutput()) {
8871 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8872 config.sample_rate = mSampleRate;
8873 config.channel_mask = mChannelMask;
8874 config.format = mFormat;
8875 audio_stream_type_t stream = streamType();
8876 audio_output_flags_t flags =
8877 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008878 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008879 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008880 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8881 mSessionId,
8882 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008883 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008884 client.clientUid,
8885 &config,
8886 flags,
8887 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008888 &portId,
8889 &secondaryOutputs);
8890 ALOGD_IF(!secondaryOutputs.empty(),
8891 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008892 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008893 audio_config_base_t config;
8894 config.sample_rate = mSampleRate;
8895 config.channel_mask = mChannelMask;
8896 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008897 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008898 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07008899 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07008900 mSessionId,
8901 client.clientPid,
8902 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008903 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008904 &config,
8905 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8906 &deviceId,
8907 &portId);
8908 }
8909 // APM should not chose a different input or output stream for the same set of attributes
8910 // and audo configuration
8911 if (ret != NO_ERROR || io != mId) {
8912 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8913 __FUNCTION__, ret, io, mId);
8914 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008915 }
8916
8917 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008918 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008919 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008920 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008921 }
8922
Eric Laurent331679c2018-04-16 17:03:16 -07008923 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008924 // abort if start is rejected by audio policy manager
8925 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008926 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008927 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008928 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008929 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008930 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008931 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008932 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008933 }
Eric Laurent331679c2018-04-16 17:03:16 -07008934 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008935 } else {
8936 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008937 }
8938 return PERMISSION_DENIED;
8939 }
8940
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008941 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07008942 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
8943 mChannelMask, mSessionId, isOutput(), client.clientUid,
8944 client.clientPid, IPCThreadState::self()->getCallingPid(),
8945 portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008946
Eric Laurent4eb58f12018-12-07 16:41:02 -08008947 if (isOutput()) {
8948 // force volume update when a new track is added
8949 mHalVolFloat = -1.0f;
8950 } else if (!track->isSilenced_l()) {
8951 for (const sp<MmapTrack> &t : mActiveTracks) {
8952 if (t->isSilenced_l() && t->uid() != client.clientUid)
8953 t->invalidate();
8954 }
8955 }
8956
8957
Eric Laurent6acd1d42017-01-04 14:23:29 -08008958 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008959 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008960 if (chain != 0) {
8961 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8962 chain->incTrackCnt();
8963 chain->incActiveTrackCnt();
8964 }
8965
Andy Hungc2b11cb2020-04-22 09:04:01 -07008966 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08008967 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008968 broadcast_l();
8969
Eric Laurenta54f1282017-07-01 19:39:32 -07008970 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008971
8972 return NO_ERROR;
8973}
8974
8975status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8976{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008977 ALOGV("%s handle %d", __FUNCTION__, handle);
8978
8979 if (mHalStream == 0) {
8980 return NO_INIT;
8981 }
8982
Eric Laurenta54f1282017-07-01 19:39:32 -07008983 if (handle == mPortId) {
8984 mHalStream->stop();
8985 return NO_ERROR;
8986 }
8987
Eric Laurent331679c2018-04-16 17:03:16 -07008988 Mutex::Autolock _l(mLock);
8989
Eric Laurent6acd1d42017-01-04 14:23:29 -08008990 sp<MmapTrack> track;
8991 for (const sp<MmapTrack> &t : mActiveTracks) {
8992 if (handle == t->portId()) {
8993 track = t;
8994 break;
8995 }
8996 }
8997 if (track == 0) {
8998 return BAD_VALUE;
8999 }
9000
9001 mActiveTracks.remove(track);
9002
Eric Laurent331679c2018-04-16 17:03:16 -07009003 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009004 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009005 AudioSystem::stopOutput(track->portId());
9006 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009007 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009008 AudioSystem::stopInput(track->portId());
9009 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009010 }
Eric Laurent331679c2018-04-16 17:03:16 -07009011 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009012
9013 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9014 if (chain != 0) {
9015 chain->decActiveTrackCnt();
9016 chain->decTrackCnt();
9017 }
9018
9019 broadcast_l();
9020
Eric Laurent6acd1d42017-01-04 14:23:29 -08009021 return NO_ERROR;
9022}
9023
Eric Laurent18b57012017-02-13 16:23:52 -08009024status_t AudioFlinger::MmapThread::standby()
9025{
9026 ALOGV("%s", __FUNCTION__);
9027
9028 if (mHalStream == 0) {
9029 return NO_INIT;
9030 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009031 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009032 return INVALID_OPERATION;
9033 }
9034 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009035 if (!mStandby) {
9036 mThreadMetrics.logEndInterval();
9037 mStandby = true;
9038 }
Eric Laurent18b57012017-02-13 16:23:52 -08009039 releaseWakeLock();
9040 return NO_ERROR;
9041}
9042
Eric Laurent6acd1d42017-01-04 14:23:29 -08009043
9044void AudioFlinger::MmapThread::readHalParameters_l()
9045{
9046 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9047 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9048 mFormat = mHALFormat;
9049 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9050 result = mHalStream->getFrameSize(&mFrameSize);
9051 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009052 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9053 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009054 result = mHalStream->getBufferSize(&mBufferSize);
9055 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9056 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009057
Andy Hungcf10d742020-04-28 15:38:24 -07009058 // TODO: make a readHalParameters call?
9059 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009060 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9061 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9062 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9063 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9064 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9065 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9066 /*
9067 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9068 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9069 (int32_t)mHapticChannelMask)
9070 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9071 (int32_t)mHapticChannelCount)
9072 */
9073 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9074 formatToString(mHALFormat).c_str())
9075 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9076 (int32_t)mFrameCount) // sic - added HAL
9077 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009078}
9079
9080bool AudioFlinger::MmapThread::threadLoop()
9081{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009082 checkSilentMode_l();
9083
9084 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9085
9086 while (!exitPending())
9087 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009088 Vector< sp<EffectChain> > effectChains;
9089
Andy Hung13850be2019-03-14 11:33:09 -07009090 { // under Thread lock
9091 Mutex::Autolock _l(mLock);
9092
Eric Laurent6acd1d42017-01-04 14:23:29 -08009093 if (mSignalPending) {
9094 // A signal was raised while we were unlocked
9095 mSignalPending = false;
9096 } else {
9097 if (mConfigEvents.isEmpty()) {
9098 // we're about to wait, flush the binder command buffer
9099 IPCThreadState::self()->flushCommands();
9100
9101 if (exitPending()) {
9102 break;
9103 }
9104
Eric Laurent6acd1d42017-01-04 14:23:29 -08009105 // wait until we have something to do...
9106 ALOGV("%s going to sleep", myName.string());
9107 mWaitWorkCV.wait(mLock);
9108 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009109
9110 checkSilentMode_l();
9111
9112 continue;
9113 }
9114 }
9115
9116 processConfigEvents_l();
9117
9118 processVolume_l();
9119
9120 checkInvalidTracks_l();
9121
9122 mActiveTracks.updatePowerState(this);
9123
Kevin Rocard069c2712018-03-29 19:09:14 -07009124 updateMetadata_l();
9125
Eric Laurent6acd1d42017-01-04 14:23:29 -08009126 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009127 } // release Thread lock
9128
Eric Laurent6acd1d42017-01-04 14:23:29 -08009129 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009130 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009131 }
Andy Hung13850be2019-03-14 11:33:09 -07009132
9133 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009134 unlockEffectChains(effectChains);
9135 // Effect chains will be actually deleted here if they were removed from
9136 // mEffectChains list during mixing or effects processing
9137 }
9138
9139 threadLoop_exit();
9140
9141 if (!mStandby) {
9142 threadLoop_standby();
9143 mStandby = true;
9144 }
9145
Eric Laurent6acd1d42017-01-04 14:23:29 -08009146 ALOGV("Thread %p type %d exiting", this, mType);
9147 return false;
9148}
9149
9150// checkForNewParameter_l() must be called with ThreadBase::mLock held
9151bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9152 status_t& status)
9153{
9154 AudioParameter param = AudioParameter(keyValuePair);
9155 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009156 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009157 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009158 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009159 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009160 if (sendToHal) {
9161 status = mHalStream->setParameters(keyValuePair);
9162 } else {
9163 status = NO_ERROR;
9164 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009165
9166 return false;
9167}
9168
9169String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9170{
9171 Mutex::Autolock _l(mLock);
9172 String8 out_s8;
9173 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9174 return out_s8;
9175 }
9176 return String8();
9177}
9178
Eric Laurent09f1ed22019-04-24 17:45:17 -07009179void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9180 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009181 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9182
9183 desc->mIoHandle = mId;
9184
9185 switch (event) {
9186 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009187 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009188 case AUDIO_INPUT_CONFIG_CHANGED:
9189 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009190 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009191 case AUDIO_OUTPUT_CONFIG_CHANGED:
9192 desc->mPatch = mPatch;
9193 desc->mChannelMask = mChannelMask;
9194 desc->mSamplingRate = mSampleRate;
9195 desc->mFormat = mFormat;
9196 desc->mFrameCount = mFrameCount;
9197 desc->mFrameCountHAL = mFrameCount;
9198 desc->mLatency = 0;
9199 break;
9200
9201 case AUDIO_INPUT_CLOSED:
9202 case AUDIO_OUTPUT_CLOSED:
9203 default:
9204 break;
9205 }
9206 mAudioFlinger->ioConfigChanged(event, desc, pid);
9207}
9208
9209status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9210 audio_patch_handle_t *handle)
9211{
9212 status_t status = NO_ERROR;
9213
9214 // store new device and send to effects
9215 audio_devices_t type = AUDIO_DEVICE_NONE;
9216 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009217 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9218 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9219 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009220 if (isOutput()) {
9221 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009222 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9223 && !mAudioHwDev->supportsAudioPatches(),
9224 "Enumerated device type(%#x) must not be used "
9225 "as it does not support audio patches",
9226 patch->sinks[i].ext.device.type);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009227 type |= patch->sinks[i].ext.device.type;
jiabinc52b1ff2019-10-31 17:20:42 -07009228 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9229 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009230 }
9231 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009232 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009233 } else {
9234 type = patch->sources[0].ext.device.type;
9235 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009236 numDevices = mPatch.num_sources;
9237 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009238 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009239 }
9240
9241 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009242 if (isOutput()) {
9243 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9244 } else {
9245 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9246 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009247 }
9248
jiabinc52b1ff2019-10-31 17:20:42 -07009249 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009250 // store new source and send to effects
9251 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9252 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9253 for (size_t i = 0; i < mEffectChains.size(); i++) {
9254 mEffectChains[i]->setAudioSource_l(mAudioSource);
9255 }
9256 }
9257 }
9258
9259 if (mAudioHwDev->supportsAudioPatches()) {
9260 status = mHalDevice->createAudioPatch(patch->num_sources,
9261 patch->sources,
9262 patch->num_sinks,
9263 patch->sinks,
9264 handle);
9265 } else {
9266 char *address;
9267 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9268 //FIXME: we only support address on first sink with HAL version < 3.0
9269 address = audio_device_address_to_parameter(
9270 patch->sinks[0].ext.device.type,
9271 patch->sinks[0].ext.device.address);
9272 } else {
9273 address = (char *)calloc(1, 1);
9274 }
9275 AudioParameter param = AudioParameter(String8(address));
9276 free(address);
9277 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9278 if (!isOutput()) {
9279 param.addInt(String8(AudioParameter::keyInputSource),
9280 (int)patch->sinks[0].ext.mix.usecase.source);
9281 }
9282 status = mHalStream->setParameters(param.toString());
9283 *handle = AUDIO_PATCH_HANDLE_NONE;
9284 }
9285
jiabinc52b1ff2019-10-31 17:20:42 -07009286 if (numDevices == 0 || mDeviceId != deviceId) {
9287 if (isOutput()) {
9288 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9289 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009290 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009291 } else {
9292 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9293 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9294 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009295 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009296 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009297 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009298 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009299 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009300 }
jiabinc52b1ff2019-10-31 17:20:42 -07009301 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009302 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009303 }
9304 return status;
9305}
9306
9307status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9308{
9309 status_t status = NO_ERROR;
9310
jiabinc52b1ff2019-10-31 17:20:42 -07009311 mPatch = audio_patch{};
9312 mOutDeviceTypeAddrs.clear();
9313 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009314
9315 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9316 supportsAudioPatches : false;
9317
9318 if (supportsAudioPatches) {
9319 status = mHalDevice->releaseAudioPatch(handle);
9320 } else {
9321 AudioParameter param;
9322 param.addInt(String8(AudioParameter::keyRouting), 0);
9323 status = mHalStream->setParameters(param.toString());
9324 }
9325 return status;
9326}
9327
Mikhail Naganovdc769682018-05-04 15:34:08 -07009328void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009329{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009330 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009331 if (isOutput()) {
9332 config->role = AUDIO_PORT_ROLE_SOURCE;
9333 config->ext.mix.hw_module = mAudioHwDev->handle();
9334 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9335 } else {
9336 config->role = AUDIO_PORT_ROLE_SINK;
9337 config->ext.mix.hw_module = mAudioHwDev->handle();
9338 config->ext.mix.usecase.source = mAudioSource;
9339 }
9340}
9341
9342status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9343{
9344 audio_session_t session = chain->sessionId();
9345
9346 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9347 // Attach all tracks with same session ID to this chain.
9348 // indicate all active tracks in the chain
9349 for (const sp<MmapTrack> &track : mActiveTracks) {
9350 if (session == track->sessionId()) {
9351 chain->incTrackCnt();
9352 chain->incActiveTrackCnt();
9353 }
9354 }
9355
9356 chain->setThread(this);
9357 chain->setInBuffer(nullptr);
9358 chain->setOutBuffer(nullptr);
9359 chain->syncHalEffectsState();
9360
9361 mEffectChains.add(chain);
9362 checkSuspendOnAddEffectChain_l(chain);
9363 return NO_ERROR;
9364}
9365
9366size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9367{
9368 audio_session_t session = chain->sessionId();
9369
9370 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9371
9372 for (size_t i = 0; i < mEffectChains.size(); i++) {
9373 if (chain == mEffectChains[i]) {
9374 mEffectChains.removeAt(i);
9375 // detach all active tracks from the chain
9376 // detach all tracks with same session ID from this chain
9377 for (const sp<MmapTrack> &track : mActiveTracks) {
9378 if (session == track->sessionId()) {
9379 chain->decActiveTrackCnt();
9380 chain->decTrackCnt();
9381 }
9382 }
9383 break;
9384 }
9385 }
9386 return mEffectChains.size();
9387}
9388
Eric Laurent6acd1d42017-01-04 14:23:29 -08009389void AudioFlinger::MmapThread::threadLoop_standby()
9390{
9391 mHalStream->standby();
9392}
9393
9394void AudioFlinger::MmapThread::threadLoop_exit()
9395{
Phil Burk7dce7282017-09-27 13:51:41 -07009396 // Do not call callback->onTearDown() because it is redundant for thread exit
9397 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009398}
9399
9400status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9401{
9402 return BAD_VALUE;
9403}
9404
9405bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9406{
9407 return false;
9408}
9409
9410status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9411 const effect_descriptor_t *desc, audio_session_t sessionId)
9412{
9413 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009414 if (audio_is_global_session(sessionId)) {
9415 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009416 desc->name, mThreadName);
9417 return BAD_VALUE;
9418 }
9419
9420 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9421 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9422 desc->name);
9423 return BAD_VALUE;
9424 }
9425 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009426 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9427 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009428 return BAD_VALUE;
9429 }
9430
9431 // Only allow effects without processing load or latency
9432 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9433 return BAD_VALUE;
9434 }
9435
jiabineb3bda02020-06-30 14:07:03 -07009436 if (EffectModule::isHapticGenerator(&desc->type)) {
9437 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9438 return BAD_VALUE;
9439 }
9440
Eric Laurent6acd1d42017-01-04 14:23:29 -08009441 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009442}
9443
9444void AudioFlinger::MmapThread::checkInvalidTracks_l()
9445{
9446 for (const sp<MmapTrack> &track : mActiveTracks) {
9447 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009448 sp<MmapStreamCallback> callback = mCallback.promote();
9449 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009450 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009451 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009452 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009453 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9454 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9455 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009456 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009457 }
9458 }
9459}
9460
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009461void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009462{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009463 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9464 mAttr.content_type, mAttr.usage, mAttr.source);
9465 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009466 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009467 dprintf(fd, " No active clients\n");
9468 }
9469}
9470
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009471void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009472{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009473 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009474 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009475 dprintf(fd, " %zu Tracks\n", numtracks);
9476 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009477 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009478 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009479 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009480 for (size_t i = 0; i < numtracks ; ++i) {
9481 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009482 result.append(prefix);
9483 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009484 }
9485 } else {
9486 dprintf(fd, "\n");
9487 }
9488 write(fd, result.string(), result.size());
9489}
9490
9491AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9492 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009493 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009494 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009495 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009496 mStreamVolume(1.0),
9497 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009498 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009499{
9500 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9501 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9502 mMasterVolume = audioFlinger->masterVolume_l();
9503 mMasterMute = audioFlinger->masterMute_l();
9504 if (mAudioHwDev) {
9505 if (mAudioHwDev->canSetMasterVolume()) {
9506 mMasterVolume = 1.0;
9507 }
9508
9509 if (mAudioHwDev->canSetMasterMute()) {
9510 mMasterMute = false;
9511 }
9512 }
9513}
9514
9515void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9516 audio_stream_type_t streamType,
9517 audio_session_t sessionId,
9518 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009519 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009520 audio_port_handle_t portId)
9521{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009522 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009523 mStreamType = streamType;
9524}
9525
9526AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9527{
9528 Mutex::Autolock _l(mLock);
9529 AudioStreamOut *output = mOutput;
9530 mOutput = NULL;
9531 return output;
9532}
9533
9534void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9535{
9536 Mutex::Autolock _l(mLock);
9537 // Don't apply master volume in SW if our HAL can do it for us.
9538 if (mAudioHwDev &&
9539 mAudioHwDev->canSetMasterVolume()) {
9540 mMasterVolume = 1.0;
9541 } else {
9542 mMasterVolume = value;
9543 }
9544}
9545
9546void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9547{
9548 Mutex::Autolock _l(mLock);
9549 // Don't apply master mute in SW if our HAL can do it for us.
9550 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9551 mMasterMute = false;
9552 } else {
9553 mMasterMute = muted;
9554 }
9555}
9556
9557void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9558{
9559 Mutex::Autolock _l(mLock);
9560 if (stream == mStreamType) {
9561 mStreamVolume = value;
9562 broadcast_l();
9563 }
9564}
9565
9566float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9567{
9568 Mutex::Autolock _l(mLock);
9569 if (stream == mStreamType) {
9570 return mStreamVolume;
9571 }
9572 return 0.0f;
9573}
9574
9575void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9576{
9577 Mutex::Autolock _l(mLock);
9578 if (stream == mStreamType) {
9579 mStreamMute= muted;
9580 broadcast_l();
9581 }
9582}
9583
9584void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9585{
9586 Mutex::Autolock _l(mLock);
9587 if (streamType == mStreamType) {
9588 for (const sp<MmapTrack> &track : mActiveTracks) {
9589 track->invalidate();
9590 }
9591 broadcast_l();
9592 }
9593}
9594
9595void AudioFlinger::MmapPlaybackThread::processVolume_l()
9596{
9597 float volume;
9598
9599 if (mMasterMute || mStreamMute) {
9600 volume = 0;
9601 } else {
9602 volume = mMasterVolume * mStreamVolume;
9603 }
9604
9605 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009606
9607 // Convert volumes from float to 8.24
9608 uint32_t vol = (uint32_t)(volume * (1 << 24));
9609
9610 // Delegate volume control to effect in track effect chain if needed
9611 // only one effect chain can be present on DirectOutputThread, so if
9612 // there is one, the track is connected to it
9613 if (!mEffectChains.isEmpty()) {
9614 mEffectChains[0]->setVolume_l(&vol, &vol);
9615 volume = (float)vol / (1 << 24);
9616 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009617 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009618 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9619 mHalVolFloat = volume; // HW volume control worked, so update value.
9620 mNoCallbackWarningCount = 0;
9621 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009622 sp<MmapStreamCallback> callback = mCallback.promote();
9623 if (callback != 0) {
9624 int channelCount;
9625 if (isOutput()) {
9626 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9627 } else {
9628 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9629 }
9630 Vector<float> values;
9631 for (int i = 0; i < channelCount; i++) {
9632 values.add(volume);
9633 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009634 mHalVolFloat = volume; // SW volume control worked, so update value.
9635 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009636 mLock.unlock();
9637 callback->onVolumeChanged(mChannelMask, values);
9638 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009639 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009640 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9641 ALOGW("Could not set MMAP stream volume: no volume callback!");
9642 mNoCallbackWarningCount++;
9643 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009644 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009645 }
9646 }
9647}
9648
Kevin Rocard069c2712018-03-29 19:09:14 -07009649void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9650{
9651 if (mOutput == nullptr || mOutput->stream == nullptr ||
9652 !mActiveTracks.readAndClearHasChanged()) {
9653 return;
9654 }
9655 StreamOutHalInterface::SourceMetadata metadata;
9656 for (const sp<MmapTrack> &track : mActiveTracks) {
9657 // No track is invalid as this is called after prepareTrack_l in the same critical section
9658 metadata.tracks.push_back({
9659 .usage = track->attributes().usage,
9660 .content_type = track->attributes().content_type,
9661 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9662 });
9663 }
9664 mOutput->stream->updateSourceMetadata(metadata);
9665}
9666
Eric Laurent6acd1d42017-01-04 14:23:29 -08009667void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9668{
9669 if (!mMasterMute) {
9670 char value[PROPERTY_VALUE_MAX];
9671 if (property_get("ro.audio.silent", value, "0") > 0) {
9672 char *endptr;
9673 unsigned long ul = strtoul(value, &endptr, 0);
9674 if (*endptr == '\0' && ul != 0) {
9675 ALOGD("Silence is golden");
9676 // The setprop command will not allow a property to be changed after
9677 // the first time it is set, so we don't have to worry about un-muting.
9678 setMasterMute_l(true);
9679 }
9680 }
9681 }
9682}
9683
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009684void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9685{
9686 MmapThread::toAudioPortConfig(config);
9687 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9688 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9689 config->flags.output = mOutput->flags;
9690 }
9691}
9692
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009693void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009694{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009695 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009696
Glenn Kastend3bb6452016-12-05 18:14:37 -08009697 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9698 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009699 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9700}
9701
9702AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9703 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009704 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009705 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009706 mInput(input)
9707{
9708 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9709 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9710}
9711
Eric Laurent331679c2018-04-16 17:03:16 -07009712status_t AudioFlinger::MmapCaptureThread::exitStandby()
9713{
Phil Burkf054fc32018-12-06 09:45:59 -08009714 {
9715 // mInput might have been cleared by clearInput()
9716 Mutex::Autolock _l(mLock);
9717 if (mInput != nullptr && mInput->stream != nullptr) {
9718 mInput->stream->setGain(1.0f);
9719 }
9720 }
Eric Laurent331679c2018-04-16 17:03:16 -07009721 return MmapThread::exitStandby();
9722}
9723
Eric Laurent6acd1d42017-01-04 14:23:29 -08009724AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9725{
9726 Mutex::Autolock _l(mLock);
9727 AudioStreamIn *input = mInput;
9728 mInput = NULL;
9729 return input;
9730}
Kevin Rocard069c2712018-03-29 19:09:14 -07009731
Eric Laurent331679c2018-04-16 17:03:16 -07009732
9733void AudioFlinger::MmapCaptureThread::processVolume_l()
9734{
9735 bool changed = false;
9736 bool silenced = false;
9737
9738 sp<MmapStreamCallback> callback = mCallback.promote();
9739 if (callback == 0) {
9740 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9741 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9742 mNoCallbackWarningCount++;
9743 }
9744 }
9745
9746 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9747 // track is silenced and unmute otherwise
9748 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9749 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9750 changed = true;
9751 silenced = mActiveTracks[i]->isSilenced_l();
9752 }
9753 }
9754
9755 if (changed) {
9756 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9757 }
9758}
9759
Kevin Rocard069c2712018-03-29 19:09:14 -07009760void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9761{
9762 if (mInput == nullptr || mInput->stream == nullptr ||
9763 !mActiveTracks.readAndClearHasChanged()) {
9764 return;
9765 }
9766 StreamInHalInterface::SinkMetadata metadata;
9767 for (const sp<MmapTrack> &track : mActiveTracks) {
9768 // No track is invalid as this is called after prepareTrack_l in the same critical section
9769 metadata.tracks.push_back({
9770 .source = track->attributes().source,
9771 .gain = 1, // capture tracks do not have volumes
9772 });
9773 }
9774 mInput->stream->updateSinkMetadata(metadata);
9775}
9776
Eric Laurent5ada82e2019-08-29 17:53:54 -07009777void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -07009778{
9779 Mutex::Autolock _l(mLock);
9780 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07009781 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -07009782 mActiveTracks[i]->setSilenced_l(silenced);
9783 broadcast_l();
9784 }
9785 }
9786}
9787
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009788void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9789{
9790 MmapThread::toAudioPortConfig(config);
9791 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9792 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9793 config->flags.input = mInput->flags;
9794 }
9795}
9796
Glenn Kasten63238ef2015-03-02 15:50:29 -08009797} // namespace android