blob: 9e4f1a29efdc8a748c38448f8690eaa1ac6aaa91 [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>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080032#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070033#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080035#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036
37#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070038#include <private/android_filesystem_config.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070043#include <system/audio_effects/effect_ns.h>
44#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046
47// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070048#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <media/nbaio/AudioStreamOutSink.h>
50#include <media/nbaio/MonoPipe.h>
51#include <media/nbaio/MonoPipeReader.h>
52#include <media/nbaio/Pipe.h>
53#include <media/nbaio/PipeReader.h>
54#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080055#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57#include <powermanager/PowerManager.h>
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
Glenn Kastenc05b8d72016-03-24 09:48:17 -070075#include "AutoPark.h"
76
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080077#include <pthread.h>
78#include "TypedLogger.h"
79
Eric Laurent81784c32012-11-19 14:55:58 -080080// ----------------------------------------------------------------------------
81
82// Note: the following macro is used for extremely verbose logging message. In
83// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
84// 0; but one side effect of this is to turn all LOGV's as well. Some messages
85// are so verbose that we want to suppress them even when we have ALOG_ASSERT
86// turned on. Do not uncomment the #def below unless you really know what you
87// are doing and want to see all of the extremely verbose messages.
88//#define VERY_VERY_VERBOSE_LOGGING
89#ifdef VERY_VERY_VERBOSE_LOGGING
90#define ALOGVV ALOGV
91#else
92#define ALOGVV(a...) do { } while(0)
93#endif
94
Andy Hung6770c6f2015-04-07 13:43:36 -070095// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070097template <typename T>
98static inline T min(const T& a, const T& b)
99{
100 return a < b ? a : b;
101}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700102
Andy Hungd330ee42015-04-20 13:23:41 -0700103#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700104#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700105#endif
106
Eric Laurent81784c32012-11-19 14:55:58 -0800107namespace android {
108
109// retry counts for buffer fill timeout
110// 50 * ~20msecs = 1 second
111static const int8_t kMaxTrackRetries = 50;
112static const int8_t kMaxTrackStartupRetries = 50;
113// allow less retry attempts on direct output thread.
114// direct outputs can be a scarce resource in audio hardware and should
115// be released as quickly as possible.
116static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700117
Eric Laurent51716182016-02-29 18:00:56 -0800118
Eric Laurent81784c32012-11-19 14:55:58 -0800119
120// don't warn about blocked writes or record buffer overflows more often than this
121static const nsecs_t kWarningThrottleNs = seconds(5);
122
123// RecordThread loop sleep time upon application overrun or audio HAL read error
124static const int kRecordThreadSleepUs = 5000;
125
Eric Laurent10351942014-05-08 18:49:52 -0700126// maximum time to wait in sendConfigEvent_l() for a status to be received
127static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800128
129// minimum sleep time for the mixer thread loop when tracks are active but in underrun
130static const uint32_t kMinThreadSleepTimeUs = 5000;
131// maximum divider applied to the active sleep time in the mixer thread loop
132static const uint32_t kMaxThreadSleepTimeShift = 2;
133
Andy Hung09a50072014-02-27 14:30:47 -0800134// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700135// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800136static const uint32_t kMinNormalSinkBufferSizeMs = 20;
137// maximum normal sink buffer size
138static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800139
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700140// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
141// FIXME This should be based on experimentally observed scheduling jitter
142static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
143
Eric Laurent972a1732013-09-04 09:42:59 -0700144// Offloaded output thread standby delay: allows track transition without going to standby
145static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
146
Eric Laurent51716182016-02-29 18:00:56 -0800147// Direct output thread minimum sleep time in idle or active(underrun) state
148static const nsecs_t kDirectMinSleepTimeUs = 10000;
149
Glenn Kasten1b291842016-07-18 14:55:21 -0700150// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
151// balance between power consumption and latency, and allows threads to be scheduled reliably
152// by the CFS scheduler.
153// FIXME Express other hardcoded references to 20ms with references to this constant and move
154// it appropriately.
155#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800156
Eric Laurent81784c32012-11-19 14:55:58 -0800157// Whether to use fast mixer
158static const enum {
159 FastMixer_Never, // never initialize or use: for debugging only
160 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
161 // normal mixer multiplier is 1
162 FastMixer_Static, // initialize if needed, then use all the time if initialized,
163 // multiplier is calculated based on min & max normal mixer buffer size
164 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
165 // multiplier is calculated based on min & max normal mixer buffer size
166 // FIXME for FastMixer_Dynamic:
167 // Supporting this option will require fixing HALs that can't handle large writes.
168 // For example, one HAL implementation returns an error from a large write,
169 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
170 // We could either fix the HAL implementations, or provide a wrapper that breaks
171 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
172} kUseFastMixer = FastMixer_Static;
173
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700174// Whether to use fast capture
175static const enum {
176 FastCapture_Never, // never initialize or use: for debugging only
177 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
178 FastCapture_Static, // initialize if needed, then use all the time if initialized
179} kUseFastCapture = FastCapture_Static;
180
Eric Laurent81784c32012-11-19 14:55:58 -0800181// Priorities for requestPriority
182static const int kPriorityAudioApp = 2;
183static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700184static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800185
Glenn Kastenea38ee72016-04-18 11:08:01 -0700186// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
187// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
188// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700189
190// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800191static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800192
Glenn Kasten03490092014-05-27 12:30:54 -0700193// The minimum and maximum allowed values
194static const int kFastTrackMultiplierMin = 1;
195static const int kFastTrackMultiplierMax = 2;
196
197// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
198static int sFastTrackMultiplier = kFastTrackMultiplier;
199
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700200// See Thread::readOnlyHeap().
201// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
202// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
203// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700204static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700205
Eric Laurent81784c32012-11-19 14:55:58 -0800206// ----------------------------------------------------------------------------
207
Glenn Kasten03490092014-05-27 12:30:54 -0700208static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
209
210static void sFastTrackMultiplierInit()
211{
212 char value[PROPERTY_VALUE_MAX];
213 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
214 char *endptr;
215 unsigned long ul = strtoul(value, &endptr, 0);
216 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
217 sFastTrackMultiplier = (int) ul;
218 }
219 }
220}
221
222// ----------------------------------------------------------------------------
223
Eric Laurent81784c32012-11-19 14:55:58 -0800224#ifdef ADD_BATTERY_DATA
225// To collect the amplifier usage
226static void addBatteryData(uint32_t params) {
227 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
228 if (service == NULL) {
229 // it already logged
230 return;
231 }
232
233 service->addBatteryData(params);
234}
235#endif
236
Andy Hung3f0c9022016-01-15 17:49:46 -0800237// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
238struct {
239 // call when you acquire a partial wakelock
240 void acquire(const sp<IBinder> &wakeLockToken) {
241 pthread_mutex_lock(&mLock);
242 if (wakeLockToken.get() == nullptr) {
243 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
244 } else {
245 if (mCount == 0) {
246 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
247 }
248 ++mCount;
249 }
250 pthread_mutex_unlock(&mLock);
251 }
252
253 // call when you release a partial wakelock.
254 void release(const sp<IBinder> &wakeLockToken) {
255 if (wakeLockToken.get() == nullptr) {
256 return;
257 }
258 pthread_mutex_lock(&mLock);
259 if (--mCount < 0) {
260 ALOGE("negative wakelock count");
261 mCount = 0;
262 }
263 pthread_mutex_unlock(&mLock);
264 }
265
266 // retrieves the boottime timebase offset from monotonic.
267 int64_t getBoottimeOffset() {
268 pthread_mutex_lock(&mLock);
269 int64_t boottimeOffset = mBoottimeOffset;
270 pthread_mutex_unlock(&mLock);
271 return boottimeOffset;
272 }
273
274 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
275 // and the selected timebase.
276 // Currently only TIMEBASE_BOOTTIME is allowed.
277 //
278 // This only needs to be called upon acquiring the first partial wakelock
279 // after all other partial wakelocks are released.
280 //
281 // We do an empirical measurement of the offset rather than parsing
282 // /proc/timer_list since the latter is not a formal kernel ABI.
283 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
284 int clockbase;
285 switch (timebase) {
286 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
287 clockbase = SYSTEM_TIME_BOOTTIME;
288 break;
289 default:
290 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
291 break;
292 }
293 // try three times to get the clock offset, choose the one
294 // with the minimum gap in measurements.
295 const int tries = 3;
296 nsecs_t bestGap, measured;
297 for (int i = 0; i < tries; ++i) {
298 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
299 const nsecs_t tbase = systemTime(clockbase);
300 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
301 const nsecs_t gap = tmono2 - tmono;
302 if (i == 0 || gap < bestGap) {
303 bestGap = gap;
304 measured = tbase - ((tmono + tmono2) >> 1);
305 }
306 }
307
308 // to avoid micro-adjusting, we don't change the timebase
309 // unless it is significantly different.
310 //
311 // Assumption: It probably takes more than toleranceNs to
312 // suspend and resume the device.
313 static int64_t toleranceNs = 10000; // 10 us
314 if (llabs(*offset - measured) > toleranceNs) {
315 ALOGV("Adjusting timebase offset old: %lld new: %lld",
316 (long long)*offset, (long long)measured);
317 *offset = measured;
318 }
319 }
320
321 pthread_mutex_t mLock;
322 int32_t mCount;
323 int64_t mBoottimeOffset;
324} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800325
326// ----------------------------------------------------------------------------
327// CPU Stats
328// ----------------------------------------------------------------------------
329
330class CpuStats {
331public:
332 CpuStats();
333 void sample(const String8 &title);
334#ifdef DEBUG_CPU_USAGE
335private:
336 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
337 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
338
339 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
340
341 int mCpuNum; // thread's current CPU number
342 int mCpukHz; // frequency of thread's current CPU in kHz
343#endif
344};
345
346CpuStats::CpuStats()
347#ifdef DEBUG_CPU_USAGE
348 : mCpuNum(-1), mCpukHz(-1)
349#endif
350{
351}
352
Glenn Kasten0f11b512014-01-31 16:18:54 -0800353void CpuStats::sample(const String8 &title
354#ifndef DEBUG_CPU_USAGE
355 __unused
356#endif
357 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800358#ifdef DEBUG_CPU_USAGE
359 // get current thread's delta CPU time in wall clock ns
360 double wcNs;
361 bool valid = mCpuUsage.sampleAndEnable(wcNs);
362
363 // record sample for wall clock statistics
364 if (valid) {
365 mWcStats.sample(wcNs);
366 }
367
368 // get the current CPU number
369 int cpuNum = sched_getcpu();
370
371 // get the current CPU frequency in kHz
372 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
373
374 // check if either CPU number or frequency changed
375 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
376 mCpuNum = cpuNum;
377 mCpukHz = cpukHz;
378 // ignore sample for purposes of cycles
379 valid = false;
380 }
381
382 // if no change in CPU number or frequency, then record sample for cycle statistics
383 if (valid && mCpukHz > 0) {
384 double cycles = wcNs * cpukHz * 0.000001;
385 mHzStats.sample(cycles);
386 }
387
388 unsigned n = mWcStats.n();
389 // mCpuUsage.elapsed() is expensive, so don't call it every loop
390 if ((n & 127) == 1) {
391 long long elapsed = mCpuUsage.elapsed();
392 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
393 double perLoop = elapsed / (double) n;
394 double perLoop100 = perLoop * 0.01;
395 double perLoop1k = perLoop * 0.001;
396 double mean = mWcStats.mean();
397 double stddev = mWcStats.stddev();
398 double minimum = mWcStats.minimum();
399 double maximum = mWcStats.maximum();
400 double meanCycles = mHzStats.mean();
401 double stddevCycles = mHzStats.stddev();
402 double minCycles = mHzStats.minimum();
403 double maxCycles = mHzStats.maximum();
404 mCpuUsage.resetElapsed();
405 mWcStats.reset();
406 mHzStats.reset();
407 ALOGD("CPU usage for %s over past %.1f secs\n"
408 " (%u mixer loops at %.1f mean ms per loop):\n"
409 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
410 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
411 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
412 title.string(),
413 elapsed * .000000001, n, perLoop * .000001,
414 mean * .001,
415 stddev * .001,
416 minimum * .001,
417 maximum * .001,
418 mean / perLoop100,
419 stddev / perLoop100,
420 minimum / perLoop100,
421 maximum / perLoop100,
422 meanCycles / perLoop1k,
423 stddevCycles / perLoop1k,
424 minCycles / perLoop1k,
425 maxCycles / perLoop1k);
426
427 }
428 }
429#endif
430};
431
432// ----------------------------------------------------------------------------
433// ThreadBase
434// ----------------------------------------------------------------------------
435
Glenn Kasten97b7b752014-09-28 13:04:24 -0700436// static
437const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
438{
439 switch (type) {
440 case MIXER:
441 return "MIXER";
442 case DIRECT:
443 return "DIRECT";
444 case DUPLICATING:
445 return "DUPLICATING";
446 case RECORD:
447 return "RECORD";
448 case OFFLOAD:
449 return "OFFLOAD";
450 default:
451 return "unknown";
452 }
453}
454
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700461 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800462 }
463 return result;
464}
465
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800467{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700468 std::string result;
469 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800470 return result;
471}
472
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700474{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700475 std::string result;
476 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477 return result;
478}
479
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800480const char *sourceToString(audio_source_t source)
481{
482 switch (source) {
483 case AUDIO_SOURCE_DEFAULT: return "default";
484 case AUDIO_SOURCE_MIC: return "mic";
485 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
486 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
487 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
488 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
489 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
490 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
491 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800492 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800493 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
494 case AUDIO_SOURCE_HOTWORD: return "hotword";
495 default: return "unknown";
496 }
497}
498
Eric Laurent81784c32012-11-19 14:55:58 -0800499AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700500 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800501 : Thread(false /*canCallJava*/),
502 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700503 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700504 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800505 // are set by PlaybackThread::readOutputParameters_l() or
506 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700507 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800508 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700509 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
510 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{
Eric Laurent296fb132015-05-01 11:38:42 -0700516 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800517}
518
519AudioFlinger::ThreadBase::~ThreadBase()
520{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700521 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700522 mConfigEvents.clear();
523
Eric Laurent81784c32012-11-19 14:55:58 -0800524 // do not lock the mutex in destructor
525 releaseWakeLock_l();
526 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800527 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800528 binder->unlinkToDeath(mDeathRecipient);
529 }
530}
531
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700532status_t AudioFlinger::ThreadBase::readyToRun()
533{
534 status_t status = initCheck();
535 if (status == NO_ERROR) {
536 ALOGI("AudioFlinger's thread %p ready to run", this);
537 } else {
538 ALOGE("No working audio driver found.");
539 }
540 return status;
541}
542
Eric Laurent81784c32012-11-19 14:55:58 -0800543void AudioFlinger::ThreadBase::exit()
544{
545 ALOGV("ThreadBase::exit");
546 // do any cleanup required for exit to succeed
547 preExit();
548 {
549 // This lock prevents the following race in thread (uniprocessor for illustration):
550 // if (!exitPending()) {
551 // // context switch from here to exit()
552 // // exit() calls requestExit(), what exitPending() observes
553 // // exit() calls signal(), which is dropped since no waiters
554 // // context switch back from exit() to here
555 // mWaitWorkCV.wait(...);
556 // // now thread is hung
557 // }
558 AutoMutex lock(mLock);
559 requestExit();
560 mWaitWorkCV.broadcast();
561 }
562 // When Thread::requestExitAndWait is made virtual and this method is renamed to
563 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
564 requestExitAndWait();
565}
566
567status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
568{
Eric Laurent81784c32012-11-19 14:55:58 -0800569 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
570 Mutex::Autolock _l(mLock);
571
Eric Laurent10351942014-05-08 18:49:52 -0700572 return sendSetParameterConfigEvent_l(keyValuePairs);
573}
574
575// sendConfigEvent_l() must be called with ThreadBase::mLock held
576// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
577status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
578{
579 status_t status = NO_ERROR;
580
Eric Laurent72e3f392015-05-20 14:43:50 -0700581 if (event->mRequiresSystemReady && !mSystemReady) {
582 event->mWaitStatus = false;
583 mPendingConfigEvents.add(event);
584 return status;
585 }
Eric Laurent10351942014-05-08 18:49:52 -0700586 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700587 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800588 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700589 mLock.unlock();
590 {
591 Mutex::Autolock _l(event->mLock);
592 while (event->mWaitStatus) {
593 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
594 event->mStatus = TIMED_OUT;
595 event->mWaitStatus = false;
596 }
597 }
598 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800599 }
Eric Laurent10351942014-05-08 18:49:52 -0700600 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800601 return status;
602}
603
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700604void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800605{
606 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700607 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800608}
609
610// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800612{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700613 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700614 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800615}
616
Mikhail Naganov83f04272017-02-07 10:45:09 -0800617void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700618{
619 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800620 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700621}
622
Eric Laurent81784c32012-11-19 14:55:58 -0800623// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800624void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
625 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800626{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800627 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700628 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800629}
630
Eric Laurent10351942014-05-08 18:49:52 -0700631// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
632status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800633{
Andy Hung2ddee192015-12-18 17:34:44 -0800634 sp<ConfigEvent> configEvent;
635 AudioParameter param(keyValuePair);
636 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700637 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800638 setMasterMono_l(value != 0);
639 if (param.size() == 1) {
640 return NO_ERROR; // should be a solo parameter - we don't pass down
641 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700642 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800643 configEvent = new SetParameterConfigEvent(param.toString());
644 } else {
645 configEvent = new SetParameterConfigEvent(keyValuePair);
646 }
Eric Laurent10351942014-05-08 18:49:52 -0700647 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700648}
649
Eric Laurent1c333e22014-05-20 10:48:17 -0700650status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
651 const struct audio_patch *patch,
652 audio_patch_handle_t *handle)
653{
654 Mutex::Autolock _l(mLock);
655 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
656 status_t status = sendConfigEvent_l(configEvent);
657 if (status == NO_ERROR) {
658 CreateAudioPatchConfigEventData *data =
659 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
660 *handle = data->mHandle;
661 }
662 return status;
663}
664
665status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
666 const audio_patch_handle_t handle)
667{
668 Mutex::Autolock _l(mLock);
669 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
670 return sendConfigEvent_l(configEvent);
671}
672
673
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700674// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700675void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700676{
Eric Laurent10351942014-05-08 18:49:52 -0700677 bool configChanged = false;
678
Eric Laurent81784c32012-11-19 14:55:58 -0800679 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700680 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700681 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800682 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700683 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700684 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700685 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
686 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800687 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700688 true /*asynchronous*/);
689 if (err != 0) {
690 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700691 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700692 }
693 } break;
694 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700695 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700696 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700697 } break;
698 case CFG_EVENT_SET_PARAMETER: {
699 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
700 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
701 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700702 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700704 case CFG_EVENT_CREATE_AUDIO_PATCH: {
705 CreateAudioPatchConfigEventData *data =
706 (CreateAudioPatchConfigEventData *)event->mData.get();
707 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
708 } break;
709 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
710 ReleaseAudioPatchConfigEventData *data =
711 (ReleaseAudioPatchConfigEventData *)event->mData.get();
712 event->mStatus = releaseAudioPatch_l(data->mHandle);
713 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700714 default:
Eric Laurent10351942014-05-08 18:49:52 -0700715 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700716 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800717 }
Eric Laurent10351942014-05-08 18:49:52 -0700718 {
719 Mutex::Autolock _l(event->mLock);
720 if (event->mWaitStatus) {
721 event->mWaitStatus = false;
722 event->mCond.signal();
723 }
724 }
725 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
726 }
727
728 if (configChanged) {
729 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800730 }
Eric Laurent81784c32012-11-19 14:55:58 -0800731}
732
Marco Nelissenb2208842014-02-07 14:00:50 -0800733String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
734 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700735 const audio_channel_representation_t representation =
736 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700737
738 switch (representation) {
739 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
740 if (output) {
741 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
742 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
743 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
744 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
745 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
746 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
747 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
748 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
749 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
750 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
751 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
753 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
754 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
755 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
756 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
757 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
758 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
759 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
760 } else {
761 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
762 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
763 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
764 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
765 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
766 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
767 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
768 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
769 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
770 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
771 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
772 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
773 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
774 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
775 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
776 }
777 const int len = s.length();
778 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700779 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700780 s.unlockBuffer(len - 2); // remove trailing ", "
781 }
782 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800783 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700784 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
785 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
786 return s;
787 default:
788 s.appendFormat("unknown mask, representation:%d bits:%#x",
789 representation, audio_channel_mask_get_bits(mask));
790 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800791 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800792}
793
Glenn Kasten0f11b512014-01-31 16:18:54 -0800794void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800795{
796 const size_t SIZE = 256;
797 char buffer[SIZE];
798 String8 result;
799
800 bool locked = AudioFlinger::dumpTryLock(mLock);
801 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700802 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800803 }
804
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800805 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700806 dprintf(fd, " I/O handle: %d\n", mId);
807 dprintf(fd, " TID: %d\n", getTid());
808 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700809 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700810 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700811 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700812 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700813 dprintf(fd, " Channel count: %u\n", mChannelCount);
814 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800815 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700816 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700817 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800819 size_t numConfig = mConfigEvents.size();
820 if (numConfig) {
821 for (size_t i = 0; i < numConfig; i++) {
822 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800824 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700825 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800826 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700827 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800828 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700829 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
830 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800831 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800832
833 if (locked) {
834 mLock.unlock();
835 }
836}
837
838void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
839{
840 const size_t SIZE = 256;
841 char buffer[SIZE];
842 String8 result;
843
Marco Nelissenb2208842014-02-07 14:00:50 -0800844 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000845 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800846 write(fd, buffer, strlen(buffer));
847
Marco Nelissenb2208842014-02-07 14:00:50 -0800848 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800849 sp<EffectChain> chain = mEffectChains[i];
850 if (chain != 0) {
851 chain->dump(fd, args);
852 }
853 }
854}
855
Andy Hungdae27702016-10-31 14:01:16 -0700856void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800857{
858 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700859 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800860}
861
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100862String16 AudioFlinger::ThreadBase::getWakeLockTag()
863{
864 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800865 case MIXER:
866 return String16("AudioMix");
867 case DIRECT:
868 return String16("AudioDirectOut");
869 case DUPLICATING:
870 return String16("AudioDup");
871 case RECORD:
872 return String16("AudioIn");
873 case OFFLOAD:
874 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800875 case MMAP:
876 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800877 default:
878 ALOG_ASSERT(false);
879 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100880 }
881}
882
Andy Hungdae27702016-10-31 14:01:16 -0700883void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800884{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800885 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800886 if (mPowerManager != 0) {
887 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700888 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
889 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700890 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100891 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700892 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700893 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800894 if (status == NO_ERROR) {
895 mWakeLockToken = binder;
896 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800897 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800898 }
Wei Jia3f273d12015-11-24 09:06:49 -0800899
Andy Hung3f0c9022016-01-15 17:49:46 -0800900 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800901 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
902 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800903}
904
905void AudioFlinger::ThreadBase::releaseWakeLock()
906{
907 Mutex::Autolock _l(mLock);
908 releaseWakeLock_l();
909}
910
911void AudioFlinger::ThreadBase::releaseWakeLock_l()
912{
Andy Hung3f0c9022016-01-15 17:49:46 -0800913 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800914 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800915 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800916 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700917 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
918 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800919 }
920 mWakeLockToken.clear();
921 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800922}
923
924void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700925 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800926 // use checkService() to avoid blocking if power service is not up yet
927 sp<IBinder> binder =
928 defaultServiceManager()->checkService(String16("power"));
929 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800930 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800931 } else {
932 mPowerManager = interface_cast<IPowerManager>(binder);
933 binder->linkToDeath(mDeathRecipient);
934 }
935 }
936}
937
Andy Hungd01b0f12016-11-07 16:10:30 -0800938void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800939 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700940
941#if !LOG_NDEBUG
942 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800943 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700944 s << uid << " ";
945 }
946 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
947#endif
948
Andy Hung438e7572015-12-14 15:51:17 -0800949 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
950 if (mSystemReady) {
951 ALOGE("no wake lock to update, but system ready!");
952 } else {
953 ALOGW("no wake lock to update, system not ready yet");
954 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800955 return;
956 }
957 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800958 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
959 status_t status = mPowerManager->updateWakeLockUids(
960 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
961 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800962 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800963 }
964}
965
Eric Laurent81784c32012-11-19 14:55:58 -0800966void AudioFlinger::ThreadBase::clearPowerManager()
967{
968 Mutex::Autolock _l(mLock);
969 releaseWakeLock_l();
970 mPowerManager.clear();
971}
972
Glenn Kasten0f11b512014-01-31 16:18:54 -0800973void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800974{
975 sp<ThreadBase> thread = mThread.promote();
976 if (thread != 0) {
977 thread->clearPowerManager();
978 }
979 ALOGW("power manager service died !!!");
980}
981
982void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800983 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800984{
985 Mutex::Autolock _l(mLock);
986 setEffectSuspended_l(type, suspend, sessionId);
987}
988
989void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800990 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800991{
992 sp<EffectChain> chain = getEffectChain_l(sessionId);
993 if (chain != 0) {
994 if (type != NULL) {
995 chain->setEffectSuspended_l(type, suspend);
996 } else {
997 chain->setEffectSuspendedAll_l(suspend);
998 }
999 }
1000
1001 updateSuspendedSessions_l(type, suspend, sessionId);
1002}
1003
1004void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1005{
1006 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1007 if (index < 0) {
1008 return;
1009 }
1010
1011 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1012 mSuspendedSessions.valueAt(index);
1013
1014 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001015 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001016 for (int j = 0; j < desc->mRefCount; j++) {
1017 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1018 chain->setEffectSuspendedAll_l(true);
1019 } else {
1020 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1021 desc->mType.timeLow);
1022 chain->setEffectSuspended_l(&desc->mType, true);
1023 }
1024 }
1025 }
1026}
1027
1028void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1029 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001030 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001031{
1032 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1033
1034 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1035
1036 if (suspend) {
1037 if (index >= 0) {
1038 sessionEffects = mSuspendedSessions.valueAt(index);
1039 } else {
1040 mSuspendedSessions.add(sessionId, sessionEffects);
1041 }
1042 } else {
1043 if (index < 0) {
1044 return;
1045 }
1046 sessionEffects = mSuspendedSessions.valueAt(index);
1047 }
1048
1049
1050 int key = EffectChain::kKeyForSuspendAll;
1051 if (type != NULL) {
1052 key = type->timeLow;
1053 }
1054 index = sessionEffects.indexOfKey(key);
1055
1056 sp<SuspendedSessionDesc> desc;
1057 if (suspend) {
1058 if (index >= 0) {
1059 desc = sessionEffects.valueAt(index);
1060 } else {
1061 desc = new SuspendedSessionDesc();
1062 if (type != NULL) {
1063 desc->mType = *type;
1064 }
1065 sessionEffects.add(key, desc);
1066 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1067 }
1068 desc->mRefCount++;
1069 } else {
1070 if (index < 0) {
1071 return;
1072 }
1073 desc = sessionEffects.valueAt(index);
1074 if (--desc->mRefCount == 0) {
1075 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1076 sessionEffects.removeItemsAt(index);
1077 if (sessionEffects.isEmpty()) {
1078 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1079 sessionId);
1080 mSuspendedSessions.removeItem(sessionId);
1081 }
1082 }
1083 }
1084 if (!sessionEffects.isEmpty()) {
1085 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1086 }
1087}
1088
1089void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1090 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001091 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001092{
1093 Mutex::Autolock _l(mLock);
1094 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1095}
1096
1097void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1098 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001099 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001100{
1101 if (mType != RECORD) {
1102 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1103 // another session. This gives the priority to well behaved effect control panels
1104 // and applications not using global effects.
1105 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1106 // global effects
1107 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1108 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1109 }
1110 }
1111
1112 sp<EffectChain> chain = getEffectChain_l(sessionId);
1113 if (chain != 0) {
1114 chain->checkSuspendOnEffectEnabled(effect, enabled);
1115 }
1116}
1117
Eric Laurent4c415062016-06-17 16:14:16 -07001118// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1119status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1120 const effect_descriptor_t *desc, audio_session_t sessionId)
1121{
1122 // No global effect sessions on record threads
1123 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1124 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1125 desc->name, mThreadName);
1126 return BAD_VALUE;
1127 }
1128 // only pre processing effects on record thread
1129 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1130 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1131 desc->name, mThreadName);
1132 return BAD_VALUE;
1133 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001134
1135 // always allow effects without processing load or latency
1136 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1137 return NO_ERROR;
1138 }
1139
Eric Laurent4c415062016-06-17 16:14:16 -07001140 audio_input_flags_t flags = mInput->flags;
1141 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1142 if (flags & AUDIO_INPUT_FLAG_RAW) {
1143 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1144 desc->name, mThreadName);
1145 return BAD_VALUE;
1146 }
1147 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1148 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1149 desc->name, mThreadName);
1150 return BAD_VALUE;
1151 }
1152 }
1153 return NO_ERROR;
1154}
1155
1156// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1157status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1158 const effect_descriptor_t *desc, audio_session_t sessionId)
1159{
1160 // no preprocessing on playback threads
1161 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1162 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1163 " thread %s", desc->name, mThreadName);
1164 return BAD_VALUE;
1165 }
1166
1167 switch (mType) {
1168 case MIXER: {
1169 // Reject any effect on mixer multichannel sinks.
1170 // TODO: fix both format and multichannel issues with effects.
1171 if (mChannelCount != FCC_2) {
1172 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1173 " thread %s", desc->name, mChannelCount, mThreadName);
1174 return BAD_VALUE;
1175 }
1176 audio_output_flags_t flags = mOutput->flags;
1177 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1178 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1179 // global effects are applied only to non fast tracks if they are SW
1180 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1181 break;
1182 }
1183 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1184 // only post processing on output stage session
1185 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1186 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1187 " on output stage session", desc->name);
1188 return BAD_VALUE;
1189 }
1190 } else {
1191 // no restriction on effects applied on non fast tracks
1192 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1193 break;
1194 }
1195 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001196
1197 // always allow effects without processing load or latency
1198 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1199 break;
1200 }
Eric Laurent4c415062016-06-17 16:14:16 -07001201 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1202 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1203 desc->name);
1204 return BAD_VALUE;
1205 }
1206 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1207 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1208 " in fast mode", desc->name);
1209 return BAD_VALUE;
1210 }
1211 }
1212 } break;
1213 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001214 // nothing actionable on offload threads, if the effect:
1215 // - is offloadable: the effect can be created
1216 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1217 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001218 break;
1219 case DIRECT:
1220 // Reject any effect on Direct output threads for now, since the format of
1221 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1222 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1223 desc->name, mThreadName);
1224 return BAD_VALUE;
1225 case DUPLICATING:
1226 // Reject any effect on mixer multichannel sinks.
1227 // TODO: fix both format and multichannel issues with effects.
1228 if (mChannelCount != FCC_2) {
1229 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1230 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1231 return BAD_VALUE;
1232 }
1233 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1234 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1235 " thread %s", desc->name, mThreadName);
1236 return BAD_VALUE;
1237 }
1238 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1239 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1240 " DUPLICATING thread %s", desc->name, mThreadName);
1241 return BAD_VALUE;
1242 }
1243 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1244 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1245 " DUPLICATING thread %s", desc->name, mThreadName);
1246 return BAD_VALUE;
1247 }
1248 break;
1249 default:
1250 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1251 }
1252
1253 return NO_ERROR;
1254}
1255
Eric Laurent81784c32012-11-19 14:55:58 -08001256// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1257sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1258 const sp<AudioFlinger::Client>& client,
1259 const sp<IEffectClient>& effectClient,
1260 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001261 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001262 effect_descriptor_t *desc,
1263 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001264 status_t *status,
1265 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001266{
1267 sp<EffectModule> effect;
1268 sp<EffectHandle> handle;
1269 status_t lStatus;
1270 sp<EffectChain> chain;
1271 bool chainCreated = false;
1272 bool effectCreated = false;
1273 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001274 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001275
1276 lStatus = initCheck();
1277 if (lStatus != NO_ERROR) {
1278 ALOGW("createEffect_l() Audio driver not initialized.");
1279 goto Exit;
1280 }
1281
Eric Laurent81784c32012-11-19 14:55:58 -08001282 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1283
1284 { // scope for mLock
1285 Mutex::Autolock _l(mLock);
1286
Eric Laurent4c415062016-06-17 16:14:16 -07001287 lStatus = checkEffectCompatibility_l(desc, sessionId);
1288 if (lStatus != NO_ERROR) {
1289 goto Exit;
1290 }
1291
Eric Laurent81784c32012-11-19 14:55:58 -08001292 // check for existing effect chain with the requested audio session
1293 chain = getEffectChain_l(sessionId);
1294 if (chain == 0) {
1295 // create a new chain for this session
1296 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1297 chain = new EffectChain(this, sessionId);
1298 addEffectChain_l(chain);
1299 chain->setStrategy(getStrategyForSession_l(sessionId));
1300 chainCreated = true;
1301 } else {
1302 effect = chain->getEffectFromDesc_l(desc);
1303 }
1304
1305 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1306
1307 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001308 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001309 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001310 lStatus = AudioSystem::registerEffect(
1311 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001312 if (lStatus != NO_ERROR) {
1313 goto Exit;
1314 }
1315 effectRegistered = true;
1316 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001317 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001318 if (lStatus != NO_ERROR) {
1319 goto Exit;
1320 }
1321 effectCreated = true;
1322
1323 effect->setDevice(mOutDevice);
1324 effect->setDevice(mInDevice);
1325 effect->setMode(mAudioFlinger->getMode());
1326 effect->setAudioSource(mAudioSource);
1327 }
1328 // create effect handle and connect it to effect module
1329 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001330 lStatus = handle->initCheck();
1331 if (lStatus == OK) {
1332 lStatus = effect->addHandle(handle.get());
1333 }
Eric Laurent81784c32012-11-19 14:55:58 -08001334 if (enabled != NULL) {
1335 *enabled = (int)effect->isEnabled();
1336 }
1337 }
1338
1339Exit:
1340 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1341 Mutex::Autolock _l(mLock);
1342 if (effectCreated) {
1343 chain->removeEffect_l(effect);
1344 }
1345 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001346 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001347 }
1348 if (chainCreated) {
1349 removeEffectChain_l(chain);
1350 }
1351 handle.clear();
1352 }
1353
Glenn Kasten9156ef32013-08-06 15:39:08 -07001354 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001355 return handle;
1356}
1357
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001358void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1359 bool unpinIfLast)
1360{
1361 bool remove = false;
1362 sp<EffectModule> effect;
1363 {
1364 Mutex::Autolock _l(mLock);
1365
1366 effect = handle->effect().promote();
1367 if (effect == 0) {
1368 return;
1369 }
1370 // restore suspended effects if the disconnected handle was enabled and the last one.
1371 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1372 if (remove) {
1373 removeEffect_l(effect, true);
1374 }
1375 }
1376 if (remove) {
1377 mAudioFlinger->updateOrphanEffectChains(effect);
1378 AudioSystem::unregisterEffect(effect->id());
1379 if (handle->enabled()) {
1380 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1381 }
1382 }
1383}
1384
Glenn Kastend848eb42016-03-08 13:42:11 -08001385sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1386 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001387{
1388 Mutex::Autolock _l(mLock);
1389 return getEffect_l(sessionId, effectId);
1390}
1391
Glenn Kastend848eb42016-03-08 13:42:11 -08001392sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1393 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001394{
1395 sp<EffectChain> chain = getEffectChain_l(sessionId);
1396 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1397}
1398
1399// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1400// PlaybackThread::mLock held
1401status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1402{
1403 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001404 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001405 sp<EffectChain> chain = getEffectChain_l(sessionId);
1406 bool chainCreated = false;
1407
Eric Laurent5baf2af2013-09-12 17:37:00 -07001408 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1409 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1410 this, effect->desc().name, effect->desc().flags);
1411
Eric Laurent81784c32012-11-19 14:55:58 -08001412 if (chain == 0) {
1413 // create a new chain for this session
1414 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1415 chain = new EffectChain(this, sessionId);
1416 addEffectChain_l(chain);
1417 chain->setStrategy(getStrategyForSession_l(sessionId));
1418 chainCreated = true;
1419 }
1420 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1421
1422 if (chain->getEffectFromId_l(effect->id()) != 0) {
1423 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1424 this, effect->desc().name, chain.get());
1425 return BAD_VALUE;
1426 }
1427
Eric Laurent5baf2af2013-09-12 17:37:00 -07001428 effect->setOffloaded(mType == OFFLOAD, mId);
1429
Eric Laurent81784c32012-11-19 14:55:58 -08001430 status_t status = chain->addEffect_l(effect);
1431 if (status != NO_ERROR) {
1432 if (chainCreated) {
1433 removeEffectChain_l(chain);
1434 }
1435 return status;
1436 }
1437
1438 effect->setDevice(mOutDevice);
1439 effect->setDevice(mInDevice);
1440 effect->setMode(mAudioFlinger->getMode());
1441 effect->setAudioSource(mAudioSource);
1442 return NO_ERROR;
1443}
1444
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001445void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001446
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001447 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001448 effect_descriptor_t desc = effect->desc();
1449 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1450 detachAuxEffect_l(effect->id());
1451 }
1452
1453 sp<EffectChain> chain = effect->chain().promote();
1454 if (chain != 0) {
1455 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001456 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001457 removeEffectChain_l(chain);
1458 }
1459 } else {
1460 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1461 }
1462}
1463
1464void AudioFlinger::ThreadBase::lockEffectChains_l(
1465 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1466{
1467 effectChains = mEffectChains;
1468 for (size_t i = 0; i < mEffectChains.size(); i++) {
1469 mEffectChains[i]->lock();
1470 }
1471}
1472
1473void AudioFlinger::ThreadBase::unlockEffectChains(
1474 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1475{
1476 for (size_t i = 0; i < effectChains.size(); i++) {
1477 effectChains[i]->unlock();
1478 }
1479}
1480
Glenn Kastend848eb42016-03-08 13:42:11 -08001481sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001482{
1483 Mutex::Autolock _l(mLock);
1484 return getEffectChain_l(sessionId);
1485}
1486
Glenn Kastend848eb42016-03-08 13:42:11 -08001487sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1488 const
Eric Laurent81784c32012-11-19 14:55:58 -08001489{
1490 size_t size = mEffectChains.size();
1491 for (size_t i = 0; i < size; i++) {
1492 if (mEffectChains[i]->sessionId() == sessionId) {
1493 return mEffectChains[i];
1494 }
1495 }
1496 return 0;
1497}
1498
1499void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1500{
1501 Mutex::Autolock _l(mLock);
1502 size_t size = mEffectChains.size();
1503 for (size_t i = 0; i < size; i++) {
1504 mEffectChains[i]->setMode_l(mode);
1505 }
1506}
1507
Eric Laurent83b88082014-06-20 18:31:16 -07001508void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1509{
1510 config->type = AUDIO_PORT_TYPE_MIX;
1511 config->ext.mix.handle = mId;
1512 config->sample_rate = mSampleRate;
1513 config->format = mFormat;
1514 config->channel_mask = mChannelMask;
1515 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1516 AUDIO_PORT_CONFIG_FORMAT;
1517}
1518
Eric Laurent72e3f392015-05-20 14:43:50 -07001519void AudioFlinger::ThreadBase::systemReady()
1520{
1521 Mutex::Autolock _l(mLock);
1522 if (mSystemReady) {
1523 return;
1524 }
1525 mSystemReady = true;
1526
1527 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1528 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1529 }
1530 mPendingConfigEvents.clear();
1531}
1532
Andy Hungdae27702016-10-31 14:01:16 -07001533template <typename T>
1534ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1535 ssize_t index = mActiveTracks.indexOf(track);
1536 if (index >= 0) {
1537 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1538 return index;
1539 }
1540 mActiveTracksGeneration++;
1541 mLatestActiveTrack = track;
1542 ++mBatteryCounter[track->uid()].second;
1543 return mActiveTracks.add(track);
1544}
1545
1546template <typename T>
1547ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1548 ssize_t index = mActiveTracks.remove(track);
1549 if (index < 0) {
1550 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1551 return index;
1552 }
1553 mActiveTracksGeneration++;
1554 --mBatteryCounter[track->uid()].second;
1555 // mLatestActiveTrack is not cleared even if is the same as track.
1556 return index;
1557}
1558
1559template <typename T>
1560void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1561 for (const sp<T> &track : mActiveTracks) {
1562 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1563 }
1564 mLastActiveTracksGeneration = mActiveTracksGeneration;
1565 mActiveTracks.clear();
1566 mLatestActiveTrack.clear();
1567 mBatteryCounter.clear();
1568}
1569
1570template <typename T>
1571void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1572 sp<ThreadBase> thread, bool force) {
1573 // Updates ActiveTracks client uids to the thread wakelock.
1574 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1575 thread->updateWakeLockUids_l(getWakeLockUids());
1576 mLastActiveTracksGeneration = mActiveTracksGeneration;
1577 }
1578
1579 // Updates BatteryNotifier uids
1580 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1581 const uid_t uid = it->first;
1582 ssize_t &previous = it->second.first;
1583 ssize_t &current = it->second.second;
1584 if (current > 0) {
1585 if (previous == 0) {
1586 BatteryNotifier::getInstance().noteStartAudio(uid);
1587 }
1588 previous = current;
1589 ++it;
1590 } else if (current == 0) {
1591 if (previous > 0) {
1592 BatteryNotifier::getInstance().noteStopAudio(uid);
1593 }
1594 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1595 } else /* (current < 0) */ {
1596 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1597 }
1598 }
1599}
Eric Laurent83b88082014-06-20 18:31:16 -07001600
Eric Laurent6acd1d42017-01-04 14:23:29 -08001601void AudioFlinger::ThreadBase::broadcast_l()
1602{
1603 // Thread could be blocked waiting for async
1604 // so signal it to handle state changes immediately
1605 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1606 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1607 mSignalPending = true;
1608 mWaitWorkCV.broadcast();
1609}
1610
Eric Laurent81784c32012-11-19 14:55:58 -08001611// ----------------------------------------------------------------------------
1612// Playback
1613// ----------------------------------------------------------------------------
1614
1615AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1616 AudioStreamOut* output,
1617 audio_io_handle_t id,
1618 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001619 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001620 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001621 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001622 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001623 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001624 mMixerBuffer(NULL),
1625 mMixerBufferSize(0),
1626 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1627 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001628 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001629 mEffectBuffer(NULL),
1630 mEffectBufferSize(0),
1631 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1632 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001633 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001634 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001635 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001636 // mStreamTypes[] initialized in constructor body
1637 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001638 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001639 mMixerStatus(MIXER_IDLE),
1640 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001641 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001642 mBytesRemaining(0),
1643 mCurrentWriteLength(0),
1644 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001645 mWriteAckSequence(0),
1646 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001647 mScreenState(AudioFlinger::mScreenState),
1648 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001649 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001650 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001651{
Glenn Kastend7dca052015-03-05 16:05:54 -08001652 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1653 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001654
1655 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1656 // it would be safer to explicitly pass initial masterVolume/masterMute as
1657 // parameter.
1658 //
1659 // If the HAL we are using has support for master volume or master mute,
1660 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1661 // and the mute set to false).
1662 mMasterVolume = audioFlinger->masterVolume_l();
1663 mMasterMute = audioFlinger->masterMute_l();
1664 if (mOutput && mOutput->audioHwDev) {
1665 if (mOutput->audioHwDev->canSetMasterVolume()) {
1666 mMasterVolume = 1.0;
1667 }
1668
1669 if (mOutput->audioHwDev->canSetMasterMute()) {
1670 mMasterMute = false;
1671 }
1672 }
1673
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001674 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001675
Eric Laurent223fd5c2014-11-11 13:43:36 -08001676 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001677 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001678 stream = (audio_stream_type_t) (stream + 1)) {
1679 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1680 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1681 }
Eric Laurent81784c32012-11-19 14:55:58 -08001682}
1683
1684AudioFlinger::PlaybackThread::~PlaybackThread()
1685{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001686 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001687 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001688 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001689 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001690}
1691
1692void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1693{
1694 dumpInternals(fd, args);
1695 dumpTracks(fd, args);
1696 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001697 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001698}
1699
Glenn Kasten0f11b512014-01-31 16:18:54 -08001700void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001701{
1702 const size_t SIZE = 256;
1703 char buffer[SIZE];
1704 String8 result;
1705
Marco Nelissenb2208842014-02-07 14:00:50 -08001706 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001707 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1708 const stream_type_t *st = &mStreamTypes[i];
1709 if (i > 0) {
1710 result.appendFormat(", ");
1711 }
1712 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1713 if (st->mute) {
1714 result.append("M");
1715 }
1716 }
1717 result.append("\n");
1718 write(fd, result.string(), result.length());
1719 result.clear();
1720
Eric Laurent81784c32012-11-19 14:55:58 -08001721 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1722 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001723 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001724 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001725
1726 size_t numtracks = mTracks.size();
1727 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001728 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001729 size_t numactiveseen = 0;
1730 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001731 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001732 Track::appendDumpHeader(result);
1733 for (size_t i = 0; i < numtracks; ++i) {
1734 sp<Track> track = mTracks[i];
1735 if (track != 0) {
1736 bool active = mActiveTracks.indexOf(track) >= 0;
1737 if (active) {
1738 numactiveseen++;
1739 }
1740 track->dump(buffer, SIZE, active);
1741 result.append(buffer);
1742 }
1743 }
1744 } else {
1745 result.append("\n");
1746 }
1747 if (numactiveseen != numactive) {
1748 // some tracks in the active list were not in the tracks list
1749 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1750 " not in the track list\n");
1751 result.append(buffer);
1752 Track::appendDumpHeader(result);
1753 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001754 sp<Track> track = mActiveTracks[i];
1755 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001756 track->dump(buffer, SIZE, true);
1757 result.append(buffer);
1758 }
1759 }
1760 }
1761
1762 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001763}
1764
1765void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1766{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001767 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001768
1769 dumpBase(fd, args);
1770
Elliott Hughes87cebad2014-05-22 10:14:43 -07001771 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001772 dprintf(fd, " Last write occurred (msecs): %llu\n",
1773 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001774 dprintf(fd, " Total writes: %d\n", mNumWrites);
1775 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1776 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1777 dprintf(fd, " Suspend count: %d\n", mSuspended);
1778 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1779 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1780 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1781 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001782 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001783 AudioStreamOut *output = mOutput;
1784 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001785 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1786 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001787 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1788 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1789 if (mPipeSink.get() != nullptr) {
1790 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1791 }
1792 if (output != nullptr) {
1793 dprintf(fd, " Hal stream dump:\n");
1794 (void)output->stream->dump(fd);
1795 }
Eric Laurent81784c32012-11-19 14:55:58 -08001796}
1797
1798// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001799
1800void AudioFlinger::PlaybackThread::onFirstRef()
1801{
Glenn Kastend7dca052015-03-05 16:05:54 -08001802 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001803}
1804
1805// ThreadBase virtuals
1806void AudioFlinger::PlaybackThread::preExit()
1807{
1808 ALOGV(" preExit()");
1809 // FIXME this is using hard-coded strings but in the future, this functionality will be
1810 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001811 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1812 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001813}
1814
1815// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1816sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1817 const sp<AudioFlinger::Client>& client,
1818 audio_stream_type_t streamType,
1819 uint32_t sampleRate,
1820 audio_format_t format,
1821 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001822 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001823 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001824 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001825 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001826 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001827 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001828 status_t *status,
1829 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001830{
Glenn Kasten74935e42013-12-19 08:56:45 -08001831 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001832 sp<Track> track;
1833 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001834 audio_output_flags_t outputFlags = mOutput->flags;
1835
1836 // special case for FAST flag considered OK if fast mixer is present
1837 if (hasFastMixer()) {
1838 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1839 }
1840
1841 // Check if requested flags are compatible with output stream flags
1842 if ((*flags & outputFlags) != *flags) {
1843 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1844 *flags, outputFlags);
1845 *flags = (audio_output_flags_t)(*flags & outputFlags);
1846 }
Eric Laurent81784c32012-11-19 14:55:58 -08001847
Eric Laurent81784c32012-11-19 14:55:58 -08001848 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001849 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001850 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001851 // PCM data
1852 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001853 // TODO: extract as a data library function that checks that a computationally
1854 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001855 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001856 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1857 (channelMask == AUDIO_CHANNEL_OUT_MONO
1858 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001859 // hardware sample rate
1860 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001861 // normal mixer has an associated fast mixer
1862 hasFastMixer() &&
1863 // there are sufficient fast track slots available
1864 (mFastTrackAvailMask != 0)
1865 // FIXME test that MixerThread for this fast track has a capable output HAL
1866 // FIXME add a permission test also?
1867 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001868 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1869 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001870 // read the fast track multiplier property the first time it is needed
1871 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1872 if (ok != 0) {
1873 ALOGE("%s pthread_once failed: %d", __func__, ok);
1874 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001875 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001876 }
Eric Laurent4c415062016-06-17 16:14:16 -07001877
1878 // check compatibility with audio effects.
1879 { // scope for mLock
1880 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001881 for (audio_session_t session : {
1882 AUDIO_SESSION_OUTPUT_STAGE,
1883 AUDIO_SESSION_OUTPUT_MIX,
1884 sessionId,
1885 }) {
1886 sp<EffectChain> chain = getEffectChain_l(session);
1887 if (chain.get() != nullptr) {
1888 audio_output_flags_t old = *flags;
1889 chain->checkOutputFlagCompatibility(flags);
1890 if (old != *flags) {
1891 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1892 (int)session, (int)old, (int)*flags);
1893 }
Eric Laurent4c415062016-06-17 16:14:16 -07001894 }
1895 }
1896 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001897 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001898 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1899 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001900 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001901 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1902 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001903 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001904 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001905 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001906 audio_is_linear_pcm(format),
1907 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001908 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001909 }
1910 }
1911 // For normal PCM streaming tracks, update minimum frame count.
1912 // For compatibility with AudioTrack calculation, buffer depth is forced
1913 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1914 // This is probably too conservative, but legacy application code may depend on it.
1915 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001916 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001917 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001918 // this must match AudioTrack.cpp calculateMinFrameCount().
1919 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001920 uint32_t latencyMs = 0;
1921 lStatus = mOutput->stream->getLatency(&latencyMs);
1922 if (lStatus != OK) {
1923 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1924 goto Exit;
1925 }
Eric Laurent81784c32012-11-19 14:55:58 -08001926 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1927 if (minBufCount < 2) {
1928 minBufCount = 2;
1929 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001930 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1931 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001932 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001933 minBufCount * sourceFramesNeededWithTimestretch(
1934 sampleRate, mNormalFrameCount,
1935 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001936 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001937 frameCount = minFrameCount;
1938 }
Eric Laurent81784c32012-11-19 14:55:58 -08001939 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001940 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001941
Glenn Kastenc3df8382014-03-13 15:05:25 -07001942 switch (mType) {
1943
1944 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001945 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001946 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001947 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1948 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001949 sampleRate, format, channelMask, mOutput, mFormat);
1950 lStatus = BAD_VALUE;
1951 goto Exit;
1952 }
1953 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001954 break;
1955
1956 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001957 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001958 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1959 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001960 sampleRate, format, channelMask, mOutput, mFormat);
1961 lStatus = BAD_VALUE;
1962 goto Exit;
1963 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001964 break;
1965
1966 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001967 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001968 ALOGE("createTrack_l() Bad parameter: format %#x \""
1969 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970 format, mOutput, mFormat);
1971 lStatus = BAD_VALUE;
1972 goto Exit;
1973 }
Andy Hungcd044842014-08-07 11:04:34 -07001974 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001975 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1976 lStatus = BAD_VALUE;
1977 goto Exit;
1978 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001979 break;
1980
Eric Laurent81784c32012-11-19 14:55:58 -08001981 }
1982
1983 lStatus = initCheck();
1984 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001985 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001986 goto Exit;
1987 }
1988
1989 { // scope for mLock
1990 Mutex::Autolock _l(mLock);
1991
1992 // all tracks in same audio session must share the same routing strategy otherwise
1993 // conflicts will happen when tracks are moved from one output to another by audio policy
1994 // manager
1995 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1996 for (size_t i = 0; i < mTracks.size(); ++i) {
1997 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001998 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001999 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2000 if (sessionId == t->sessionId() && strategy != actual) {
2001 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2002 strategy, actual);
2003 lStatus = BAD_VALUE;
2004 goto Exit;
2005 }
2006 }
2007 }
2008
Glenn Kastend79072e2016-01-06 08:41:20 -08002009 track = new Track(this, client, streamType, sampleRate, format,
2010 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002011 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002012
Glenn Kasten03003332013-08-06 15:40:54 -07002013 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2014 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002015 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002016 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002017 goto Exit;
2018 }
2019 mTracks.add(track);
2020
2021 sp<EffectChain> chain = getEffectChain_l(sessionId);
2022 if (chain != 0) {
2023 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2024 track->setMainBuffer(chain->inBuffer());
2025 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2026 chain->incTrackCnt();
2027 }
2028
Eric Laurent05067782016-06-01 18:27:28 -07002029 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002030 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2031 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2032 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08002033 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*isForApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002034 }
2035 }
2036
2037 lStatus = NO_ERROR;
2038
2039Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002040 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002041 return track;
2042}
2043
2044uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2045{
2046 return latency;
2047}
2048
2049uint32_t AudioFlinger::PlaybackThread::latency() const
2050{
2051 Mutex::Autolock _l(mLock);
2052 return latency_l();
2053}
2054uint32_t AudioFlinger::PlaybackThread::latency_l() const
2055{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002056 uint32_t latency;
2057 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2058 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002059 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002060 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002061}
2062
2063void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2064{
2065 Mutex::Autolock _l(mLock);
2066 // Don't apply master volume in SW if our HAL can do it for us.
2067 if (mOutput && mOutput->audioHwDev &&
2068 mOutput->audioHwDev->canSetMasterVolume()) {
2069 mMasterVolume = 1.0;
2070 } else {
2071 mMasterVolume = value;
2072 }
2073}
2074
2075void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2076{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002077 if (isDuplicating()) {
2078 return;
2079 }
Eric Laurent81784c32012-11-19 14:55:58 -08002080 Mutex::Autolock _l(mLock);
2081 // Don't apply master mute in SW if our HAL can do it for us.
2082 if (mOutput && mOutput->audioHwDev &&
2083 mOutput->audioHwDev->canSetMasterMute()) {
2084 mMasterMute = false;
2085 } else {
2086 mMasterMute = muted;
2087 }
2088}
2089
2090void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2091{
2092 Mutex::Autolock _l(mLock);
2093 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002094 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002095}
2096
2097void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2098{
2099 Mutex::Autolock _l(mLock);
2100 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002101 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002102}
2103
2104float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2105{
2106 Mutex::Autolock _l(mLock);
2107 return mStreamTypes[stream].volume;
2108}
2109
2110// addTrack_l() must be called with ThreadBase::mLock held
2111status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2112{
2113 status_t status = ALREADY_EXISTS;
2114
Eric Laurent81784c32012-11-19 14:55:58 -08002115 if (mActiveTracks.indexOf(track) < 0) {
2116 // the track is newly added, make sure it fills up all its
2117 // buffers before playing. This is to ensure the client will
2118 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002119 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002120 TrackBase::track_state state = track->mState;
2121 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002122 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002123 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002124 mLock.lock();
2125 // abort track was stopped/paused while we released the lock
2126 if (state != track->mState) {
2127 if (status == NO_ERROR) {
2128 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002129 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002130 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002131 mLock.lock();
2132 }
2133 return INVALID_OPERATION;
2134 }
2135 // abort if start is rejected by audio policy manager
2136 if (status != NO_ERROR) {
2137 return PERMISSION_DENIED;
2138 }
2139#ifdef ADD_BATTERY_DATA
2140 // to track the speaker usage
2141 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2142#endif
2143 }
2144
Eric Laurent51716182016-02-29 18:00:56 -08002145 // set retry count for buffer fill
2146 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002147 if (track->isStopping_1()) {
2148 track->mRetryCount = kMaxTrackStopRetriesOffload;
2149 } else {
2150 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2151 }
2152 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002153 } else {
2154 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002155 track->mFillingUpStatus =
2156 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002157 }
2158
Eric Laurent81784c32012-11-19 14:55:58 -08002159 track->mResetDone = false;
2160 track->mPresentationCompleteFrames = 0;
2161 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002162 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2163 if (chain != 0) {
2164 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2165 track->sessionId());
2166 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002167 }
2168
Andy Hung2148bf02016-11-28 19:01:02 -08002169 char buffer[256];
2170 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2171 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2172
Eric Laurent81784c32012-11-19 14:55:58 -08002173 status = NO_ERROR;
2174 }
2175
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002176 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002177 return status;
2178}
2179
Eric Laurentbfb1b832013-01-07 09:53:42 -08002180bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002181{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002182 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002183 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002184 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2185 track->mState = TrackBase::STOPPED;
2186 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002187 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002188 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002189 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002190 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002191
2192 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002193}
2194
2195void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2196{
2197 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002198
2199 char buffer[256];
2200 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2201 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2202
Eric Laurent81784c32012-11-19 14:55:58 -08002203 mTracks.remove(track);
2204 deleteTrackName_l(track->name());
2205 // redundant as track is about to be destroyed, for dumpsys only
2206 track->mName = -1;
2207 if (track->isFastTrack()) {
2208 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002209 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002210 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2211 mFastTrackAvailMask |= 1 << index;
2212 // redundant as track is about to be destroyed, for dumpsys only
2213 track->mFastIndex = -1;
2214 }
2215 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2216 if (chain != 0) {
2217 chain->decTrackCnt();
2218 }
2219}
2220
2221String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2222{
Eric Laurent81784c32012-11-19 14:55:58 -08002223 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002224 String8 out_s8;
2225 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2226 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002227 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002228 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002229}
2230
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002231void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002232 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2233 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002234
Eric Laurent73e26b62015-04-27 16:55:58 -07002235 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002236
2237 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002238 case AUDIO_OUTPUT_OPENED:
2239 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002240 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002241 desc->mChannelMask = mChannelMask;
2242 desc->mSamplingRate = mSampleRate;
2243 desc->mFormat = mFormat;
2244 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002245 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002246 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002247 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002248 break;
2249
Eric Laurent73e26b62015-04-27 16:55:58 -07002250 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002251 default:
2252 break;
2253 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002254 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002255}
2256
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002257void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002258{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002259 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002260}
2261
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002262void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002263{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002264 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002265}
2266
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002267void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002268{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002269 mCallbackThread->setAsyncError();
2270}
2271
Eric Laurent3b4529e2013-09-05 18:09:19 -07002272void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273{
2274 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002275 // reject out of sequence requests
2276 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2277 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278 mWaitWorkCV.signal();
2279 }
2280}
2281
Eric Laurent3b4529e2013-09-05 18:09:19 -07002282void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002283{
2284 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002285 // reject out of sequence requests
2286 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2287 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288 mWaitWorkCV.signal();
2289 }
2290}
2291
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002292void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002293{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002294 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002295 mSampleRate = mOutput->getSampleRate();
2296 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002297 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002298 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002299 }
Andy Hung9a592762014-07-21 21:56:01 -07002300 if ((mType == MIXER || mType == DUPLICATING)
2301 && !isValidPcmSinkChannelMask(mChannelMask)) {
2302 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2303 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002304 }
Andy Hunge5412692014-05-16 11:25:07 -07002305 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002306
2307 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002308 status_t result = mOutput->stream->getFormat(&mHALFormat);
2309 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002310 // Get format from the shim, which will be different than the HAL format
2311 // if playing compressed audio over HDMI passthrough.
2312 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002313 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002314 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002315 }
Andy Hung6146c082014-03-18 11:56:15 -07002316 if ((mType == MIXER || mType == DUPLICATING)
2317 && !isValidPcmSinkFormat(mFormat)) {
2318 LOG_FATAL("HAL format %#x not supported for mixed output",
2319 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002320 }
Phil Burk062e67a2015-02-11 13:40:50 -08002321 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002322 result = mOutput->stream->getBufferSize(&mBufferSize);
2323 LOG_ALWAYS_FATAL_IF(result != OK,
2324 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002325 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002326 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002327 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002328 mFrameCount);
2329 }
2330
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002331 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2332 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002333 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002334 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002335 }
2336 }
2337
Eric Laurentd1f69b02014-12-15 14:33:13 -08002338 mHwSupportsPause = false;
2339 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002340 bool supportsPause = false, supportsResume = false;
2341 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2342 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002343 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002344 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002345 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002346 } else if (supportsResume) {
2347 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002348 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002349 }
2350 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002351 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2352 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2353 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002354
Andy Hungfbfc3952015-01-15 13:33:51 -08002355 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2356 // For best precision, we use float instead of the associated output
2357 // device format (typically PCM 16 bit).
2358
2359 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2360 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2361 mBufferSize = mFrameSize * mFrameCount;
2362
2363 // TODO: We currently use the associated output device channel mask and sample rate.
2364 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2365 // (if a valid mask) to avoid premature downmix.
2366 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2367 // instead of the output device sample rate to avoid loss of high frequency information.
2368 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2369 }
2370
Andy Hung09a50072014-02-27 14:30:47 -08002371 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002372 double multiplier = 1.0;
2373 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2374 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002375 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2376 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002377
Eric Laurent81784c32012-11-19 14:55:58 -08002378 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2379 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2380 maxNormalFrameCount = maxNormalFrameCount & ~15;
2381 if (maxNormalFrameCount < minNormalFrameCount) {
2382 maxNormalFrameCount = minNormalFrameCount;
2383 }
2384 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2385 if (multiplier <= 1.0) {
2386 multiplier = 1.0;
2387 } else if (multiplier <= 2.0) {
2388 if (2 * mFrameCount <= maxNormalFrameCount) {
2389 multiplier = 2.0;
2390 } else {
2391 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2392 }
2393 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002394 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002395 }
2396 }
2397 mNormalFrameCount = multiplier * mFrameCount;
2398 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002399 if (mType == MIXER || mType == DUPLICATING) {
2400 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2401 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002402 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002403 mNormalFrameCount);
2404
Andy Hung08fb1742015-05-31 23:22:10 -07002405 // Check if we want to throttle the processing to no more than 2x normal rate
2406 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002407 mThreadThrottleTimeMs = 0;
2408 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002409 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2410
Andy Hung010a1a12014-03-13 13:57:33 -07002411 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2412 // Originally this was int16_t[] array, need to remove legacy implications.
2413 free(mSinkBuffer);
2414 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002415 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2416 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2417 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002418 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002419
Andy Hung69aed5f2014-02-25 17:24:40 -08002420 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2421 // drives the output.
2422 free(mMixerBuffer);
2423 mMixerBuffer = NULL;
2424 if (mMixerBufferEnabled) {
2425 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2426 mMixerBufferSize = mNormalFrameCount * mChannelCount
2427 * audio_bytes_per_sample(mMixerBufferFormat);
2428 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2429 }
Andy Hung98ef9782014-03-04 14:46:50 -08002430 free(mEffectBuffer);
2431 mEffectBuffer = NULL;
2432 if (mEffectBufferEnabled) {
2433 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2434 mEffectBufferSize = mNormalFrameCount * mChannelCount
2435 * audio_bytes_per_sample(mEffectBufferFormat);
2436 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2437 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002438
Eric Laurent81784c32012-11-19 14:55:58 -08002439 // force reconfiguration of effect chains and engines to take new buffer size and audio
2440 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002441 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002442 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2443 // matter.
2444 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2445 Vector< sp<EffectChain> > effectChains = mEffectChains;
2446 for (size_t i = 0; i < effectChains.size(); i ++) {
2447 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2448 }
2449}
2450
2451
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002452status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002453{
2454 if (halFrames == NULL || dspFrames == NULL) {
2455 return BAD_VALUE;
2456 }
2457 Mutex::Autolock _l(mLock);
2458 if (initCheck() != NO_ERROR) {
2459 return INVALID_OPERATION;
2460 }
Andy Hung818e7a32016-02-16 18:08:07 -08002461 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002462 *halFrames = framesWritten;
2463
2464 if (isSuspended()) {
2465 // return an estimation of rendered frames when the output is suspended
2466 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002467 *dspFrames = (uint32_t)
2468 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002469 return NO_ERROR;
2470 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002471 status_t status;
2472 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002473 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002474 *dspFrames = (size_t)frames;
2475 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002476 }
2477}
2478
Eric Laurent4c415062016-06-17 16:14:16 -07002479// hasAudioSession_l() must be called with ThreadBase::mLock held
2480uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002481{
Eric Laurent81784c32012-11-19 14:55:58 -08002482 uint32_t result = 0;
2483 if (getEffectChain_l(sessionId) != 0) {
2484 result = EFFECT_SESSION;
2485 }
2486
2487 for (size_t i = 0; i < mTracks.size(); ++i) {
2488 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002489 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002490 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002491 if (track->isFastTrack()) {
2492 result |= FAST_SESSION;
2493 }
Eric Laurent81784c32012-11-19 14:55:58 -08002494 break;
2495 }
2496 }
2497
2498 return result;
2499}
2500
Glenn Kastend848eb42016-03-08 13:42:11 -08002501uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002502{
2503 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2504 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2505 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2506 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2507 }
2508 for (size_t i = 0; i < mTracks.size(); i++) {
2509 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002510 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002511 return AudioSystem::getStrategyForStream(track->streamType());
2512 }
2513 }
2514 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2515}
2516
2517
Phil Burk062e67a2015-02-11 13:40:50 -08002518AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002519{
2520 Mutex::Autolock _l(mLock);
2521 return mOutput;
2522}
2523
Phil Burk062e67a2015-02-11 13:40:50 -08002524AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002525{
2526 Mutex::Autolock _l(mLock);
2527 AudioStreamOut *output = mOutput;
2528 mOutput = NULL;
2529 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2530 // must push a NULL and wait for ack
2531 mOutputSink.clear();
2532 mPipeSink.clear();
2533 mNormalSink.clear();
2534 return output;
2535}
2536
2537// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002538sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002539{
2540 if (mOutput == NULL) {
2541 return NULL;
2542 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002543 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002544}
2545
2546uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2547{
2548 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2549}
2550
2551status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2552{
2553 if (!isValidSyncEvent(event)) {
2554 return BAD_VALUE;
2555 }
2556
2557 Mutex::Autolock _l(mLock);
2558
2559 for (size_t i = 0; i < mTracks.size(); ++i) {
2560 sp<Track> track = mTracks[i];
2561 if (event->triggerSession() == track->sessionId()) {
2562 (void) track->setSyncEvent(event);
2563 return NO_ERROR;
2564 }
2565 }
2566
2567 return NAME_NOT_FOUND;
2568}
2569
2570bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2571{
2572 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2573}
2574
2575void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2576 const Vector< sp<Track> >& tracksToRemove)
2577{
2578 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002579 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002580 for (size_t i = 0 ; i < count ; i++) {
2581 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002582 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002583 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002584 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585#ifdef ADD_BATTERY_DATA
2586 // to track the speaker usage
2587 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2588#endif
2589 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002590 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002591 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002592 }
Eric Laurent81784c32012-11-19 14:55:58 -08002593 }
2594 }
2595 }
Eric Laurent81784c32012-11-19 14:55:58 -08002596}
2597
2598void AudioFlinger::PlaybackThread::checkSilentMode_l()
2599{
2600 if (!mMasterMute) {
2601 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002602 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2603 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2604 return;
2605 }
Eric Laurent81784c32012-11-19 14:55:58 -08002606 if (property_get("ro.audio.silent", value, "0") > 0) {
2607 char *endptr;
2608 unsigned long ul = strtoul(value, &endptr, 0);
2609 if (*endptr == '\0' && ul != 0) {
2610 ALOGD("Silence is golden");
2611 // The setprop command will not allow a property to be changed after
2612 // the first time it is set, so we don't have to worry about un-muting.
2613 setMasterMute_l(true);
2614 }
2615 }
2616 }
2617}
2618
2619// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002620ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002621{
Eric Laurent81784c32012-11-19 14:55:58 -08002622 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002623 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002624 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002625
2626 // If an NBAIO sink is present, use it to write the normal mixer's submix
2627 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002628
Andy Hung010a1a12014-03-13 13:57:33 -07002629 const size_t count = mBytesRemaining / mFrameSize;
2630
Simon Wilson2d590962012-11-29 15:18:50 -08002631 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002632 // update the setpoint when AudioFlinger::mScreenState changes
2633 uint32_t screenState = AudioFlinger::mScreenState;
2634 if (screenState != mScreenState) {
2635 mScreenState = screenState;
2636 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2637 if (pipe != NULL) {
2638 pipe->setAvgFrames((mScreenState & 1) ?
2639 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2640 }
2641 }
Andy Hung010a1a12014-03-13 13:57:33 -07002642 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002643 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002644 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002645 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002646 } else {
2647 bytesWritten = framesWritten;
2648 }
2649 // otherwise use the HAL / AudioStreamOut directly
2650 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002652
Eric Laurentbfb1b832013-01-07 09:53:42 -08002653 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002654 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2655 mWriteAckSequence += 2;
2656 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002658 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002660 // FIXME We should have an implementation of timestamps for direct output threads.
2661 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002662 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002663
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 if (mUseAsyncWrite &&
2665 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2666 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002667 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002668 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002669 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002670 }
Eric Laurent81784c32012-11-19 14:55:58 -08002671 }
2672
Eric Laurent81784c32012-11-19 14:55:58 -08002673 mNumWrites++;
2674 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002675 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002676 return bytesWritten;
2677}
2678
2679void AudioFlinger::PlaybackThread::threadLoop_drain()
2680{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002681 bool supportsDrain = false;
2682 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002683 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2684 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002685 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2686 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002688 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002689 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002690 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002691 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002692 }
2693}
2694
2695void AudioFlinger::PlaybackThread::threadLoop_exit()
2696{
Eric Laurent275e8e92014-11-30 15:14:47 -08002697 {
2698 Mutex::Autolock _l(mLock);
2699 for (size_t i = 0; i < mTracks.size(); i++) {
2700 sp<Track> track = mTracks[i];
2701 track->invalidate();
2702 }
Andy Hungdae27702016-10-31 14:01:16 -07002703 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2704 // After we exit there are no more track changes sent to BatteryNotifier
2705 // because that requires an active threadLoop.
2706 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2707 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002708 }
Eric Laurent81784c32012-11-19 14:55:58 -08002709}
2710
2711/*
2712The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002713 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002714 - mActiveSleepTimeUs from activeSleepTimeUs()
2715 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002716 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2717 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002718 - maxPeriod from frame count and sample rate (MIXER only)
2719
2720The parameters that affect these derived values are:
2721 - frame count
2722 - frame size
2723 - sample rate
2724 - device type: A2DP or not
2725 - device latency
2726 - format: PCM or not
2727 - active sleep time
2728 - idle sleep time
2729*/
2730
2731void AudioFlinger::PlaybackThread::cacheParameters_l()
2732{
Andy Hung25c2dac2014-02-27 14:56:00 -08002733 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002734 mActiveSleepTimeUs = activeSleepTimeUs();
2735 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002736
2737 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2738 // truncating audio when going to standby.
2739 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2740 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2741 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2742 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2743 }
2744 }
Eric Laurent81784c32012-11-19 14:55:58 -08002745}
2746
Eric Laurent13084622016-05-17 10:51:49 -07002747bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002748{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002749 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002750 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002751 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002752 size_t size = mTracks.size();
2753 for (size_t i = 0; i < size; i++) {
2754 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002755 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002756 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002757 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002758 }
2759 }
Eric Laurent13084622016-05-17 10:51:49 -07002760 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002761}
2762
Haynes Mathew George05317d22016-05-03 16:34:26 -07002763void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2764{
2765 Mutex::Autolock _l(mLock);
2766 invalidateTracks_l(streamType);
2767}
2768
Eric Laurent81784c32012-11-19 14:55:58 -08002769status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2770{
Glenn Kastend848eb42016-03-08 13:42:11 -08002771 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002772 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2773 status_t result = EffectBufferHalInterface::mirror(
2774 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2775 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2776 &halInBuffer);
2777 if (result != OK) return result;
2778 halOutBuffer = halInBuffer;
2779 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002780
2781 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002782 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002783 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002784 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002785 if (mType != DIRECT) {
2786 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002787 status_t result = EffectBufferHalInterface::allocate(
2788 numSamples * sizeof(int16_t),
2789 &halInBuffer);
2790 if (result != OK) return result;
2791 buffer = halInBuffer->audioBuffer()->s16;
2792 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2793 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002794 }
2795
2796 // Attach all tracks with same session ID to this chain.
2797 for (size_t i = 0; i < mTracks.size(); ++i) {
2798 sp<Track> track = mTracks[i];
2799 if (session == track->sessionId()) {
2800 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2801 buffer);
2802 track->setMainBuffer(buffer);
2803 chain->incTrackCnt();
2804 }
2805 }
2806
2807 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002808 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002809 if (session == track->sessionId()) {
2810 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2811 chain->incActiveTrackCnt();
2812 }
2813 }
2814 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002815 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002816 chain->setInBuffer(halInBuffer);
2817 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002818 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002819 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002820 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2821 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002822 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002823 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002824 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002825 // Effect chain for other sessions are inserted at beginning of effect
2826 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002827 // sessions is not important.
2828 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2829 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2830 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002831 size_t size = mEffectChains.size();
2832 size_t i = 0;
2833 for (i = 0; i < size; i++) {
2834 if (mEffectChains[i]->sessionId() < session) {
2835 break;
2836 }
2837 }
2838 mEffectChains.insertAt(chain, i);
2839 checkSuspendOnAddEffectChain_l(chain);
2840
2841 return NO_ERROR;
2842}
2843
2844size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2845{
Glenn Kastend848eb42016-03-08 13:42:11 -08002846 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002847
2848 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2849
2850 for (size_t i = 0; i < mEffectChains.size(); i++) {
2851 if (chain == mEffectChains[i]) {
2852 mEffectChains.removeAt(i);
2853 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002854 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002855 if (session == track->sessionId()) {
2856 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2857 chain.get(), session);
2858 chain->decActiveTrackCnt();
2859 }
2860 }
2861
2862 // detach all tracks with same session ID from this chain
2863 for (size_t i = 0; i < mTracks.size(); ++i) {
2864 sp<Track> track = mTracks[i];
2865 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002866 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002867 chain->decTrackCnt();
2868 }
2869 }
2870 break;
2871 }
2872 }
2873 return mEffectChains.size();
2874}
2875
2876status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002877 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002878{
2879 Mutex::Autolock _l(mLock);
2880 return attachAuxEffect_l(track, EffectId);
2881}
2882
2883status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002884 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002885{
2886 status_t status = NO_ERROR;
2887
2888 if (EffectId == 0) {
2889 track->setAuxBuffer(0, NULL);
2890 } else {
2891 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2892 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2893 if (effect != 0) {
2894 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2895 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2896 } else {
2897 status = INVALID_OPERATION;
2898 }
2899 } else {
2900 status = BAD_VALUE;
2901 }
2902 }
2903 return status;
2904}
2905
2906void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2907{
2908 for (size_t i = 0; i < mTracks.size(); ++i) {
2909 sp<Track> track = mTracks[i];
2910 if (track->auxEffectId() == effectId) {
2911 attachAuxEffect_l(track, 0);
2912 }
2913 }
2914}
2915
2916bool AudioFlinger::PlaybackThread::threadLoop()
2917{
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002918 logWriterTLS = mNBLogWriter.get();
2919
Eric Laurent81784c32012-11-19 14:55:58 -08002920 Vector< sp<Track> > tracksToRemove;
2921
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002922 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002923 nsecs_t lastWriteFinished = -1; // time last server write completed
2924 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002925
2926 // MIXER
2927 nsecs_t lastWarning = 0;
2928
2929 // DUPLICATING
2930 // FIXME could this be made local to while loop?
2931 writeFrames = 0;
2932
2933 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002934 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002935
2936 if (mType == MIXER) {
2937 sleepTimeShift = 0;
2938 }
2939
2940 CpuStats cpuStats;
2941 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2942
2943 acquireWakeLock();
2944
Glenn Kasten9e58b552013-01-18 15:09:48 -08002945 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2946 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2947 // and then that string will be logged at the next convenient opportunity.
2948 const char *logString = NULL;
2949
Eric Laurent664539d2013-09-23 18:24:31 -07002950 checkSilentMode_l();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002951#if 0
2952 int z = 0; // used in logFormat example
2953#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002954 while (!exitPending())
2955 {
2956 cpuStats.sample(myName);
2957
2958 Vector< sp<EffectChain> > effectChains;
2959
Eric Laurent81784c32012-11-19 14:55:58 -08002960 { // scope for mLock
2961
2962 Mutex::Autolock _l(mLock);
2963
Eric Laurent021cf962014-05-13 10:18:14 -07002964 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002965
Glenn Kasten9e58b552013-01-18 15:09:48 -08002966 if (logString != NULL) {
2967 mNBLogWriter->logTimestamp();
2968 mNBLogWriter->log(logString);
2969 logString = NULL;
2970 }
2971
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002972 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002973 // and associate with the sink frames written out. We need
2974 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002975 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002976 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002977 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002978 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002979 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002980 ExtendedTimestamp timestamp; // use private copy to fetch
2981 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002982
2983 // We keep track of the last valid kernel position in case we are in underrun
2984 // and the normal mixer period is the same as the fast mixer period, or there
2985 // is some error from the HAL.
2986 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2987 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2988 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2989 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2990 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2991
2992 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2993 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2994 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2995 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002996 }
2997
2998 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2999 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003000 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003001 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003002 }
3003
Andy Hung818e7a32016-02-16 18:08:07 -08003004 // copy over kernel info
3005 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003006 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3007 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003008 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3009 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003010 }
3011 // mFramesWritten for non-offloaded tracks are contiguous
3012 // even after standby() is called. This is useful for the track frame
3013 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003014 bool serverLocationUpdate = false;
3015 if (mFramesWritten != lastFramesWritten) {
3016 serverLocationUpdate = true;
3017 lastFramesWritten = mFramesWritten;
3018 }
3019 // Only update timestamps if there is a meaningful change.
3020 // Either the kernel timestamp must be valid or we have written something.
3021 if (kernelLocationUpdate || serverLocationUpdate) {
3022 if (serverLocationUpdate) {
3023 // use the time before we called the HAL write - it is a bit more accurate
3024 // to when the server last read data than the current time here.
3025 //
3026 // If we haven't written anything, mLastWriteTime will be -1
3027 // and we use systemTime().
3028 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3029 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3030 ? systemTime() : mLastWriteTime;
3031 }
Andy Hungdae27702016-10-31 14:01:16 -07003032
3033 for (const sp<Track> &t : mActiveTracks) {
3034 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003035 t->updateTrackFrameInfo(
3036 t->mAudioTrackServerProxy->framesReleased(),
3037 mFramesWritten,
3038 mTimestamp);
3039 }
Andy Hunge10393e2015-06-12 13:59:33 -07003040 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003041 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003042#if 0
3043 // logFormat example
3044 if (!(z % 100)) {
3045 timespec ts;
3046 clock_gettime(CLOCK_MONOTONIC, &ts);
3047 LOGF("This is an integer %d, this is a float %f, this is my "
3048 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
3049 LOGF("A deceptive null-terminated string %\0");
3050 }
3051 ++z;
3052#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003053 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003054 if (mSignalPending) {
3055 // A signal was raised while we were unlocked
3056 mSignalPending = false;
3057 } else if (waitingAsyncCallback_l()) {
3058 if (exitPending()) {
3059 break;
3060 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003061 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003062 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003063 releaseWakeLock_l();
3064 released = true;
3065 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003066 ALOGV("wait async completion");
3067 mWaitWorkCV.wait(mLock);
3068 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003069 if (released) {
3070 acquireWakeLock_l();
3071 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003072 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3073 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003074
3075 continue;
3076 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003077 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003078 isSuspended()) {
3079 // put audio hardware into standby after short delay
3080 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003081
3082 threadLoop_standby();
3083
3084 mStandby = true;
3085 }
3086
3087 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3088 // we're about to wait, flush the binder command buffer
3089 IPCThreadState::self()->flushCommands();
3090
3091 clearOutputTracks();
3092
3093 if (exitPending()) {
3094 break;
3095 }
3096
3097 releaseWakeLock_l();
3098 // wait until we have something to do...
3099 ALOGV("%s going to sleep", myName.string());
3100 mWaitWorkCV.wait(mLock);
3101 ALOGV("%s waking up", myName.string());
3102 acquireWakeLock_l();
3103
3104 mMixerStatus = MIXER_IDLE;
3105 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3106 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003108 checkSilentMode_l();
3109
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003110 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3111 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003112 if (mType == MIXER) {
3113 sleepTimeShift = 0;
3114 }
3115
3116 continue;
3117 }
3118 }
Eric Laurent81784c32012-11-19 14:55:58 -08003119 // mMixerStatusIgnoringFastTracks is also updated internally
3120 mMixerStatus = prepareTracks_l(&tracksToRemove);
3121
Andy Hungdae27702016-10-31 14:01:16 -07003122 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003123
Eric Laurent81784c32012-11-19 14:55:58 -08003124 // prevent any changes in effect chain list and in each effect chain
3125 // during mixing and effect process as the audio buffers could be deleted
3126 // or modified if an effect is created or deleted
3127 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003128 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003129
Eric Laurentbfb1b832013-01-07 09:53:42 -08003130 if (mBytesRemaining == 0) {
3131 mCurrentWriteLength = 0;
3132 if (mMixerStatus == MIXER_TRACKS_READY) {
3133 // threadLoop_mix() sets mCurrentWriteLength
3134 threadLoop_mix();
3135 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3136 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003137 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003138 // must be written to HAL
3139 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003140 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003141 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003142 }
3143 }
Andy Hung98ef9782014-03-04 14:46:50 -08003144 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003145 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003146 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3147 // or mSinkBuffer (if there are no effects).
3148 //
3149 // This is done pre-effects computation; if effects change to
3150 // support higher precision, this needs to move.
3151 //
3152 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003153 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003154 if (mMixerBufferValid) {
3155 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3156 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3157
Andy Hung2ddee192015-12-18 17:34:44 -08003158 // mono blend occurs for mixer threads only (not direct or offloaded)
3159 // and is handled here if we're going directly to the sink.
3160 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003161 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3162 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003163 }
3164
Andy Hung98ef9782014-03-04 14:46:50 -08003165 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3166 mNormalFrameCount * mChannelCount);
3167 }
3168
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169 mBytesRemaining = mCurrentWriteLength;
3170 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003171 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3172 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3173 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3174 mBytesWritten += mBytesRemaining;
3175 mFramesWritten += framesRemaining;
3176 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003177 mBytesRemaining = 0;
3178 }
Eric Laurent81784c32012-11-19 14:55:58 -08003179
Eric Laurentbfb1b832013-01-07 09:53:42 -08003180 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003181 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003182 for (size_t i = 0; i < effectChains.size(); i ++) {
3183 effectChains[i]->process_l();
3184 }
Eric Laurent81784c32012-11-19 14:55:58 -08003185 }
3186 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003187 // Process effect chains for offloaded thread even if no audio
3188 // was read from audio track: process only updates effect state
3189 // and thus does have to be synchronized with audio writes but may have
3190 // to be called while waiting for async write callback
3191 if (mType == OFFLOAD) {
3192 for (size_t i = 0; i < effectChains.size(); i ++) {
3193 effectChains[i]->process_l();
3194 }
3195 }
Eric Laurent81784c32012-11-19 14:55:58 -08003196
Andy Hung98ef9782014-03-04 14:46:50 -08003197 // Only if the Effects buffer is enabled and there is data in the
3198 // Effects buffer (buffer valid), we need to
3199 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003200 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003201 if (mEffectBufferValid) {
3202 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003203
3204 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003205 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3206 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003207 }
3208
Andy Hung98ef9782014-03-04 14:46:50 -08003209 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3210 mNormalFrameCount * mChannelCount);
3211 }
3212
Eric Laurent81784c32012-11-19 14:55:58 -08003213 // enable changes in effect chain
3214 unlockEffectChains(effectChains);
3215
Eric Laurentbfb1b832013-01-07 09:53:42 -08003216 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003217 // mSleepTimeUs == 0 means we must write to audio hardware
3218 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003219 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003220 // We save lastWriteFinished here, as previousLastWriteFinished,
3221 // for throttling. On thread start, previousLastWriteFinished will be
3222 // set to -1, which properly results in no throttling after the first write.
3223 nsecs_t previousLastWriteFinished = lastWriteFinished;
3224 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003225 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003226 // FIXME rewrite to reduce number of system calls
3227 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003228 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003229 lastWriteFinished = systemTime();
3230 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003231 if (ret < 0) {
3232 mBytesRemaining = 0;
3233 } else {
3234 mBytesWritten += ret;
3235 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003236 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003237 }
3238 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3239 (mMixerStatus == MIXER_DRAIN_ALL)) {
3240 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003241 }
Andy Hung08fb1742015-05-31 23:22:10 -07003242 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003243 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003244 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003245 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003246 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003247 ATRACE_NAME("underrun");
3248 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003249 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003250 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003251 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003252 }
Andy Hung08fb1742015-05-31 23:22:10 -07003253
3254 if (mThreadThrottle
3255 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3256 && ret > 0) { // we wrote something
3257 // Limit MixerThread data processing to no more than twice the
3258 // expected processing rate.
3259 //
3260 // This helps prevent underruns with NuPlayer and other applications
3261 // which may set up buffers that are close to the minimum size, or use
3262 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3263 //
3264 // The throttle smooths out sudden large data drains from the device,
3265 // e.g. when it comes out of standby, which often causes problems with
3266 // (1) mixer threads without a fast mixer (which has its own warm-up)
3267 // (2) minimum buffer sized tracks (even if the track is full,
3268 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003269 //
3270 // Total time spent in last processing cycle equals time spent in
3271 // 1. threadLoop_write, as well as time spent in
3272 // 2. threadLoop_mix (significant for heavy mixing, especially
3273 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003274
Andy Hung69488c42016-05-16 18:43:33 -07003275 // it's OK if deltaMs is an overestimate.
3276 const int32_t deltaMs =
3277 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003278 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3279 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3280 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003281 // notify of throttle start on verbose log
3282 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3283 "mixer(%p) throttle begin:"
3284 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003285 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003286 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003287 // Throttle must be attributed to the previous mixer loop's write time
3288 // to allow back-to-back throttling.
3289 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003290 } else {
3291 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3292 if (diff > 0) {
3293 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003294 // but prevent spamming for bluetooth
3295 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3296 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003297 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3298 }
Andy Hung08fb1742015-05-31 23:22:10 -07003299 }
3300 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003301 }
Eric Laurent81784c32012-11-19 14:55:58 -08003302
Eric Laurentbfb1b832013-01-07 09:53:42 -08003303 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003304 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003305 Mutex::Autolock _l(mLock);
3306 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3307 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003308 }
Glenn Kastene7754022014-10-31 12:11:26 -07003309 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003310 }
Eric Laurent81784c32012-11-19 14:55:58 -08003311 }
3312
3313 // Finally let go of removed track(s), without the lock held
3314 // since we can't guarantee the destructors won't acquire that
3315 // same lock. This will also mutate and push a new fast mixer state.
3316 threadLoop_removeTracks(tracksToRemove);
3317 tracksToRemove.clear();
3318
3319 // FIXME I don't understand the need for this here;
3320 // it was in the original code but maybe the
3321 // assignment in saveOutputTracks() makes this unnecessary?
3322 clearOutputTracks();
3323
3324 // Effect chains will be actually deleted here if they were removed from
3325 // mEffectChains list during mixing or effects processing
3326 effectChains.clear();
3327
3328 // FIXME Note that the above .clear() is no longer necessary since effectChains
3329 // is now local to this block, but will keep it for now (at least until merge done).
3330 }
3331
Eric Laurentbfb1b832013-01-07 09:53:42 -08003332 threadLoop_exit();
3333
Eric Laurentcf817a22014-08-04 20:36:31 -07003334 if (!mStandby) {
3335 threadLoop_standby();
3336 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003337 }
3338
3339 releaseWakeLock();
3340
3341 ALOGV("Thread %p type %d exiting", this, mType);
3342 return false;
3343}
3344
Eric Laurentbfb1b832013-01-07 09:53:42 -08003345// removeTracks_l() must be called with ThreadBase::mLock held
3346void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3347{
3348 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003349 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003350 for (size_t i=0 ; i<count ; i++) {
3351 const sp<Track>& track = tracksToRemove.itemAt(i);
3352 mActiveTracks.remove(track);
3353 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3354 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3355 if (chain != 0) {
3356 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3357 track->sessionId());
3358 chain->decActiveTrackCnt();
3359 }
3360 if (track->isTerminated()) {
3361 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003362 } else { // inactive but not terminated
3363 char buffer[256];
3364 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3365 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003366 }
3367 }
3368 }
3369
3370}
Eric Laurent81784c32012-11-19 14:55:58 -08003371
Eric Laurentaccc1472013-09-20 09:36:34 -07003372status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3373{
3374 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003375 ExtendedTimestamp ets;
3376 status_t status = mNormalSink->getTimestamp(ets);
3377 if (status == NO_ERROR) {
3378 status = ets.getBestTimestamp(&timestamp);
3379 }
3380 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003381 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003382 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003383 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003384 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003385 timestamp.mPosition = (uint32_t)position64;
3386 return NO_ERROR;
3387 }
3388 }
3389 return INVALID_OPERATION;
3390}
Eric Laurent1c333e22014-05-20 10:48:17 -07003391
Eric Laurent054d9d32015-04-24 08:48:48 -07003392status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3393 audio_patch_handle_t *handle)
3394{
Andy Hungf60abce2016-08-26 11:37:54 -07003395 status_t status;
3396 if (property_get_bool("af.patch_park", false /* default_value */)) {
3397 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3398 // or if HAL does not properly lock against access.
3399 AutoPark<FastMixer> park(mFastMixer);
3400 status = PlaybackThread::createAudioPatch_l(patch, handle);
3401 } else {
3402 status = PlaybackThread::createAudioPatch_l(patch, handle);
3403 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003404 return status;
3405}
3406
Eric Laurent1c333e22014-05-20 10:48:17 -07003407status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3408 audio_patch_handle_t *handle)
3409{
3410 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003411
3412 // store new device and send to effects
3413 audio_devices_t type = AUDIO_DEVICE_NONE;
3414 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3415 type |= patch->sinks[i].ext.device.type;
3416 }
3417
3418#ifdef ADD_BATTERY_DATA
3419 // when changing the audio output device, call addBatteryData to notify
3420 // the change
3421 if (mOutDevice != type) {
3422 uint32_t params = 0;
3423 // check whether speaker is on
3424 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3425 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003426 }
3427
Eric Laurent054d9d32015-04-24 08:48:48 -07003428 audio_devices_t deviceWithoutSpeaker
3429 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3430 // check if any other device (except speaker) is on
3431 if (type & deviceWithoutSpeaker) {
3432 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3433 }
3434
3435 if (params != 0) {
3436 addBatteryData(params);
3437 }
3438 }
3439#endif
3440
3441 for (size_t i = 0; i < mEffectChains.size(); i++) {
3442 mEffectChains[i]->setDevice_l(type);
3443 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003444
3445 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3446 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3447 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003448 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003449 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003450
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003451 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003452 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3453 status = hwDevice->createAudioPatch(patch->num_sources,
3454 patch->sources,
3455 patch->num_sinks,
3456 patch->sinks,
3457 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003458 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003459 char *address;
3460 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3461 //FIXME: we only support address on first sink with HAL version < 3.0
3462 address = audio_device_address_to_parameter(
3463 patch->sinks[0].ext.device.type,
3464 patch->sinks[0].ext.device.address);
3465 } else {
3466 address = (char *)calloc(1, 1);
3467 }
3468 AudioParameter param = AudioParameter(String8(address));
3469 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003470 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003471 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003472 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003473 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003474 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003475 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003476 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3477 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003478 return status;
3479}
3480
Eric Laurent054d9d32015-04-24 08:48:48 -07003481status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3482{
Andy Hungf60abce2016-08-26 11:37:54 -07003483 status_t status;
3484 if (property_get_bool("af.patch_park", false /* default_value */)) {
3485 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3486 // or if HAL does not properly lock against access.
3487 AutoPark<FastMixer> park(mFastMixer);
3488 status = PlaybackThread::releaseAudioPatch_l(handle);
3489 } else {
3490 status = PlaybackThread::releaseAudioPatch_l(handle);
3491 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003492 return status;
3493}
3494
Eric Laurent1c333e22014-05-20 10:48:17 -07003495status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3496{
3497 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003498
3499 mOutDevice = AUDIO_DEVICE_NONE;
3500
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003501 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003502 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3503 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003504 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003505 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003506 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003507 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003508 }
3509 return status;
3510}
3511
Eric Laurent83b88082014-06-20 18:31:16 -07003512void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3513{
3514 Mutex::Autolock _l(mLock);
3515 mTracks.add(track);
3516}
3517
3518void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3519{
3520 Mutex::Autolock _l(mLock);
3521 destroyTrack_l(track);
3522}
3523
3524void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3525{
3526 ThreadBase::getAudioPortConfig(config);
3527 config->role = AUDIO_PORT_ROLE_SOURCE;
3528 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3529 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3530}
3531
Eric Laurent81784c32012-11-19 14:55:58 -08003532// ----------------------------------------------------------------------------
3533
3534AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003535 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3536 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003537 // mAudioMixer below
3538 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003539 mFastMixerFutex(0),
3540 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003541 // mOutputSink below
3542 // mPipeSink below
3543 // mNormalSink below
3544{
3545 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003546 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3547 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003548 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3549 mNormalFrameCount);
3550 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3551
Andy Hungfbfc3952015-01-15 13:33:51 -08003552 if (type == DUPLICATING) {
3553 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3554 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3555 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3556 return;
3557 }
Eric Laurent81784c32012-11-19 14:55:58 -08003558 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003559 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003560 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003561 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003562#if !LOG_NDEBUG
3563 ssize_t index =
3564#else
3565 (void)
3566#endif
3567 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003568 ALOG_ASSERT(index == 0);
3569
3570 // initialize fast mixer depending on configuration
3571 bool initFastMixer;
3572 switch (kUseFastMixer) {
3573 case FastMixer_Never:
3574 initFastMixer = false;
3575 break;
3576 case FastMixer_Always:
3577 initFastMixer = true;
3578 break;
3579 case FastMixer_Static:
3580 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003581 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3582 // where the period is less than an experimentally determined threshold that can be
3583 // scheduled reliably with CFS. However, the BT A2DP HAL is
3584 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3585 initFastMixer = mFrameCount < mNormalFrameCount
3586 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003587 break;
3588 }
Andy Hungfda69402017-02-15 14:33:12 -08003589 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3590 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3591 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003592 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003593 audio_format_t fastMixerFormat;
3594 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3595 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3596 } else {
3597 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3598 }
3599 if (mFormat != fastMixerFormat) {
3600 // change our Sink format to accept our intermediate precision
3601 mFormat = fastMixerFormat;
3602 free(mSinkBuffer);
3603 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3604 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3605 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3606 }
Eric Laurent81784c32012-11-19 14:55:58 -08003607
3608 // create a MonoPipe to connect our submix to FastMixer
3609 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003610#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003611 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003612#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003613 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003614 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003615 format.mFormat = fastMixerFormat;
3616 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3617
Eric Laurent81784c32012-11-19 14:55:58 -08003618 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3619 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3620 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3621 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3622 const NBAIO_Format offers[1] = {format};
3623 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003624#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003625 ssize_t index =
3626#else
3627 (void)
3628#endif
3629 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003630 ALOG_ASSERT(index == 0);
3631 monoPipe->setAvgFrames((mScreenState & 1) ?
3632 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3633 mPipeSink = monoPipe;
3634
Glenn Kasten46909e72013-02-26 09:20:22 -08003635#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003636 if (mTeeSinkOutputEnabled) {
3637 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003638 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3639 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003640 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003641 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003642 ALOG_ASSERT(index == 0);
3643 mTeeSink = teeSink;
3644 PipeReader *teeSource = new PipeReader(*teeSink);
3645 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003646 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003647 ALOG_ASSERT(index == 0);
3648 mTeeSource = teeSource;
3649 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003650#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003651
3652 // create fast mixer and configure it initially with just one fast track for our submix
3653 mFastMixer = new FastMixer();
3654 FastMixerStateQueue *sq = mFastMixer->sq();
3655#ifdef STATE_QUEUE_DUMP
3656 sq->setObserverDump(&mStateQueueObserverDump);
3657 sq->setMutatorDump(&mStateQueueMutatorDump);
3658#endif
3659 FastMixerState *state = sq->begin();
3660 FastTrack *fastTrack = &state->mFastTracks[0];
3661 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3662 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3663 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003664 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3665 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003666 fastTrack->mGeneration++;
3667 state->mFastTracksGen++;
3668 state->mTrackMask = 1;
3669 // fast mixer will use the HAL output sink
3670 state->mOutputSink = mOutputSink.get();
3671 state->mOutputSinkGen++;
3672 state->mFrameCount = mFrameCount;
3673 state->mCommand = FastMixerState::COLD_IDLE;
3674 // already done in constructor initialization list
3675 //mFastMixerFutex = 0;
3676 state->mColdFutexAddr = &mFastMixerFutex;
3677 state->mColdGen++;
3678 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003679#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003680 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003681#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003682 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3683 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003684 sq->end();
3685 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3686
3687 // start the fast mixer
3688 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3689 pid_t tid = mFastMixer->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08003690 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003691 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003692
3693#ifdef AUDIO_WATCHDOG
3694 // create and start the watchdog
3695 mAudioWatchdog = new AudioWatchdog();
3696 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3697 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3698 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003699 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003700#endif
3701
Eric Laurent81784c32012-11-19 14:55:58 -08003702 }
3703
3704 switch (kUseFastMixer) {
3705 case FastMixer_Never:
3706 case FastMixer_Dynamic:
3707 mNormalSink = mOutputSink;
3708 break;
3709 case FastMixer_Always:
3710 mNormalSink = mPipeSink;
3711 break;
3712 case FastMixer_Static:
3713 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3714 break;
3715 }
3716}
3717
3718AudioFlinger::MixerThread::~MixerThread()
3719{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003720 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003721 FastMixerStateQueue *sq = mFastMixer->sq();
3722 FastMixerState *state = sq->begin();
3723 if (state->mCommand == FastMixerState::COLD_IDLE) {
3724 int32_t old = android_atomic_inc(&mFastMixerFutex);
3725 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003726 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003727 }
3728 }
3729 state->mCommand = FastMixerState::EXIT;
3730 sq->end();
3731 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3732 mFastMixer->join();
3733 // Though the fast mixer thread has exited, it's state queue is still valid.
3734 // We'll use that extract the final state which contains one remaining fast track
3735 // corresponding to our sub-mix.
3736 state = sq->begin();
3737 ALOG_ASSERT(state->mTrackMask == 1);
3738 FastTrack *fastTrack = &state->mFastTracks[0];
3739 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3740 delete fastTrack->mBufferProvider;
3741 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003742 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003743#ifdef AUDIO_WATCHDOG
3744 if (mAudioWatchdog != 0) {
3745 mAudioWatchdog->requestExit();
3746 mAudioWatchdog->requestExitAndWait();
3747 mAudioWatchdog.clear();
3748 }
3749#endif
3750 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003751 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003752 delete mAudioMixer;
3753}
3754
3755
3756uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3757{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003758 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003759 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3760 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3761 }
3762 return latency;
3763}
3764
3765
3766void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3767{
3768 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3769}
3770
Eric Laurentbfb1b832013-01-07 09:53:42 -08003771ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003772{
3773 // FIXME we should only do one push per cycle; confirm this is true
3774 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003775 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003776 FastMixerStateQueue *sq = mFastMixer->sq();
3777 FastMixerState *state = sq->begin();
3778 if (state->mCommand != FastMixerState::MIX_WRITE &&
3779 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3780 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003781
3782 // FIXME workaround for first HAL write being CPU bound on some devices
3783 ATRACE_BEGIN("write");
3784 mOutput->write((char *)mSinkBuffer, 0);
3785 ATRACE_END();
3786
Eric Laurent81784c32012-11-19 14:55:58 -08003787 int32_t old = android_atomic_inc(&mFastMixerFutex);
3788 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003789 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003790 }
3791#ifdef AUDIO_WATCHDOG
3792 if (mAudioWatchdog != 0) {
3793 mAudioWatchdog->resume();
3794 }
3795#endif
3796 }
3797 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003798#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003799 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003800 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003801#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003802 sq->end();
3803 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3804 if (kUseFastMixer == FastMixer_Dynamic) {
3805 mNormalSink = mPipeSink;
3806 }
3807 } else {
3808 sq->end(false /*didModify*/);
3809 }
3810 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003811 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003812}
3813
3814void AudioFlinger::MixerThread::threadLoop_standby()
3815{
3816 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003817 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003818 FastMixerStateQueue *sq = mFastMixer->sq();
3819 FastMixerState *state = sq->begin();
3820 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003821 // Report any frames trapped in the Monopipe
3822 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3823 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3824 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3825 "monoPipeWritten:%lld monoPipeLeft:%lld",
3826 (long long)mFramesWritten, (long long)mSuspendedFrames,
3827 (long long)mPipeSink->framesWritten(), pipeFrames);
3828 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3829
Eric Laurent81784c32012-11-19 14:55:58 -08003830 state->mCommand = FastMixerState::COLD_IDLE;
3831 state->mColdFutexAddr = &mFastMixerFutex;
3832 state->mColdGen++;
3833 mFastMixerFutex = 0;
3834 sq->end();
3835 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3836 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3837 if (kUseFastMixer == FastMixer_Dynamic) {
3838 mNormalSink = mOutputSink;
3839 }
3840#ifdef AUDIO_WATCHDOG
3841 if (mAudioWatchdog != 0) {
3842 mAudioWatchdog->pause();
3843 }
3844#endif
3845 } else {
3846 sq->end(false /*didModify*/);
3847 }
3848 }
3849 PlaybackThread::threadLoop_standby();
3850}
3851
Eric Laurentbfb1b832013-01-07 09:53:42 -08003852bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3853{
3854 return false;
3855}
3856
3857bool AudioFlinger::PlaybackThread::shouldStandby_l()
3858{
3859 return !mStandby;
3860}
3861
3862bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3863{
3864 Mutex::Autolock _l(mLock);
3865 return waitingAsyncCallback_l();
3866}
3867
Eric Laurent81784c32012-11-19 14:55:58 -08003868// shared by MIXER and DIRECT, overridden by DUPLICATING
3869void AudioFlinger::PlaybackThread::threadLoop_standby()
3870{
3871 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003872 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003873 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003874 // discard any pending drain or write ack by incrementing sequence
3875 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3876 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003877 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003878 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3879 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003880 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003881 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003882}
3883
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003884void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3885{
3886 ALOGV("signal playback thread");
3887 broadcast_l();
3888}
3889
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003890void AudioFlinger::PlaybackThread::onAsyncError()
3891{
3892 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3893 invalidateTracks((audio_stream_type_t)i);
3894 }
3895}
3896
Eric Laurent81784c32012-11-19 14:55:58 -08003897void AudioFlinger::MixerThread::threadLoop_mix()
3898{
Eric Laurent81784c32012-11-19 14:55:58 -08003899 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003900 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003901 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003902 // increase sleep time progressively when application underrun condition clears.
3903 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3904 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3905 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003906 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003907 sleepTimeShift--;
3908 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003909 mSleepTimeUs = 0;
3910 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003911 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003912
Eric Laurent81784c32012-11-19 14:55:58 -08003913}
3914
3915void AudioFlinger::MixerThread::threadLoop_sleepTime()
3916{
3917 // If no tracks are ready, sleep once for the duration of an output
3918 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003919 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003920 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003921 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3922 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3923 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003924 }
3925 // reduce sleep time in case of consecutive application underruns to avoid
3926 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3927 // duration we would end up writing less data than needed by the audio HAL if
3928 // the condition persists.
3929 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3930 sleepTimeShift++;
3931 }
3932 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003933 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003934 }
3935 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003936 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3937 // before effects processing or output.
3938 if (mMixerBufferValid) {
3939 memset(mMixerBuffer, 0, mMixerBufferSize);
3940 } else {
3941 memset(mSinkBuffer, 0, mSinkBufferSize);
3942 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003943 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003944 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3945 "anticipated start");
3946 }
3947 // TODO add standby time extension fct of effect tail
3948}
3949
3950// prepareTracks_l() must be called with ThreadBase::mLock held
3951AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3952 Vector< sp<Track> > *tracksToRemove)
3953{
3954
3955 mixer_state mixerStatus = MIXER_IDLE;
3956 // find out which tracks need to be processed
3957 size_t count = mActiveTracks.size();
3958 size_t mixedTracks = 0;
3959 size_t tracksWithEffect = 0;
3960 // counts only _active_ fast tracks
3961 size_t fastTracks = 0;
3962 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3963
3964 float masterVolume = mMasterVolume;
3965 bool masterMute = mMasterMute;
3966
3967 if (masterMute) {
3968 masterVolume = 0;
3969 }
3970 // Delegate master volume control to effect in output mix effect chain if needed
3971 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3972 if (chain != 0) {
3973 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3974 chain->setVolume_l(&v, &v);
3975 masterVolume = (float)((v + (1 << 23)) >> 24);
3976 chain.clear();
3977 }
3978
3979 // prepare a new state to push
3980 FastMixerStateQueue *sq = NULL;
3981 FastMixerState *state = NULL;
3982 bool didModify = false;
3983 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003984 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003985 sq = mFastMixer->sq();
3986 state = sq->begin();
3987 }
3988
Andy Hung69aed5f2014-02-25 17:24:40 -08003989 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003990 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003991
Eric Laurent81784c32012-11-19 14:55:58 -08003992 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07003993 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003994
3995 // this const just means the local variable doesn't change
3996 Track* const track = t.get();
3997
3998 // process fast tracks
3999 if (track->isFastTrack()) {
4000
4001 // It's theoretically possible (though unlikely) for a fast track to be created
4002 // and then removed within the same normal mix cycle. This is not a problem, as
4003 // the track never becomes active so it's fast mixer slot is never touched.
4004 // The converse, of removing an (active) track and then creating a new track
4005 // at the identical fast mixer slot within the same normal mix cycle,
4006 // is impossible because the slot isn't marked available until the end of each cycle.
4007 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004008 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004009 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4010 FastTrack *fastTrack = &state->mFastTracks[j];
4011
4012 // Determine whether the track is currently in underrun condition,
4013 // and whether it had a recent underrun.
4014 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4015 FastTrackUnderruns underruns = ftDump->mUnderruns;
4016 uint32_t recentFull = (underruns.mBitFields.mFull -
4017 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4018 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4019 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4020 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4021 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4022 uint32_t recentUnderruns = recentPartial + recentEmpty;
4023 track->mObservedUnderruns = underruns;
4024 // don't count underruns that occur while stopping or pausing
4025 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004026 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4027 recentUnderruns > 0) {
4028 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4029 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004030 } else {
4031 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004032 }
4033
4034 // This is similar to the state machine for normal tracks,
4035 // with a few modifications for fast tracks.
4036 bool isActive = true;
4037 switch (track->mState) {
4038 case TrackBase::STOPPING_1:
4039 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004040 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004041 track->mState = TrackBase::STOPPING_2;
4042 }
4043 break;
4044 case TrackBase::PAUSING:
4045 // ramp down is not yet implemented
4046 track->setPaused();
4047 break;
4048 case TrackBase::RESUMING:
4049 // ramp up is not yet implemented
4050 track->mState = TrackBase::ACTIVE;
4051 break;
4052 case TrackBase::ACTIVE:
4053 if (recentFull > 0 || recentPartial > 0) {
4054 // track has provided at least some frames recently: reset retry count
4055 track->mRetryCount = kMaxTrackRetries;
4056 }
4057 if (recentUnderruns == 0) {
4058 // no recent underruns: stay active
4059 break;
4060 }
4061 // there has recently been an underrun of some kind
4062 if (track->sharedBuffer() == 0) {
4063 // were any of the recent underruns "empty" (no frames available)?
4064 if (recentEmpty == 0) {
4065 // no, then ignore the partial underruns as they are allowed indefinitely
4066 break;
4067 }
4068 // there has recently been an "empty" underrun: decrement the retry counter
4069 if (--(track->mRetryCount) > 0) {
4070 break;
4071 }
4072 // indicate to client process that the track was disabled because of underrun;
4073 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004074 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004075 // remove from active list, but state remains ACTIVE [confusing but true]
4076 isActive = false;
4077 break;
4078 }
4079 // fall through
4080 case TrackBase::STOPPING_2:
4081 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004082 case TrackBase::STOPPED:
4083 case TrackBase::FLUSHED: // flush() while active
4084 // Check for presentation complete if track is inactive
4085 // We have consumed all the buffers of this track.
4086 // This would be incomplete if we auto-paused on underrun
4087 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004088 uint32_t latency = 0;
4089 status_t result = mOutput->stream->getLatency(&latency);
4090 ALOGE_IF(result != OK,
4091 "Error when retrieving output stream latency: %d", result);
4092 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004093 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004094 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4095 // track stays in active list until presentation is complete
4096 break;
4097 }
4098 }
4099 if (track->isStopping_2()) {
4100 track->mState = TrackBase::STOPPED;
4101 }
4102 if (track->isStopped()) {
4103 // Can't reset directly, as fast mixer is still polling this track
4104 // track->reset();
4105 // So instead mark this track as needing to be reset after push with ack
4106 resetMask |= 1 << i;
4107 }
4108 isActive = false;
4109 break;
4110 case TrackBase::IDLE:
4111 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004112 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004113 }
4114
4115 if (isActive) {
4116 // was it previously inactive?
4117 if (!(state->mTrackMask & (1 << j))) {
4118 ExtendedAudioBufferProvider *eabp = track;
4119 VolumeProvider *vp = track;
4120 fastTrack->mBufferProvider = eabp;
4121 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004122 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004123 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004124 fastTrack->mGeneration++;
4125 state->mTrackMask |= 1 << j;
4126 didModify = true;
4127 // no acknowledgement required for newly active tracks
4128 }
4129 // cache the combined master volume and stream type volume for fast mixer; this
4130 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004131 const float vh = track->getVolumeHandler()->getVolume(
4132 track->mAudioTrackServerProxy->framesReleased());
4133 track->mCachedVolume = masterVolume
4134 * mStreamTypes[track->streamType()].volume
4135 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004136 ++fastTracks;
4137 } else {
4138 // was it previously active?
4139 if (state->mTrackMask & (1 << j)) {
4140 fastTrack->mBufferProvider = NULL;
4141 fastTrack->mGeneration++;
4142 state->mTrackMask &= ~(1 << j);
4143 didModify = true;
4144 // If any fast tracks were removed, we must wait for acknowledgement
4145 // because we're about to decrement the last sp<> on those tracks.
4146 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4147 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004148 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4149 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4150 j, track->mState, state->mTrackMask, recentUnderruns,
4151 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004152 }
4153 tracksToRemove->add(track);
4154 // Avoids a misleading display in dumpsys
4155 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4156 }
4157 continue;
4158 }
4159
4160 { // local variable scope to avoid goto warning
4161
4162 audio_track_cblk_t* cblk = track->cblk();
4163
4164 // The first time a track is added we wait
4165 // for all its buffers to be filled before processing it
4166 int name = track->name();
4167 // make sure that we have enough frames to mix one full buffer.
4168 // enforce this condition only once to enable draining the buffer in case the client
4169 // app does not call stop() and relies on underrun to stop:
4170 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4171 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004172 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004173 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004174 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004175
4176 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004177 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004178 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4179 // add frames already consumed but not yet released by the resampler
4180 // because mAudioTrackServerProxy->framesReady() will include these frames
4181 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4182
Eric Laurent81784c32012-11-19 14:55:58 -08004183 uint32_t minFrames = 1;
4184 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4185 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004186 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004187 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004188
4189 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004190 if (ATRACE_ENABLED()) {
4191 // I wish we had formatted trace names
4192 char traceName[16];
4193 strcpy(traceName, "nRdy");
4194 int name = track->name();
4195 if (AudioMixer::TRACK0 <= name &&
4196 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4197 name -= AudioMixer::TRACK0;
4198 traceName[4] = (name / 10) + '0';
4199 traceName[5] = (name % 10) + '0';
4200 } else {
4201 traceName[4] = '?';
4202 traceName[5] = '?';
4203 }
4204 traceName[6] = '\0';
4205 ATRACE_INT(traceName, framesReady);
4206 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004207 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004208 !track->isPaused() && !track->isTerminated())
4209 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004210 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004211
4212 mixedTracks++;
4213
Andy Hung69aed5f2014-02-25 17:24:40 -08004214 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4215 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004216 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004217 if (track->mainBuffer() != mSinkBuffer &&
4218 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004219 if (mEffectBufferEnabled) {
4220 mEffectBufferValid = true; // Later can set directly.
4221 }
Eric Laurent81784c32012-11-19 14:55:58 -08004222 chain = getEffectChain_l(track->sessionId());
4223 // Delegate volume control to effect in track effect chain if needed
4224 if (chain != 0) {
4225 tracksWithEffect++;
4226 } else {
4227 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4228 "session %d",
4229 name, track->sessionId());
4230 }
4231 }
4232
4233
4234 int param = AudioMixer::VOLUME;
4235 if (track->mFillingUpStatus == Track::FS_FILLED) {
4236 // no ramp for the first volume setting
4237 track->mFillingUpStatus = Track::FS_ACTIVE;
4238 if (track->mState == TrackBase::RESUMING) {
4239 track->mState = TrackBase::ACTIVE;
4240 param = AudioMixer::RAMP_VOLUME;
4241 }
4242 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004243 // FIXME should not make a decision based on mServer
4244 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004245 // If the track is stopped before the first frame was mixed,
4246 // do not apply ramp
4247 param = AudioMixer::RAMP_VOLUME;
4248 }
4249
4250 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004251 uint32_t vl, vr; // in U8.24 integer format
4252 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004253 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004254 vl = vr = 0;
4255 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004256 if (track->isPausing()) {
4257 track->setPaused();
4258 }
4259 } else {
4260
4261 // read original volumes with volume control
4262 float typeVolume = mStreamTypes[track->streamType()].volume;
4263 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004264 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004265 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004266 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4267 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004268 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004269 if (vlf > GAIN_FLOAT_UNITY) {
4270 ALOGV("Track left volume out of range: %.3g", vlf);
4271 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004272 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004273 if (vrf > GAIN_FLOAT_UNITY) {
4274 ALOGV("Track right volume out of range: %.3g", vrf);
4275 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004276 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004277 const float vh = track->getVolumeHandler()->getVolume(
4278 track->mAudioTrackServerProxy->framesReleased());
4279 // now apply the master volume and stream type volume and shaper volume
4280 vlf *= v * vh;
4281 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004282 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004283 // then derive vl and vr as U8.24 versions for the effect chain
4284 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4285 vl = (uint32_t) (scaleto8_24 * vlf);
4286 vr = (uint32_t) (scaleto8_24 * vrf);
4287 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004288 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004289 // send level comes from shared memory and so may be corrupt
4290 if (sendLevel > MAX_GAIN_INT) {
4291 ALOGV("Track send level out of range: %04X", sendLevel);
4292 sendLevel = MAX_GAIN_INT;
4293 }
Andy Hung6be49402014-05-30 10:42:03 -07004294 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4295 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004296 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004297
Eric Laurent81784c32012-11-19 14:55:58 -08004298 // Delegate volume control to effect in track effect chain if needed
4299 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4300 // Do not ramp volume if volume is controlled by effect
4301 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004302 // Update remaining floating point volume levels
4303 vlf = (float)vl / (1 << 24);
4304 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004305 track->mHasVolumeController = true;
4306 } else {
4307 // force no volume ramp when volume controller was just disabled or removed
4308 // from effect chain to avoid volume spike
4309 if (track->mHasVolumeController) {
4310 param = AudioMixer::VOLUME;
4311 }
4312 track->mHasVolumeController = false;
4313 }
4314
Eric Laurent81784c32012-11-19 14:55:58 -08004315 // XXX: these things DON'T need to be done each time
4316 mAudioMixer->setBufferProvider(name, track);
4317 mAudioMixer->enable(name);
4318
Andy Hung6be49402014-05-30 10:42:03 -07004319 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4320 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4321 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004322 mAudioMixer->setParameter(
4323 name,
4324 AudioMixer::TRACK,
4325 AudioMixer::FORMAT, (void *)track->format());
4326 mAudioMixer->setParameter(
4327 name,
4328 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004329 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004330 mAudioMixer->setParameter(
4331 name,
4332 AudioMixer::TRACK,
4333 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004334 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004335 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004336 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004337 if (reqSampleRate == 0) {
4338 reqSampleRate = mSampleRate;
4339 } else if (reqSampleRate > maxSampleRate) {
4340 reqSampleRate = maxSampleRate;
4341 }
Eric Laurent81784c32012-11-19 14:55:58 -08004342 mAudioMixer->setParameter(
4343 name,
4344 AudioMixer::RESAMPLE,
4345 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004346 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004347
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004348 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004349 mAudioMixer->setParameter(
4350 name,
4351 AudioMixer::TIMESTRETCH,
4352 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004353 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004354
Andy Hung69aed5f2014-02-25 17:24:40 -08004355 /*
4356 * Select the appropriate output buffer for the track.
4357 *
Andy Hung98ef9782014-03-04 14:46:50 -08004358 * Tracks with effects go into their own effects chain buffer
4359 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004360 *
4361 * Other tracks can use mMixerBuffer for higher precision
4362 * channel accumulation. If this buffer is enabled
4363 * (mMixerBufferEnabled true), then selected tracks will accumulate
4364 * into it.
4365 *
4366 */
4367 if (mMixerBufferEnabled
4368 && (track->mainBuffer() == mSinkBuffer
4369 || track->mainBuffer() == mMixerBuffer)) {
4370 mAudioMixer->setParameter(
4371 name,
4372 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004373 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004374 mAudioMixer->setParameter(
4375 name,
4376 AudioMixer::TRACK,
4377 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4378 // TODO: override track->mainBuffer()?
4379 mMixerBufferValid = true;
4380 } else {
4381 mAudioMixer->setParameter(
4382 name,
4383 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004384 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004385 mAudioMixer->setParameter(
4386 name,
4387 AudioMixer::TRACK,
4388 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4389 }
Eric Laurent81784c32012-11-19 14:55:58 -08004390 mAudioMixer->setParameter(
4391 name,
4392 AudioMixer::TRACK,
4393 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4394
4395 // reset retry count
4396 track->mRetryCount = kMaxTrackRetries;
4397
4398 // If one track is ready, set the mixer ready if:
4399 // - the mixer was not ready during previous round OR
4400 // - no other track is not ready
4401 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4402 mixerStatus != MIXER_TRACKS_ENABLED) {
4403 mixerStatus = MIXER_TRACKS_READY;
4404 }
4405 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004406 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004407 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4408 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004409 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004410 } else {
4411 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004412 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004413
Eric Laurent81784c32012-11-19 14:55:58 -08004414 // clear effect chain input buffer if an active track underruns to avoid sending
4415 // previous audio buffer again to effects
4416 chain = getEffectChain_l(track->sessionId());
4417 if (chain != 0) {
4418 chain->clearInputBuffer();
4419 }
4420
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004421 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004422 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4423 track->isStopped() || track->isPaused()) {
4424 // We have consumed all the buffers of this track.
4425 // Remove it from the list of active tracks.
4426 // TODO: use actual buffer filling status instead of latency when available from
4427 // audio HAL
4428 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004429 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004430 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4431 if (track->isStopped()) {
4432 track->reset();
4433 }
4434 tracksToRemove->add(track);
4435 }
4436 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004437 // No buffers for this track. Give it a few chances to
4438 // fill a buffer, then remove it from active list.
4439 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004440 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004441 tracksToRemove->add(track);
4442 // indicate to client process that the track was disabled because of underrun;
4443 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004444 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004445 // If one track is not ready, mark the mixer also not ready if:
4446 // - the mixer was ready during previous round OR
4447 // - no other track is ready
4448 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4449 mixerStatus != MIXER_TRACKS_READY) {
4450 mixerStatus = MIXER_TRACKS_ENABLED;
4451 }
4452 }
4453 mAudioMixer->disable(name);
4454 }
4455
4456 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004457
4458 }
4459
4460 // Push the new FastMixer state if necessary
4461 bool pauseAudioWatchdog = false;
4462 if (didModify) {
4463 state->mFastTracksGen++;
4464 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4465 if (kUseFastMixer == FastMixer_Dynamic &&
4466 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4467 state->mCommand = FastMixerState::COLD_IDLE;
4468 state->mColdFutexAddr = &mFastMixerFutex;
4469 state->mColdGen++;
4470 mFastMixerFutex = 0;
4471 if (kUseFastMixer == FastMixer_Dynamic) {
4472 mNormalSink = mOutputSink;
4473 }
4474 // If we go into cold idle, need to wait for acknowledgement
4475 // so that fast mixer stops doing I/O.
4476 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4477 pauseAudioWatchdog = true;
4478 }
Eric Laurent81784c32012-11-19 14:55:58 -08004479 }
4480 if (sq != NULL) {
4481 sq->end(didModify);
4482 sq->push(block);
4483 }
4484#ifdef AUDIO_WATCHDOG
4485 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4486 mAudioWatchdog->pause();
4487 }
4488#endif
4489
4490 // Now perform the deferred reset on fast tracks that have stopped
4491 while (resetMask != 0) {
4492 size_t i = __builtin_ctz(resetMask);
4493 ALOG_ASSERT(i < count);
4494 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004495 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004496 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4497 track->reset();
4498 }
4499
4500 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004501 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004502
Eric Laurent97d547d2014-09-02 14:45:53 -07004503 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4504 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004505 }
4506
4507 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004508 // as long as there are effects we should clear the effects buffer, to avoid
4509 // passing a non-clean buffer to the effect chain
4510 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004511 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004512 // sink or mix buffer must be cleared if all tracks are connected to an
4513 // effect chain as in this case the mixer will not write to the sink or mix buffer
4514 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004515 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4516 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004517 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004518 if (mMixerBufferValid) {
4519 memset(mMixerBuffer, 0, mMixerBufferSize);
4520 // TODO: In testing, mSinkBuffer below need not be cleared because
4521 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4522 // after mixing.
4523 //
4524 // To enforce this guarantee:
4525 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4526 // (mixedTracks == 0 && fastTracks > 0))
4527 // must imply MIXER_TRACKS_READY.
4528 // Later, we may clear buffers regardless, and skip much of this logic.
4529 }
Andy Hung98ef9782014-03-04 14:46:50 -08004530 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004531 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004532 }
4533
4534 // if any fast tracks, then status is ready
4535 mMixerStatusIgnoringFastTracks = mixerStatus;
4536 if (fastTracks > 0) {
4537 mixerStatus = MIXER_TRACKS_READY;
4538 }
4539 return mixerStatus;
4540}
4541
Eric Laurentad7dd962016-09-22 12:38:37 -07004542// trackCountForUid_l() must be called with ThreadBase::mLock held
4543uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4544{
4545 uint32_t trackCount = 0;
4546 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004547 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004548 trackCount++;
4549 }
4550 }
4551 return trackCount;
4552}
4553
Eric Laurent81784c32012-11-19 14:55:58 -08004554// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004555int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004556 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004557{
Eric Laurentad7dd962016-09-22 12:38:37 -07004558 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4559 return -1;
4560 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004561 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004562}
4563
4564// deleteTrackName_l() must be called with ThreadBase::mLock held
4565void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4566{
4567 ALOGV("remove track (%d) and delete from mixer", name);
4568 mAudioMixer->deleteTrackName(name);
4569}
4570
Eric Laurent10351942014-05-08 18:49:52 -07004571// checkForNewParameter_l() must be called with ThreadBase::mLock held
4572bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4573 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004574{
Eric Laurent81784c32012-11-19 14:55:58 -08004575 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004576 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004577
Eric Laurent10351942014-05-08 18:49:52 -07004578 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004579
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004580 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004581
Eric Laurent10351942014-05-08 18:49:52 -07004582 AudioParameter param = AudioParameter(keyValuePair);
4583 int value;
4584 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4585 reconfig = true;
4586 }
4587 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004588 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004589 status = BAD_VALUE;
4590 } else {
4591 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004592 reconfig = true;
4593 }
Eric Laurent10351942014-05-08 18:49:52 -07004594 }
4595 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004596 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004597 status = BAD_VALUE;
4598 } else {
4599 // no need to save value, since it's constant
4600 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004601 }
Eric Laurent10351942014-05-08 18:49:52 -07004602 }
4603 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4604 // do not accept frame count changes if tracks are open as the track buffer
4605 // size depends on frame count and correct behavior would not be guaranteed
4606 // if frame count is changed after track creation
4607 if (!mTracks.isEmpty()) {
4608 status = INVALID_OPERATION;
4609 } else {
4610 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004611 }
Eric Laurent10351942014-05-08 18:49:52 -07004612 }
4613 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004614#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004615 // when changing the audio output device, call addBatteryData to notify
4616 // the change
4617 if (mOutDevice != value) {
4618 uint32_t params = 0;
4619 // check whether speaker is on
4620 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4621 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004622 }
Eric Laurent10351942014-05-08 18:49:52 -07004623
4624 audio_devices_t deviceWithoutSpeaker
4625 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4626 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004627 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004628 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4629 }
4630
4631 if (params != 0) {
4632 addBatteryData(params);
4633 }
4634 }
Eric Laurent81784c32012-11-19 14:55:58 -08004635#endif
4636
Eric Laurent10351942014-05-08 18:49:52 -07004637 // forward device change to effects that have requested to be
4638 // aware of attached audio device.
4639 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004640 a2dpDeviceChanged =
4641 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004642 mOutDevice = value;
4643 for (size_t i = 0; i < mEffectChains.size(); i++) {
4644 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004645 }
4646 }
Eric Laurent10351942014-05-08 18:49:52 -07004647 }
Eric Laurent81784c32012-11-19 14:55:58 -08004648
Eric Laurent10351942014-05-08 18:49:52 -07004649 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004650 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004651 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004652 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004653 mStandby = true;
4654 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004655 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004656 }
Eric Laurent10351942014-05-08 18:49:52 -07004657 if (status == NO_ERROR && reconfig) {
4658 readOutputParameters_l();
4659 delete mAudioMixer;
4660 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4661 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004662 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004663 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004664 if (name < 0) {
4665 break;
4666 }
4667 mTracks[i]->mName = name;
4668 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004669 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004670 }
Eric Laurent81784c32012-11-19 14:55:58 -08004671 }
4672
Eric Laurent42537be2016-01-08 17:16:42 -08004673 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004674}
4675
4676
4677void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4678{
Eric Laurent81784c32012-11-19 14:55:58 -08004679 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004680 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004681 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004682 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004683
4684 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004685 // while we are dumping it. It may be inconsistent, but it won't mutate!
4686 // This is a large object so we place it on the heap.
4687 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4688 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4689 copy->dump(fd);
4690 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004691
4692#ifdef STATE_QUEUE_DUMP
4693 // Similar for state queue
4694 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4695 observerCopy.dump(fd);
4696 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4697 mutatorCopy.dump(fd);
4698#endif
4699
Glenn Kasten46909e72013-02-26 09:20:22 -08004700#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004701 // Write the tee output to a .wav file
4702 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004703#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004704
4705#ifdef AUDIO_WATCHDOG
4706 if (mAudioWatchdog != 0) {
4707 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4708 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4709 wdCopy.dump(fd);
4710 }
4711#endif
4712}
4713
4714uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4715{
4716 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4717}
4718
4719uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4720{
4721 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4722}
4723
4724void AudioFlinger::MixerThread::cacheParameters_l()
4725{
4726 PlaybackThread::cacheParameters_l();
4727
4728 // FIXME: Relaxed timing because of a certain device that can't meet latency
4729 // Should be reduced to 2x after the vendor fixes the driver issue
4730 // increase threshold again due to low power audio mode. The way this warning
4731 // threshold is calculated and its usefulness should be reconsidered anyway.
4732 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4733}
4734
4735// ----------------------------------------------------------------------------
4736
4737AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004738 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4739 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004740 // mLeftVolFloat, mRightVolFloat
4741{
4742}
4743
Eric Laurentbfb1b832013-01-07 09:53:42 -08004744AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4745 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004746 ThreadBase::type_t type, bool systemReady)
4747 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004748 // mLeftVolFloat, mRightVolFloat
4749{
4750}
4751
Eric Laurent81784c32012-11-19 14:55:58 -08004752AudioFlinger::DirectOutputThread::~DirectOutputThread()
4753{
4754}
4755
Eric Laurent5850c4c2016-11-10 13:04:31 -08004756void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004757{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004758 float left, right;
4759
4760 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4761 left = right = 0;
4762 } else {
4763 float typeVolume = mStreamTypes[track->streamType()].volume;
4764 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004765 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004766
4767 if (audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4768 const float vh = track->getVolumeHandler()->getVolume(
4769 track->mAudioTrackServerProxy->framesReleased());
4770 v *= vh;
4771 } else {
4772 // TODO: implement volume scaling in HW
4773 }
4774
Glenn Kastenc56f3422014-03-21 17:53:17 -07004775 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4776 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4777 if (left > GAIN_FLOAT_UNITY) {
4778 left = GAIN_FLOAT_UNITY;
4779 }
4780 left *= v;
4781 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4782 if (right > GAIN_FLOAT_UNITY) {
4783 right = GAIN_FLOAT_UNITY;
4784 }
4785 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004786 }
4787
4788 if (lastTrack) {
4789 if (left != mLeftVolFloat || right != mRightVolFloat) {
4790 mLeftVolFloat = left;
4791 mRightVolFloat = right;
4792
4793 // Convert volumes from float to 8.24
4794 uint32_t vl = (uint32_t)(left * (1 << 24));
4795 uint32_t vr = (uint32_t)(right * (1 << 24));
4796
4797 // Delegate volume control to effect in track effect chain if needed
4798 // only one effect chain can be present on DirectOutputThread, so if
4799 // there is one, the track is connected to it
4800 if (!mEffectChains.isEmpty()) {
4801 mEffectChains[0]->setVolume_l(&vl, &vr);
4802 left = (float)vl / (1 << 24);
4803 right = (float)vr / (1 << 24);
4804 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004805 status_t result = mOutput->stream->setVolume(left, right);
4806 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004807 }
4808 }
4809}
4810
Phil Burk43b4dcc2015-06-09 16:53:44 -07004811void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4812{
4813 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004814 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004815
Eric Laurent0f0631e2015-07-06 18:01:25 -07004816 if (previousTrack != 0 && latestTrack != 0) {
4817 if (mType == DIRECT) {
4818 if (previousTrack.get() != latestTrack.get()) {
4819 mFlushPending = true;
4820 }
4821 } else /* mType == OFFLOAD */ {
4822 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4823 mFlushPending = true;
4824 }
4825 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004826 }
4827 PlaybackThread::onAddNewTrack_l();
4828}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004829
Eric Laurent81784c32012-11-19 14:55:58 -08004830AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4831 Vector< sp<Track> > *tracksToRemove
4832)
4833{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004834 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004835 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004836 bool doHwPause = false;
4837 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004838
4839 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004840 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004841 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004842 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004843 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004844 continue;
4845 }
4846
Eric Laurent5850c4c2016-11-10 13:04:31 -08004847 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004848#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004849 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004850#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004851 // Only consider last track started for volume and mixer state control.
4852 // In theory an older track could underrun and restart after the new one starts
4853 // but as we only care about the transition phase between two tracks on a
4854 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004855 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004856 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004857
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004858 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004859 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004860 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004861 doHwPause = true;
4862 mHwPaused = true;
4863 }
4864 tracksToRemove->add(track);
4865 } else if (track->isFlushPending()) {
4866 track->flushAck();
4867 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004868 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004869 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004870 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004871 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004872 if (last) {
4873 mLeftVolFloat = mRightVolFloat = -1.0;
4874 if (mHwPaused) {
4875 doHwResume = true;
4876 mHwPaused = false;
4877 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004878 }
4879 }
4880
Eric Laurent81784c32012-11-19 14:55:58 -08004881 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004882 // for all its buffers to be filled before processing it.
4883 // Allow draining the buffer in case the client
4884 // app does not call stop() and relies on underrun to stop:
4885 // hence the test on (track->mRetryCount > 1).
4886 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004887 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004888 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004889 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004890 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004891 minFrames = mNormalFrameCount;
4892 } else {
4893 minFrames = 1;
4894 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004895
Eric Laurentab5cdba2014-06-09 17:22:27 -07004896 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4897 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004898 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004899 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004900
4901 if (track->mFillingUpStatus == Track::FS_FILLED) {
4902 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004903 if (last) {
4904 // make sure processVolume_l() will apply new volume even if 0
4905 mLeftVolFloat = mRightVolFloat = -1.0;
4906 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004907 if (!mHwSupportsPause) {
4908 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004909 }
4910 }
4911
4912 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004913 processVolume_l(track, last);
4914 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004915 sp<Track> previousTrack = mPreviousTrack.promote();
4916 if (previousTrack != 0) {
4917 if (track != previousTrack.get()) {
4918 // Flush any data still being written from last track
4919 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004920 // Invalidate previous track to force a seek when resuming.
4921 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004922 }
4923 }
4924 mPreviousTrack = track;
4925
Eric Laurentd595b7c2013-04-03 17:27:56 -07004926 // reset retry count
4927 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004928 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004929 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004930 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004931 doHwResume = true;
4932 mHwPaused = false;
4933 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004934 }
Eric Laurent81784c32012-11-19 14:55:58 -08004935 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004936 // clear effect chain input buffer if the last active track started underruns
4937 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004938 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004939 mEffectChains[0]->clearInputBuffer();
4940 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004941 if (track->isStopping_1()) {
4942 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004943 if (last && mHwPaused) {
4944 doHwResume = true;
4945 mHwPaused = false;
4946 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004947 }
4948 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4949 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004950 // We have consumed all the buffers of this track.
4951 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004952 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004953 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004954 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4955 } else {
4956 audioHALFrames = 0;
4957 }
4958
Andy Hung818e7a32016-02-16 18:08:07 -08004959 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004960 if (mStandby || !last ||
4961 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004962 if (track->isStopping_2()) {
4963 track->mState = TrackBase::STOPPED;
4964 }
Eric Laurent81784c32012-11-19 14:55:58 -08004965 if (track->isStopped()) {
4966 track->reset();
4967 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004968 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004969 }
4970 } else {
4971 // No buffers for this track. Give it a few chances to
4972 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004973 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004974 if (--(track->mRetryCount) <= 0) {
4975 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004976 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004977 // indicate to client process that the track was disabled because of underrun;
4978 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004979 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004980 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004981 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4982 "minFrames = %u, mFormat = %#x",
4983 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004984 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004985 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004986 doHwPause = true;
4987 mHwPaused = true;
4988 }
Eric Laurent81784c32012-11-19 14:55:58 -08004989 }
4990 }
4991 }
4992 }
4993
Eric Laurentd1f69b02014-12-15 14:33:13 -08004994 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004995 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004996 for (size_t i = 0; i < mTracks.size(); i++) {
4997 if (mTracks[i]->isFlushPending()) {
4998 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004999 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005000 }
5001 }
5002 }
5003
5004 // make sure the pause/flush/resume sequence is executed in the right order.
5005 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5006 // before flush and then resume HW. This can happen in case of pause/flush/resume
5007 // if resume is received before pause is executed.
5008 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005009 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005010 status_t result = mOutput->stream->pause();
5011 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005012 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005013 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005014 flushHw_l();
5015 }
5016 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005017 status_t result = mOutput->stream->resume();
5018 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005019 }
Eric Laurent81784c32012-11-19 14:55:58 -08005020 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005021 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005022
5023 return mixerStatus;
5024}
5025
5026void AudioFlinger::DirectOutputThread::threadLoop_mix()
5027{
Eric Laurent81784c32012-11-19 14:55:58 -08005028 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005029 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005030 // output audio to hardware
5031 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005032 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005033 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005034 status_t status = mActiveTrack->getNextBuffer(&buffer);
5035 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005036 // no need to pad with 0 for compressed audio
5037 if (audio_has_proportional_frames(mFormat)) {
5038 memset(curBuf, 0, frameCount * mFrameSize);
5039 }
Eric Laurent81784c32012-11-19 14:55:58 -08005040 break;
5041 }
5042 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5043 frameCount -= buffer.frameCount;
5044 curBuf += buffer.frameCount * mFrameSize;
5045 mActiveTrack->releaseBuffer(&buffer);
5046 }
Andy Hung2098f272014-02-27 14:00:06 -08005047 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005048 mSleepTimeUs = 0;
5049 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005050 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005051}
5052
5053void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5054{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005055 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005056 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005057 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005058 return;
5059 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005060 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005061 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005062 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005063 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005064 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005065 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005066 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005067 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005068 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005069 }
5070}
5071
Eric Laurentd1f69b02014-12-15 14:33:13 -08005072void AudioFlinger::DirectOutputThread::threadLoop_exit()
5073{
5074 {
5075 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005076 for (size_t i = 0; i < mTracks.size(); i++) {
5077 if (mTracks[i]->isFlushPending()) {
5078 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005079 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005080 }
5081 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005082 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005083 flushHw_l();
5084 }
5085 }
5086 PlaybackThread::threadLoop_exit();
5087}
5088
5089// must be called with thread mutex locked
5090bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5091{
5092 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005093 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005094
vivek mehta9cd7ad12016-03-17 00:18:29 -07005095 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5096 return !mStandby;
5097 }
5098
Eric Laurentd1f69b02014-12-15 14:33:13 -08005099 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5100 // after a timeout and we will enter standby then.
5101 if (mTracks.size() > 0) {
5102 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005103 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5104 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005105 }
5106
Eric Laurent5cff4032015-05-26 13:49:58 -07005107 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005108}
5109
Eric Laurent81784c32012-11-19 14:55:58 -08005110// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005111int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005112 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005113{
Eric Laurentad7dd962016-09-22 12:38:37 -07005114 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5115 return -1;
5116 }
Eric Laurent81784c32012-11-19 14:55:58 -08005117 return 0;
5118}
5119
5120// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005121void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005122{
5123}
5124
Eric Laurent10351942014-05-08 18:49:52 -07005125// checkForNewParameter_l() must be called with ThreadBase::mLock held
5126bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5127 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005128{
5129 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005130 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005131
Eric Laurent10351942014-05-08 18:49:52 -07005132 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005133
Eric Laurent10351942014-05-08 18:49:52 -07005134 AudioParameter param = AudioParameter(keyValuePair);
5135 int value;
5136 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5137 // forward device change to effects that have requested to be
5138 // aware of attached audio device.
5139 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005140 a2dpDeviceChanged =
5141 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005142 mOutDevice = value;
5143 for (size_t i = 0; i < mEffectChains.size(); i++) {
5144 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005145 }
5146 }
Eric Laurent81784c32012-11-19 14:55:58 -08005147 }
Eric Laurent10351942014-05-08 18:49:52 -07005148 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5149 // do not accept frame count changes if tracks are open as the track buffer
5150 // size depends on frame count and correct behavior would not be garantied
5151 // if frame count is changed after track creation
5152 if (!mTracks.isEmpty()) {
5153 status = INVALID_OPERATION;
5154 } else {
5155 reconfig = true;
5156 }
5157 }
5158 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005159 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005160 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005161 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005162 mStandby = true;
5163 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005164 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005165 }
5166 if (status == NO_ERROR && reconfig) {
5167 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005168 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005169 }
5170 }
5171
Eric Laurent42537be2016-01-08 17:16:42 -08005172 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005173}
5174
5175uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5176{
5177 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005178 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005179 time = PlaybackThread::activeSleepTimeUs();
5180 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005181 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005182 }
5183 return time;
5184}
5185
5186uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5187{
5188 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005189 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005190 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5191 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005192 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005193 }
5194 return time;
5195}
5196
5197uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5198{
5199 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005200 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005201 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5202 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005203 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005204 }
5205 return time;
5206}
5207
5208void AudioFlinger::DirectOutputThread::cacheParameters_l()
5209{
5210 PlaybackThread::cacheParameters_l();
5211
5212 // use shorter standby delay as on normal output to release
5213 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005214 // no delay on outputs with HW A/V sync
5215 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005216 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005217 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005218 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005219 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005220 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005221 }
Eric Laurent81784c32012-11-19 14:55:58 -08005222}
5223
Eric Laurente659ef42014-09-29 13:06:46 -07005224void AudioFlinger::DirectOutputThread::flushHw_l()
5225{
Phil Burk062e67a2015-02-11 13:40:50 -08005226 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005227 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005228 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005229}
5230
Eric Laurent81784c32012-11-19 14:55:58 -08005231// ----------------------------------------------------------------------------
5232
Eric Laurentbfb1b832013-01-07 09:53:42 -08005233AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005234 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005236 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005237 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005238 mDrainSequence(0),
5239 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005240{
5241}
5242
5243AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5244{
5245}
5246
5247void AudioFlinger::AsyncCallbackThread::onFirstRef()
5248{
5249 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5250}
5251
5252bool AudioFlinger::AsyncCallbackThread::threadLoop()
5253{
5254 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005255 uint32_t writeAckSequence;
5256 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005257 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005258
5259 {
5260 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005261 while (!((mWriteAckSequence & 1) ||
5262 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005263 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005264 exitPending())) {
5265 mWaitWorkCV.wait(mLock);
5266 }
5267
Eric Laurentbfb1b832013-01-07 09:53:42 -08005268 if (exitPending()) {
5269 break;
5270 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005271 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5272 mWriteAckSequence, mDrainSequence);
5273 writeAckSequence = mWriteAckSequence;
5274 mWriteAckSequence &= ~1;
5275 drainSequence = mDrainSequence;
5276 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005277 asyncError = mAsyncError;
5278 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005279 }
5280 {
Eric Laurent4de95592013-09-26 15:28:21 -07005281 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5282 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005283 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005284 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005285 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005286 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005287 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005288 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005289 if (asyncError) {
5290 playbackThread->onAsyncError();
5291 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005292 }
5293 }
5294 }
5295 return false;
5296}
5297
5298void AudioFlinger::AsyncCallbackThread::exit()
5299{
5300 ALOGV("AsyncCallbackThread::exit");
5301 Mutex::Autolock _l(mLock);
5302 requestExit();
5303 mWaitWorkCV.broadcast();
5304}
5305
Eric Laurent3b4529e2013-09-05 18:09:19 -07005306void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005307{
5308 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005309 // bit 0 is cleared
5310 mWriteAckSequence = sequence << 1;
5311}
5312
5313void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5314{
5315 Mutex::Autolock _l(mLock);
5316 // ignore unexpected callbacks
5317 if (mWriteAckSequence & 2) {
5318 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005319 mWaitWorkCV.signal();
5320 }
5321}
5322
Eric Laurent3b4529e2013-09-05 18:09:19 -07005323void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005324{
5325 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005326 // bit 0 is cleared
5327 mDrainSequence = sequence << 1;
5328}
5329
5330void AudioFlinger::AsyncCallbackThread::resetDraining()
5331{
5332 Mutex::Autolock _l(mLock);
5333 // ignore unexpected callbacks
5334 if (mDrainSequence & 2) {
5335 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005336 mWaitWorkCV.signal();
5337 }
5338}
5339
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005340void AudioFlinger::AsyncCallbackThread::setAsyncError()
5341{
5342 Mutex::Autolock _l(mLock);
5343 mAsyncError = true;
5344 mWaitWorkCV.signal();
5345}
5346
Eric Laurentbfb1b832013-01-07 09:53:42 -08005347
5348// ----------------------------------------------------------------------------
5349AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005350 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5351 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005352 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5353 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005354{
Eric Laurentfd477972013-10-25 18:10:40 -07005355 //FIXME: mStandby should be set to true by ThreadBase constructor
5356 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005357 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005358}
5359
Eric Laurentbfb1b832013-01-07 09:53:42 -08005360void AudioFlinger::OffloadThread::threadLoop_exit()
5361{
5362 if (mFlushPending || mHwPaused) {
5363 // If a flush is pending or track was paused, just discard buffered data
5364 flushHw_l();
5365 } else {
5366 mMixerStatus = MIXER_DRAIN_ALL;
5367 threadLoop_drain();
5368 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005369 if (mUseAsyncWrite) {
5370 ALOG_ASSERT(mCallbackThread != 0);
5371 mCallbackThread->exit();
5372 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005373 PlaybackThread::threadLoop_exit();
5374}
5375
5376AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5377 Vector< sp<Track> > *tracksToRemove
5378)
5379{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005380 size_t count = mActiveTracks.size();
5381
5382 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005383 bool doHwPause = false;
5384 bool doHwResume = false;
5385
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005386 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005387
Eric Laurentbfb1b832013-01-07 09:53:42 -08005388 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005389 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005390 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005391#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005392 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005393#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005394 // Only consider last track started for volume and mixer state control.
5395 // In theory an older track could underrun and restart after the new one starts
5396 // but as we only care about the transition phase between two tracks on a
5397 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005398 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005399 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005400
Haynes Mathew George7844f672014-01-15 12:32:55 -08005401 if (track->isInvalid()) {
5402 ALOGW("An invalidated track shouldn't be in active list");
5403 tracksToRemove->add(track);
5404 continue;
5405 }
5406
5407 if (track->mState == TrackBase::IDLE) {
5408 ALOGW("An idle track shouldn't be in active list");
5409 continue;
5410 }
5411
Eric Laurentbfb1b832013-01-07 09:53:42 -08005412 if (track->isPausing()) {
5413 track->setPaused();
5414 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005415 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005416 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005417 mHwPaused = true;
5418 }
5419 // If we were part way through writing the mixbuffer to
5420 // the HAL we must save this until we resume
5421 // BUG - this will be wrong if a different track is made active,
5422 // in that case we want to discard the pending data in the
5423 // mixbuffer and tell the client to present it again when the
5424 // track is resumed
5425 mPausedWriteLength = mCurrentWriteLength;
5426 mPausedBytesRemaining = mBytesRemaining;
5427 mBytesRemaining = 0; // stop writing
5428 }
5429 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005430 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005431 if (track->isStopping_1()) {
5432 track->mRetryCount = kMaxTrackStopRetriesOffload;
5433 } else {
5434 track->mRetryCount = kMaxTrackRetriesOffload;
5435 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005436 track->flushAck();
5437 if (last) {
5438 mFlushPending = true;
5439 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005440 } else if (track->isResumePending()){
5441 track->resumeAck();
5442 if (last) {
5443 if (mPausedBytesRemaining) {
5444 // Need to continue write that was interrupted
5445 mCurrentWriteLength = mPausedWriteLength;
5446 mBytesRemaining = mPausedBytesRemaining;
5447 mPausedBytesRemaining = 0;
5448 }
5449 if (mHwPaused) {
5450 doHwResume = true;
5451 mHwPaused = false;
5452 // threadLoop_mix() will handle the case that we need to
5453 // resume an interrupted write
5454 }
5455 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005456 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005457
Eric Laurent3df841a2016-07-15 15:15:40 -07005458 mLeftVolFloat = mRightVolFloat = -1.0;
5459
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005460 // Do not handle new data in this iteration even if track->framesReady()
5461 mixerStatus = MIXER_TRACKS_ENABLED;
5462 }
5463 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005464 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005465 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005466 if (track->mFillingUpStatus == Track::FS_FILLED) {
5467 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005468 if (last) {
5469 // make sure processVolume_l() will apply new volume even if 0
5470 mLeftVolFloat = mRightVolFloat = -1.0;
5471 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005472 }
5473
5474 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005475 sp<Track> previousTrack = mPreviousTrack.promote();
5476 if (previousTrack != 0) {
5477 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005478 // Flush any data still being written from last track
5479 mBytesRemaining = 0;
5480 if (mPausedBytesRemaining) {
5481 // Last track was paused so we also need to flush saved
5482 // mixbuffer state and invalidate track so that it will
5483 // re-submit that unwritten data when it is next resumed
5484 mPausedBytesRemaining = 0;
5485 // Invalidate is a bit drastic - would be more efficient
5486 // to have a flag to tell client that some of the
5487 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005488 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005489 }
5490 // flush data already sent to the DSP if changing audio session as audio
5491 // comes from a different source. Also invalidate previous track to force a
5492 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005493 if (previousTrack->sessionId() != track->sessionId()) {
5494 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005495 }
5496 }
5497 }
5498 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005499 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005500 if (track->isStopping_1()) {
5501 track->mRetryCount = kMaxTrackStopRetriesOffload;
5502 } else {
5503 track->mRetryCount = kMaxTrackRetriesOffload;
5504 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005505 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005506 mixerStatus = MIXER_TRACKS_READY;
5507 }
5508 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005509 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005510 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005511 if (--(track->mRetryCount) <= 0) {
5512 // Hardware buffer can hold a large amount of audio so we must
5513 // wait for all current track's data to drain before we say
5514 // that the track is stopped.
5515 if (mBytesRemaining == 0) {
5516 // Only start draining when all data in mixbuffer
5517 // has been written
5518 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5519 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5520 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5521 if (last && !mStandby) {
5522 // do not modify drain sequence if we are already draining. This happens
5523 // when resuming from pause after drain.
5524 if ((mDrainSequence & 1) == 0) {
5525 mSleepTimeUs = 0;
5526 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5527 mixerStatus = MIXER_DRAIN_TRACK;
5528 mDrainSequence += 2;
5529 }
5530 if (mHwPaused) {
5531 // It is possible to move from PAUSED to STOPPING_1 without
5532 // a resume so we must ensure hardware is running
5533 doHwResume = true;
5534 mHwPaused = false;
5535 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005536 }
5537 }
Eric Laurente93cc032016-05-05 10:15:10 -07005538 } else if (last) {
5539 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5540 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005541 }
5542 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005543 // Drain has completed or we are in standby, signal presentation complete
5544 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005545 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005546 uint32_t latency = 0;
5547 status_t result = mOutput->stream->getLatency(&latency);
5548 ALOGE_IF(result != OK,
5549 "Error when retrieving output stream latency: %d", result);
5550 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005551 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005552 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005553 track->presentationComplete(framesWritten, audioHALFrames);
5554 track->reset();
5555 tracksToRemove->add(track);
5556 }
5557 } else {
5558 // No buffers for this track. Give it a few chances to
5559 // fill a buffer, then remove it from active list.
5560 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005561 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005562 uint64_t position = 0;
5563 struct timespec unused;
5564 // The running check restarts the retry counter at least once.
5565 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5566 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5567 running = true;
5568 mOffloadUnderrunPosition = position;
5569 }
5570 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005571 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5572 (long long)position, (long long)mOffloadUnderrunPosition);
5573 }
5574 if (running) { // still running, give us more time.
5575 track->mRetryCount = kMaxTrackRetriesOffload;
5576 } else {
5577 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5578 track->name());
5579 tracksToRemove->add(track);
5580 // indicate to client process that the track was disabled because of underrun;
5581 // it will then automatically call start() when data is available
5582 track->disable();
5583 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005584 } else if (last){
5585 mixerStatus = MIXER_TRACKS_ENABLED;
5586 }
5587 }
5588 }
5589 // compute volume for this track
5590 processVolume_l(track, last);
5591 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005592
Eric Laurentea0fade2013-10-04 16:23:48 -07005593 // make sure the pause/flush/resume sequence is executed in the right order.
5594 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5595 // before flush and then resume HW. This can happen in case of pause/flush/resume
5596 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005597 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005598 status_t result = mOutput->stream->pause();
5599 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005600 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005601 if (mFlushPending) {
5602 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005603 }
Eric Laurentfd477972013-10-25 18:10:40 -07005604 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005605 status_t result = mOutput->stream->resume();
5606 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005607 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005608
Eric Laurentbfb1b832013-01-07 09:53:42 -08005609 // remove all the tracks that need to be...
5610 removeTracks_l(*tracksToRemove);
5611
5612 return mixerStatus;
5613}
5614
Eric Laurentbfb1b832013-01-07 09:53:42 -08005615// must be called with thread mutex locked
5616bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5617{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005618 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5619 mWriteAckSequence, mDrainSequence);
5620 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005621 return true;
5622 }
5623 return false;
5624}
5625
Eric Laurentbfb1b832013-01-07 09:53:42 -08005626bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5627{
5628 Mutex::Autolock _l(mLock);
5629 return waitingAsyncCallback_l();
5630}
5631
5632void AudioFlinger::OffloadThread::flushHw_l()
5633{
Eric Laurente659ef42014-09-29 13:06:46 -07005634 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005635 // Flush anything still waiting in the mixbuffer
5636 mCurrentWriteLength = 0;
5637 mBytesRemaining = 0;
5638 mPausedWriteLength = 0;
5639 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005640 // reset bytes written count to reflect that DSP buffers are empty after flush.
5641 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005642 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005643
Eric Laurentbfb1b832013-01-07 09:53:42 -08005644 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005645 // discard any pending drain or write ack by incrementing sequence
5646 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5647 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005648 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005649 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5650 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005651 }
5652}
5653
Haynes Mathew George05317d22016-05-03 16:34:26 -07005654void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5655{
5656 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005657 if (PlaybackThread::invalidateTracks_l(streamType)) {
5658 mFlushPending = true;
5659 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005660}
5661
Eric Laurentbfb1b832013-01-07 09:53:42 -08005662// ----------------------------------------------------------------------------
5663
Eric Laurent81784c32012-11-19 14:55:58 -08005664AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005665 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005666 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005667 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005668 mWaitTimeMs(UINT_MAX)
5669{
5670 addOutputTrack(mainThread);
5671}
5672
5673AudioFlinger::DuplicatingThread::~DuplicatingThread()
5674{
5675 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5676 mOutputTracks[i]->destroy();
5677 }
5678}
5679
5680void AudioFlinger::DuplicatingThread::threadLoop_mix()
5681{
5682 // mix buffers...
5683 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005684 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005685 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005686 if (mMixerBufferValid) {
5687 memset(mMixerBuffer, 0, mMixerBufferSize);
5688 } else {
5689 memset(mSinkBuffer, 0, mSinkBufferSize);
5690 }
Eric Laurent81784c32012-11-19 14:55:58 -08005691 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005692 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005693 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005694 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005695 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005696}
5697
5698void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5699{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005700 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005701 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005702 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005703 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005704 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005705 }
5706 } else if (mBytesWritten != 0) {
5707 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5708 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005709 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005710 } else {
5711 // flush remaining overflow buffers in output tracks
5712 writeFrames = 0;
5713 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005714 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005715 }
5716}
5717
Eric Laurentbfb1b832013-01-07 09:53:42 -08005718ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005719{
5720 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005721 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005722 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005723 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005724 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005725}
5726
5727void AudioFlinger::DuplicatingThread::threadLoop_standby()
5728{
5729 // DuplicatingThread implements standby by stopping all tracks
5730 for (size_t i = 0; i < outputTracks.size(); i++) {
5731 outputTracks[i]->stop();
5732 }
5733}
5734
5735void AudioFlinger::DuplicatingThread::saveOutputTracks()
5736{
5737 outputTracks = mOutputTracks;
5738}
5739
5740void AudioFlinger::DuplicatingThread::clearOutputTracks()
5741{
5742 outputTracks.clear();
5743}
5744
5745void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5746{
5747 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005748 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5749 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5750 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5751 const size_t frameCount =
5752 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5753 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5754 // from different OutputTracks and their associated MixerThreads (e.g. one may
5755 // nearly empty and the other may be dropping data).
5756
5757 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005758 this,
5759 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005760 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005761 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005762 frameCount,
5763 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005764 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5765 if (status != NO_ERROR) {
5766 ALOGE("addOutputTrack() initCheck failed %d", status);
5767 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005768 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005769 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5770 mOutputTracks.add(outputTrack);
5771 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5772 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005773}
5774
5775void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5776{
5777 Mutex::Autolock _l(mLock);
5778 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5779 if (mOutputTracks[i]->thread() == thread) {
5780 mOutputTracks[i]->destroy();
5781 mOutputTracks.removeAt(i);
5782 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005783 if (thread->getOutput() == mOutput) {
5784 mOutput = NULL;
5785 }
Eric Laurent81784c32012-11-19 14:55:58 -08005786 return;
5787 }
5788 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005789 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005790}
5791
5792// caller must hold mLock
5793void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5794{
5795 mWaitTimeMs = UINT_MAX;
5796 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5797 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5798 if (strong != 0) {
5799 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5800 if (waitTimeMs < mWaitTimeMs) {
5801 mWaitTimeMs = waitTimeMs;
5802 }
5803 }
5804 }
5805}
5806
5807
5808bool AudioFlinger::DuplicatingThread::outputsReady(
5809 const SortedVector< sp<OutputTrack> > &outputTracks)
5810{
5811 for (size_t i = 0; i < outputTracks.size(); i++) {
5812 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5813 if (thread == 0) {
5814 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5815 outputTracks[i].get());
5816 return false;
5817 }
5818 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5819 // see note at standby() declaration
5820 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5821 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5822 thread.get());
5823 return false;
5824 }
5825 }
5826 return true;
5827}
5828
5829uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5830{
5831 return (mWaitTimeMs * 1000) / 2;
5832}
5833
5834void AudioFlinger::DuplicatingThread::cacheParameters_l()
5835{
5836 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5837 updateWaitTime_l();
5838
5839 MixerThread::cacheParameters_l();
5840}
5841
Eric Laurent6acd1d42017-01-04 14:23:29 -08005842
Eric Laurent81784c32012-11-19 14:55:58 -08005843// ----------------------------------------------------------------------------
5844// Record
5845// ----------------------------------------------------------------------------
5846
5847AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5848 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005849 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005850 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005851 audio_devices_t inDevice,
5852 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005853#ifdef TEE_SINK
5854 , const sp<NBAIO_Sink>& teeSink
5855#endif
5856 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005857 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005858 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005859 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005860 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005861#ifdef TEE_SINK
5862 , mTeeSink(teeSink)
5863#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005864 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5865 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005866 // mFastCapture below
5867 , mFastCaptureFutex(0)
5868 // mInputSource
5869 // mPipeSink
5870 // mPipeSource
5871 , mPipeFramesP2(0)
5872 // mPipeMemory
5873 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005874 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005875{
Glenn Kastend7dca052015-03-05 16:05:54 -08005876 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5877 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005878
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005879 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005880
5881 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005882 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005883 size_t numCounterOffers = 0;
5884 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005885#if !LOG_NDEBUG
5886 ssize_t index =
5887#else
5888 (void)
5889#endif
5890 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005891 ALOG_ASSERT(index == 0);
5892
5893 // initialize fast capture depending on configuration
5894 bool initFastCapture;
5895 switch (kUseFastCapture) {
5896 case FastCapture_Never:
5897 initFastCapture = false;
5898 break;
5899 case FastCapture_Always:
5900 initFastCapture = true;
5901 break;
5902 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005903 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005904 break;
5905 // case FastCapture_Dynamic:
5906 }
5907
5908 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005909 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005910 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005911 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5912 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005913 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5914 void *pipeBuffer;
5915 const sp<MemoryDealer> roHeap(readOnlyHeap());
5916 sp<IMemory> pipeMemory;
5917 if ((roHeap == 0) ||
5918 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5919 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5920 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5921 goto failed;
5922 }
5923 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5924 memset(pipeBuffer, 0, pipeSize);
5925 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5926 const NBAIO_Format offers[1] = {format};
5927 size_t numCounterOffers = 0;
5928 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5929 ALOG_ASSERT(index == 0);
5930 mPipeSink = pipe;
5931 PipeReader *pipeReader = new PipeReader(*pipe);
5932 numCounterOffers = 0;
5933 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5934 ALOG_ASSERT(index == 0);
5935 mPipeSource = pipeReader;
5936 mPipeFramesP2 = pipeFramesP2;
5937 mPipeMemory = pipeMemory;
5938
5939 // create fast capture
5940 mFastCapture = new FastCapture();
5941 FastCaptureStateQueue *sq = mFastCapture->sq();
5942#ifdef STATE_QUEUE_DUMP
5943 // FIXME
5944#endif
5945 FastCaptureState *state = sq->begin();
5946 state->mCblk = NULL;
5947 state->mInputSource = mInputSource.get();
5948 state->mInputSourceGen++;
5949 state->mPipeSink = pipe;
5950 state->mPipeSinkGen++;
5951 state->mFrameCount = mFrameCount;
5952 state->mCommand = FastCaptureState::COLD_IDLE;
5953 // already done in constructor initialization list
5954 //mFastCaptureFutex = 0;
5955 state->mColdFutexAddr = &mFastCaptureFutex;
5956 state->mColdGen++;
5957 state->mDumpState = &mFastCaptureDumpState;
5958#ifdef TEE_SINK
5959 // FIXME
5960#endif
5961 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5962 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5963 sq->end();
5964 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5965
5966 // start the fast capture
5967 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5968 pid_t tid = mFastCapture->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08005969 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005970 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005971#ifdef AUDIO_WATCHDOG
5972 // FIXME
5973#endif
5974
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005975 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005976 }
5977failed: ;
5978
5979 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005980}
5981
Eric Laurent81784c32012-11-19 14:55:58 -08005982AudioFlinger::RecordThread::~RecordThread()
5983{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005984 if (mFastCapture != 0) {
5985 FastCaptureStateQueue *sq = mFastCapture->sq();
5986 FastCaptureState *state = sq->begin();
5987 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5988 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5989 if (old == -1) {
5990 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5991 }
5992 }
5993 state->mCommand = FastCaptureState::EXIT;
5994 sq->end();
5995 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5996 mFastCapture->join();
5997 mFastCapture.clear();
5998 }
5999 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006000 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006001 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006002}
6003
6004void AudioFlinger::RecordThread::onFirstRef()
6005{
Glenn Kastend7dca052015-03-05 16:05:54 -08006006 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006007}
6008
Eric Laurent555530a2017-02-07 18:17:24 -08006009void AudioFlinger::RecordThread::preExit()
6010{
6011 ALOGV(" preExit()");
6012 Mutex::Autolock _l(mLock);
6013 for (size_t i = 0; i < mTracks.size(); i++) {
6014 sp<RecordTrack> track = mTracks[i];
6015 track->invalidate();
6016 }
6017 mActiveTracks.clear();
6018 mStartStopCond.broadcast();
6019}
6020
Eric Laurent81784c32012-11-19 14:55:58 -08006021bool AudioFlinger::RecordThread::threadLoop()
6022{
Eric Laurent81784c32012-11-19 14:55:58 -08006023 nsecs_t lastWarning = 0;
6024
6025 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006026
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006027reacquire_wakelock:
6028 sp<RecordTrack> activeTrack;
6029 {
6030 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006031 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006032 }
6033
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006034 // used to request a deferred sleep, to be executed later while mutex is unlocked
6035 uint32_t sleepUs = 0;
6036
6037 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006038 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006039 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006040
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006041 // activeTracks accumulates a copy of a subset of mActiveTracks
6042 Vector< sp<RecordTrack> > activeTracks;
6043
Glenn Kasten735f45f2014-08-18 15:51:59 -07006044 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006045 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006046
Glenn Kasten735f45f2014-08-18 15:51:59 -07006047 // reference to a fast track which is about to be removed
6048 sp<RecordTrack> fastTrackToRemove;
6049
Eric Laurent81784c32012-11-19 14:55:58 -08006050 { // scope for mLock
6051 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006052
Eric Laurent021cf962014-05-13 10:18:14 -07006053 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006054
Eric Laurent000a4192014-01-29 15:17:32 -08006055 // check exitPending here because checkForNewParameters_l() and
6056 // checkForNewParameters_l() can temporarily release mLock
6057 if (exitPending()) {
6058 break;
6059 }
6060
Eric Laurent5c25d562016-07-13 17:17:45 -07006061 // sleep with mutex unlocked
6062 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006063 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006064 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6065 ATRACE_END();
6066 sleepUs = 0;
6067 continue;
6068 }
6069
Glenn Kasten2b806402013-11-20 16:37:38 -08006070 // if no active track(s), then standby and release wakelock
6071 size_t size = mActiveTracks.size();
6072 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006073 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006074 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006075 releaseWakeLock_l();
6076 ALOGV("RecordThread: loop stopping");
6077 // go to sleep
6078 mWaitWorkCV.wait(mLock);
6079 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006080 goto reacquire_wakelock;
6081 }
6082
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006083 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006084 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006085 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006086
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006087 activeTrack = mActiveTracks[i];
6088 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006089 if (activeTrack->isFastTrack()) {
6090 ALOG_ASSERT(fastTrackToRemove == 0);
6091 fastTrackToRemove = activeTrack;
6092 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006093 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006094 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006095 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006096 continue;
6097 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006098
6099 TrackBase::track_state activeTrackState = activeTrack->mState;
6100 switch (activeTrackState) {
6101
6102 case TrackBase::PAUSING:
6103 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006104 doBroadcast = true;
6105 size--;
6106 continue;
6107
6108 case TrackBase::STARTING_1:
6109 sleepUs = 10000;
6110 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006111 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006112 continue;
6113
6114 case TrackBase::STARTING_2:
6115 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006116 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006117 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006118 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006119 break;
6120
6121 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006122 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 break;
6124
6125 case TrackBase::IDLE:
6126 i++;
6127 continue;
6128
6129 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006130 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006131 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006132
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006133 activeTracks.add(activeTrack);
6134 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006135
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006136 if (activeTrack->isFastTrack()) {
6137 ALOG_ASSERT(!mFastTrackAvail);
6138 ALOG_ASSERT(fastTrack == 0);
6139 fastTrack = activeTrack;
6140 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006141 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006142
Andy Hungdae27702016-10-31 14:01:16 -07006143 mActiveTracks.updatePowerState(this);
6144
Eric Laurent5c25d562016-07-13 17:17:45 -07006145 if (allStopped) {
6146 standbyIfNotAlreadyInStandby();
6147 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006148 if (doBroadcast) {
6149 mStartStopCond.broadcast();
6150 }
6151
6152 // sleep if there are no active tracks to process
6153 if (activeTracks.size() == 0) {
6154 if (sleepUs == 0) {
6155 sleepUs = kRecordThreadSleepUs;
6156 }
6157 continue;
6158 }
6159 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006160
Eric Laurent81784c32012-11-19 14:55:58 -08006161 lockEffectChains_l(effectChains);
6162 }
6163
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006164 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006165
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006166 size_t size = effectChains.size();
6167 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006168 // thread mutex is not locked, but effect chain is locked
6169 effectChains[i]->process_l();
6170 }
6171
Glenn Kasten735f45f2014-08-18 15:51:59 -07006172 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006173 if (mFastCapture != 0) {
6174 FastCaptureStateQueue *sq = mFastCapture->sq();
6175 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006176 bool didModify = false;
6177 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006178 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6179 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6180 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6181 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6182 if (old == -1) {
6183 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6184 }
6185 }
6186 state->mCommand = FastCaptureState::READ_WRITE;
6187#if 0 // FIXME
6188 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006189 FastThreadDumpState::kSamplingNforLowRamDevice :
6190 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006191#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006192 didModify = true;
6193 }
6194 audio_track_cblk_t *cblkOld = state->mCblk;
6195 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6196 if (cblkNew != cblkOld) {
6197 state->mCblk = cblkNew;
6198 // block until acked if removing a fast track
6199 if (cblkOld != NULL) {
6200 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6201 }
6202 didModify = true;
6203 }
6204 sq->end(didModify);
6205 if (didModify) {
6206 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006207#if 0
6208 if (kUseFastCapture == FastCapture_Dynamic) {
6209 mNormalSource = mPipeSource;
6210 }
6211#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006212 }
6213 }
6214
Glenn Kasten735f45f2014-08-18 15:51:59 -07006215 // now run the fast track destructor with thread mutex unlocked
6216 fastTrackToRemove.clear();
6217
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006218 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6219 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6220 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6221 // If destination is non-contiguous, first read past the nominal end of buffer, then
6222 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006223
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006224 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006225 ssize_t framesRead;
6226
6227 // If an NBAIO source is present, use it to read the normal capture's data
6228 if (mPipeSource != 0) {
6229 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006230 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006231 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006232 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006233 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6234 // buffer size or at least for 20ms.
6235 size_t sleepFrames = max(
6236 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6237 if (framesRead <= (ssize_t) sleepFrames) {
6238 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6239 }
6240 if (framesRead < 0) {
6241 status_t status = (status_t) framesRead;
6242 switch (status) {
6243 case OVERRUN:
6244 ALOGW("overrun on read from pipe");
6245 framesRead = 0;
6246 break;
6247 case NEGOTIATE:
6248 ALOGE("re-negotiation is needed");
6249 framesRead = -1; // Will cause an attempt to recover.
6250 break;
6251 default:
6252 ALOGE("unknown error %d on read from pipe", status);
6253 break;
6254 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006255 }
6256 // otherwise use the HAL / AudioStreamIn directly
6257 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006258 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006259 size_t bytesRead;
6260 status_t result = mInput->stream->read(
6261 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006262 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006263 if (result < 0) {
6264 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006265 } else {
6266 framesRead = bytesRead / mFrameSize;
6267 }
6268 }
6269
Andy Hung3f0c9022016-01-15 17:49:46 -08006270 // Update server timestamp with server stats
6271 // systemTime() is optional if the hardware supports timestamps.
6272 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6273 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6274
6275 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006276 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006277 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006278 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006279 if (ret == NO_ERROR) {
6280 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6281 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6282 // Note: In general record buffers should tend to be empty in
6283 // a properly running pipeline.
6284 //
6285 // Also, it is not advantageous to call get_presentation_position during the read
6286 // as the read obtains a lock, preventing the timestamp call from executing.
6287 }
6288 }
6289 // Use this to track timestamp information
6290 // ALOGD("%s", mTimestamp.toString().c_str());
6291
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006292 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006293 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006294 // Force input into standby so that it tries to recover at next read attempt
6295 inputStandBy();
6296 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006297 }
6298 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006299 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006300 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006301 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006302
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006303 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006304 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006305 }
6306 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006307 {
6308 size_t part1 = mRsmpInFramesP2 - rear;
6309 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006310 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006311 (framesRead - part1) * mFrameSize);
6312 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006313 }
6314 rear = mRsmpInRear += framesRead;
6315
6316 size = activeTracks.size();
6317 // loop over each active track
6318 for (size_t i = 0; i < size; i++) {
6319 activeTrack = activeTracks[i];
6320
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006321 // skip fast tracks, as those are handled directly by FastCapture
6322 if (activeTrack->isFastTrack()) {
6323 continue;
6324 }
6325
Andy Hung73c02e42015-03-29 01:13:58 -07006326 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006327 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6328
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006329 enum {
6330 OVERRUN_UNKNOWN,
6331 OVERRUN_TRUE,
6332 OVERRUN_FALSE
6333 } overrun = OVERRUN_UNKNOWN;
6334
6335 // loop over getNextBuffer to handle circular sink
6336 for (;;) {
6337
6338 activeTrack->mSink.frameCount = ~0;
6339 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6340 size_t framesOut = activeTrack->mSink.frameCount;
6341 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6342
Andy Hung73c02e42015-03-29 01:13:58 -07006343 // check available frames and handle overrun conditions
6344 // if the record track isn't draining fast enough.
6345 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006346 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006347 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6348 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006349 overrun = OVERRUN_TRUE;
6350 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006351 if (framesOut == 0 || framesIn == 0) {
6352 break;
6353 }
6354
Andy Hung6770c6f2015-04-07 13:43:36 -07006355 // Don't allow framesOut to be larger than what is possible with resampling
6356 // from framesIn.
6357 // This isn't strictly necessary but helps limit buffer resizing in
6358 // RecordBufferConverter. TODO: remove when no longer needed.
6359 framesOut = min(framesOut,
6360 destinationFramesPossible(
6361 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006362 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6363 framesOut = activeTrack->mRecordBufferConverter->convert(
6364 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006365
6366 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6367 overrun = OVERRUN_FALSE;
6368 }
6369
6370 if (activeTrack->mFramesToDrop == 0) {
6371 if (framesOut > 0) {
6372 activeTrack->mSink.frameCount = framesOut;
6373 activeTrack->releaseBuffer(&activeTrack->mSink);
6374 }
6375 } else {
6376 // FIXME could do a partial drop of framesOut
6377 if (activeTrack->mFramesToDrop > 0) {
6378 activeTrack->mFramesToDrop -= framesOut;
6379 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006380 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006381 }
6382 } else {
6383 activeTrack->mFramesToDrop += framesOut;
6384 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6385 activeTrack->mSyncStartEvent->isCancelled()) {
6386 ALOGW("Synced record %s, session %d, trigger session %d",
6387 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6388 activeTrack->sessionId(),
6389 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006390 activeTrack->mSyncStartEvent->triggerSession() :
6391 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006392 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006393 }
6394 }
6395 }
6396
6397 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006398 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006399 }
6400 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006401
6402 switch (overrun) {
6403 case OVERRUN_TRUE:
6404 // client isn't retrieving buffers fast enough
6405 if (!activeTrack->setOverflow()) {
6406 nsecs_t now = systemTime();
6407 // FIXME should lastWarning per track?
6408 if ((now - lastWarning) > kWarningThrottleNs) {
6409 ALOGW("RecordThread: buffer overflow");
6410 lastWarning = now;
6411 }
6412 }
6413 break;
6414 case OVERRUN_FALSE:
6415 activeTrack->clearOverflow();
6416 break;
6417 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006418 break;
6419 }
6420
Andy Hung3f0c9022016-01-15 17:49:46 -08006421 // update frame information and push timestamp out
6422 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006423 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006424 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6425 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006426 }
6427
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006428unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006429 // enable changes in effect chain
6430 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006431 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006432 }
6433
Glenn Kasten93e471f2013-08-19 08:40:07 -07006434 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006435
6436 {
6437 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006438 for (size_t i = 0; i < mTracks.size(); i++) {
6439 sp<RecordTrack> track = mTracks[i];
6440 track->invalidate();
6441 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006442 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006443 mStartStopCond.broadcast();
6444 }
6445
6446 releaseWakeLock();
6447
6448 ALOGV("RecordThread %p exiting", this);
6449 return false;
6450}
6451
Glenn Kasten93e471f2013-08-19 08:40:07 -07006452void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006453{
6454 if (!mStandby) {
6455 inputStandBy();
6456 mStandby = true;
6457 }
6458}
6459
6460void AudioFlinger::RecordThread::inputStandBy()
6461{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006462 // Idle the fast capture if it's currently running
6463 if (mFastCapture != 0) {
6464 FastCaptureStateQueue *sq = mFastCapture->sq();
6465 FastCaptureState *state = sq->begin();
6466 if (!(state->mCommand & FastCaptureState::IDLE)) {
6467 state->mCommand = FastCaptureState::COLD_IDLE;
6468 state->mColdFutexAddr = &mFastCaptureFutex;
6469 state->mColdGen++;
6470 mFastCaptureFutex = 0;
6471 sq->end();
6472 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6473 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6474#if 0
6475 if (kUseFastCapture == FastCapture_Dynamic) {
6476 // FIXME
6477 }
6478#endif
6479#ifdef AUDIO_WATCHDOG
6480 // FIXME
6481#endif
6482 } else {
6483 sq->end(false /*didModify*/);
6484 }
6485 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006486 status_t result = mInput->stream->standby();
6487 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006488
6489 // If going into standby, flush the pipe source.
6490 if (mPipeSource.get() != nullptr) {
6491 const ssize_t flushed = mPipeSource->flush();
6492 if (flushed > 0) {
6493 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6494 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6495 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6496 }
6497 }
Eric Laurent81784c32012-11-19 14:55:58 -08006498}
6499
Glenn Kasten05997e22014-03-13 15:08:33 -07006500// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006501sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006502 const sp<AudioFlinger::Client>& client,
6503 uint32_t sampleRate,
6504 audio_format_t format,
6505 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006506 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006507 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006508 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006509 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006510 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006511 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006512 status_t *status,
6513 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006514{
Glenn Kasten74935e42013-12-19 08:56:45 -08006515 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006516 sp<RecordTrack> track;
6517 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006518 audio_input_flags_t inputFlags = mInput->flags;
6519
6520 // special case for FAST flag considered OK if fast capture is present
6521 if (hasFastCapture()) {
6522 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6523 }
6524
6525 // Check if requested flags are compatible with output stream flags
6526 if ((*flags & inputFlags) != *flags) {
6527 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6528 " input flags (%08x)",
6529 *flags, inputFlags);
6530 *flags = (audio_input_flags_t)(*flags & inputFlags);
6531 }
Eric Laurent81784c32012-11-19 14:55:58 -08006532
Glenn Kasten90e58b12013-07-31 16:16:02 -07006533 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006534 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006535 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006536 // we formerly checked for a callback handler (non-0 tid),
6537 // but that is no longer required for TRANSFER_OBTAIN mode
6538 //
Glenn Kasten74105912014-07-03 12:28:53 -07006539 // frame count is not specified, or is exactly the pipe depth
6540 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006541 // PCM data
6542 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006543 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006544 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006545 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006546 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006547 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006548 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006549 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006550 hasFastCapture() &&
6551 // there are sufficient fast track slots available
6552 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006553 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006554 // check compatibility with audio effects.
6555 Mutex::Autolock _l(mLock);
6556 // Do not accept FAST flag if the session has software effects
6557 sp<EffectChain> chain = getEffectChain_l(sessionId);
6558 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006559 audio_input_flags_t old = *flags;
6560 chain->checkInputFlagCompatibility(flags);
6561 if (old != *flags) {
6562 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6563 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006564 }
6565 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006566 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006567 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6568 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006569 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006570 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006571 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006572 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006573 frameCount, mFrameCount, mPipeFramesP2,
6574 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6575 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006576 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006577 }
6578 }
6579
6580 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006581 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006582 // fast track: frame count is exactly the pipe depth
6583 frameCount = mPipeFramesP2;
6584 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6585 *notificationFrames = mFrameCount;
6586 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006587 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6588 // or 20 ms if there is a fast capture
6589 // TODO This could be a roundupRatio inline, and const
6590 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6591 * sampleRate + mSampleRate - 1) / mSampleRate;
6592 // minimum number of notification periods is at least kMinNotifications,
6593 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6594 static const size_t kMinNotifications = 3;
6595 static const uint32_t kMinMs = 30;
6596 // TODO This could be a roundupRatio inline
6597 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6598 // TODO This could be a roundupRatio inline
6599 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6600 maxNotificationFrames;
6601 const size_t minFrameCount = maxNotificationFrames *
6602 max(kMinNotifications, minNotificationsByMs);
6603 frameCount = max(frameCount, minFrameCount);
6604 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6605 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006606 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006607 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006608 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006609
Glenn Kasten15e57982013-09-24 11:52:37 -07006610 lStatus = initCheck();
6611 if (lStatus != NO_ERROR) {
6612 ALOGE("createRecordTrack_l() audio driver not initialized");
6613 goto Exit;
6614 }
Eric Laurent81784c32012-11-19 14:55:58 -08006615
6616 { // scope for mLock
6617 Mutex::Autolock _l(mLock);
6618
6619 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006620 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006621 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006622
Glenn Kasten03003332013-08-06 15:40:54 -07006623 lStatus = track->initCheck();
6624 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006625 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006626 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006627 goto Exit;
6628 }
6629 mTracks.add(track);
6630
6631 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6632 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6633 mAudioFlinger->btNrecIsOff();
6634 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6635 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006636
Eric Laurent05067782016-06-01 18:27:28 -07006637 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006638 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6639 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6640 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08006641 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006642 }
Eric Laurent81784c32012-11-19 14:55:58 -08006643 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006644
Eric Laurent81784c32012-11-19 14:55:58 -08006645 lStatus = NO_ERROR;
6646
6647Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006648 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006649 return track;
6650}
6651
6652status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6653 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006654 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006655{
6656 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6657 sp<ThreadBase> strongMe = this;
6658 status_t status = NO_ERROR;
6659
6660 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006661 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006662 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006663 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006664 triggerSession,
6665 recordTrack->sessionId(),
6666 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006667 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006668 // Sync event can be cancelled by the trigger session if the track is not in a
6669 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006670 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006671 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006672 } else {
6673 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006674 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006675 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006676 }
6677 }
6678
6679 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006680 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006681 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006682 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6683 if (recordTrack->mState == TrackBase::PAUSING) {
6684 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006685 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006686 } else {
6687 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006688 }
6689 return status;
6690 }
6691
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006692 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6693 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6694 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006695 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006696 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006697 status_t status = NO_ERROR;
6698 if (recordTrack->isExternalTrack()) {
6699 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006700 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006701 mLock.lock();
6702 // FIXME should verify that recordTrack is still in mActiveTracks
6703 if (status != NO_ERROR) {
6704 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006705 recordTrack->clearSyncStartEvent();
6706 ALOGV("RecordThread::start error %d", status);
6707 return status;
6708 }
Eric Laurent81784c32012-11-19 14:55:58 -08006709 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006710 // Catch up with current buffer indices if thread is already running.
6711 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6712 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6713 // see previously buffered data before it called start(), but with greater risk of overrun.
6714
Andy Hung73c02e42015-03-29 01:13:58 -07006715 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006716 // clear any converter state as new data will be discontinuous
6717 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006718 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006719 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006720 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006721 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006722 ALOGV("Record failed to start");
6723 status = BAD_VALUE;
6724 goto startError;
6725 }
Eric Laurent81784c32012-11-19 14:55:58 -08006726 return status;
6727 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006728
Eric Laurent81784c32012-11-19 14:55:58 -08006729startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006730 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006731 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006732 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006733 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006734 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006735 return status;
6736}
6737
Eric Laurent81784c32012-11-19 14:55:58 -08006738void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6739{
6740 sp<SyncEvent> strongEvent = event.promote();
6741
6742 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006743 sp<RefBase> ptr = strongEvent->cookie().promote();
6744 if (ptr != 0) {
6745 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6746 recordTrack->handleSyncStartEvent(strongEvent);
6747 }
Eric Laurent81784c32012-11-19 14:55:58 -08006748 }
6749}
6750
Glenn Kastena8356f62013-07-25 14:37:52 -07006751bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006752 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006753 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006754 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006755 return false;
6756 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006757 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006758 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006759 // signal thread to stop
6760 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006761 // do not wait for mStartStopCond if exiting
6762 if (exitPending()) {
6763 return true;
6764 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006765 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006766 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006767 // if we have been restarted, recordTrack is in mActiveTracks here
6768 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006769 ALOGV("Record stopped OK");
6770 return true;
6771 }
6772 return false;
6773}
6774
Glenn Kasten0f11b512014-01-31 16:18:54 -08006775bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006776{
6777 return false;
6778}
6779
Glenn Kasten0f11b512014-01-31 16:18:54 -08006780status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006781{
6782#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6783 if (!isValidSyncEvent(event)) {
6784 return BAD_VALUE;
6785 }
6786
Glenn Kastend848eb42016-03-08 13:42:11 -08006787 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006788 status_t ret = NAME_NOT_FOUND;
6789
6790 Mutex::Autolock _l(mLock);
6791
6792 for (size_t i = 0; i < mTracks.size(); i++) {
6793 sp<RecordTrack> track = mTracks[i];
6794 if (eventSession == track->sessionId()) {
6795 (void) track->setSyncEvent(event);
6796 ret = NO_ERROR;
6797 }
6798 }
6799 return ret;
6800#else
6801 return BAD_VALUE;
6802#endif
6803}
6804
6805// destroyTrack_l() must be called with ThreadBase::mLock held
6806void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6807{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006808 track->terminate();
6809 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006810 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006811 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006812 removeTrack_l(track);
6813 }
6814}
6815
6816void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6817{
6818 mTracks.remove(track);
6819 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006820 if (track->isFastTrack()) {
6821 ALOG_ASSERT(!mFastTrackAvail);
6822 mFastTrackAvail = true;
6823 }
Eric Laurent81784c32012-11-19 14:55:58 -08006824}
6825
6826void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6827{
6828 dumpInternals(fd, args);
6829 dumpTracks(fd, args);
6830 dumpEffectChains(fd, args);
6831}
6832
6833void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6834{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006835 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006836
Glenn Kasten44182c22015-03-05 17:12:23 -08006837 dumpBase(fd, args);
6838
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006839 AudioStreamIn *input = mInput;
6840 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6841 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6842 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006843 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006844 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006845 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006846 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006847 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006848
Glenn Kasten2f90c512015-12-02 11:40:09 -08006849 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6850 // while we are dumping it. It may be inconsistent, but it won't mutate!
6851 // This is a large object so we place it on the heap.
6852 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6853 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6854 copy->dump(fd);
6855 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006856}
6857
Glenn Kasten0f11b512014-01-31 16:18:54 -08006858void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006859{
6860 const size_t SIZE = 256;
6861 char buffer[SIZE];
6862 String8 result;
6863
Marco Nelissenb2208842014-02-07 14:00:50 -08006864 size_t numtracks = mTracks.size();
6865 size_t numactive = mActiveTracks.size();
6866 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006867 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006868 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006869 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006870 RecordTrack::appendDumpHeader(result);
6871 for (size_t i = 0; i < numtracks ; ++i) {
6872 sp<RecordTrack> track = mTracks[i];
6873 if (track != 0) {
6874 bool active = mActiveTracks.indexOf(track) >= 0;
6875 if (active) {
6876 numactiveseen++;
6877 }
6878 track->dump(buffer, SIZE, active);
6879 result.append(buffer);
6880 }
Eric Laurent81784c32012-11-19 14:55:58 -08006881 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006882 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006883 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006884 }
6885
Marco Nelissenb2208842014-02-07 14:00:50 -08006886 if (numactiveseen != numactive) {
6887 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6888 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006889 result.append(buffer);
6890 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006891 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006892 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006893 if (mTracks.indexOf(track) < 0) {
6894 track->dump(buffer, SIZE, true);
6895 result.append(buffer);
6896 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006897 }
Eric Laurent81784c32012-11-19 14:55:58 -08006898
6899 }
6900 write(fd, result.string(), result.size());
6901}
6902
Andy Hung73c02e42015-03-29 01:13:58 -07006903
6904void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6905{
6906 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6907 RecordThread *recordThread = (RecordThread *) threadBase.get();
6908 mRsmpInFront = recordThread->mRsmpInRear;
6909 mRsmpInUnrel = 0;
6910}
6911
6912void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6913 size_t *framesAvailable, bool *hasOverrun)
6914{
6915 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6916 RecordThread *recordThread = (RecordThread *) threadBase.get();
6917 const int32_t rear = recordThread->mRsmpInRear;
6918 const int32_t front = mRsmpInFront;
6919 const ssize_t filled = rear - front;
6920
6921 size_t framesIn;
6922 bool overrun = false;
6923 if (filled < 0) {
6924 // should not happen, but treat like a massive overrun and re-sync
6925 framesIn = 0;
6926 mRsmpInFront = rear;
6927 overrun = true;
6928 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6929 framesIn = (size_t) filled;
6930 } else {
6931 // client is not keeping up with server, but give it latest data
6932 framesIn = recordThread->mRsmpInFrames;
6933 mRsmpInFront = /* front = */ rear - framesIn;
6934 overrun = true;
6935 }
6936 if (framesAvailable != NULL) {
6937 *framesAvailable = framesIn;
6938 }
6939 if (hasOverrun != NULL) {
6940 *hasOverrun = overrun;
6941 }
6942}
6943
Eric Laurent81784c32012-11-19 14:55:58 -08006944// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006945status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006946 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006947{
Andy Hung73c02e42015-03-29 01:13:58 -07006948 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006949 if (threadBase == 0) {
6950 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006951 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006952 return NOT_ENOUGH_DATA;
6953 }
6954 RecordThread *recordThread = (RecordThread *) threadBase.get();
6955 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006956 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006957 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006958 // FIXME should not be P2 (don't want to increase latency)
6959 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006960 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006961 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006962 front &= recordThread->mRsmpInFramesP2 - 1;
6963 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006964 if (part1 > (size_t) filled) {
6965 part1 = filled;
6966 }
6967 size_t ask = buffer->frameCount;
6968 ALOG_ASSERT(ask > 0);
6969 if (part1 > ask) {
6970 part1 = ask;
6971 }
6972 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006973 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006974 buffer->raw = NULL;
6975 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006976 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006977 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006978 }
6979
Andy Hung57446612015-04-19 23:56:46 -07006980 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006981 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006982 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006983 return NO_ERROR;
6984}
6985
6986// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006987void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6988 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006989{
Glenn Kasten85948432013-08-19 12:09:05 -07006990 size_t stepCount = buffer->frameCount;
6991 if (stepCount == 0) {
6992 return;
6993 }
Andy Hung73c02e42015-03-29 01:13:58 -07006994 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6995 mRsmpInUnrel -= stepCount;
6996 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006997 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006998 buffer->frameCount = 0;
6999}
7000
Andy Hung97a893e2015-03-29 01:03:07 -07007001
Eric Laurent10351942014-05-08 18:49:52 -07007002bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7003 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007004{
7005 bool reconfig = false;
7006
Eric Laurent10351942014-05-08 18:49:52 -07007007 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007008
Eric Laurent10351942014-05-08 18:49:52 -07007009 audio_format_t reqFormat = mFormat;
7010 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007011 // 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 -07007012 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7013
7014 AudioParameter param = AudioParameter(keyValuePair);
7015 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007016
7017 // scope for AutoPark extends to end of method
7018 AutoPark<FastCapture> park(mFastCapture);
7019
Eric Laurent10351942014-05-08 18:49:52 -07007020 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7021 // channel count change can be requested. Do we mandate the first client defines the
7022 // HAL sampling rate and channel count or do we allow changes on the fly?
7023 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7024 samplingRate = value;
7025 reconfig = true;
7026 }
7027 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007028 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007029 status = BAD_VALUE;
7030 } else {
7031 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007032 reconfig = true;
7033 }
Eric Laurent10351942014-05-08 18:49:52 -07007034 }
7035 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7036 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007037 if (!audio_is_input_channel(mask) ||
7038 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007039 status = BAD_VALUE;
7040 } else {
7041 channelMask = mask;
7042 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007043 }
Eric Laurent10351942014-05-08 18:49:52 -07007044 }
7045 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7046 // do not accept frame count changes if tracks are open as the track buffer
7047 // size depends on frame count and correct behavior would not be guaranteed
7048 // if frame count is changed after track creation
7049 if (mActiveTracks.size() > 0) {
7050 status = INVALID_OPERATION;
7051 } else {
7052 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007053 }
Eric Laurent10351942014-05-08 18:49:52 -07007054 }
7055 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7056 // forward device change to effects that have requested to be
7057 // aware of attached audio device.
7058 for (size_t i = 0; i < mEffectChains.size(); i++) {
7059 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007060 }
Eric Laurent81784c32012-11-19 14:55:58 -08007061
Eric Laurent10351942014-05-08 18:49:52 -07007062 // store input device and output device but do not forward output device to audio HAL.
7063 // Note that status is ignored by the caller for output device
7064 // (see AudioFlinger::setParameters()
7065 if (audio_is_output_devices(value)) {
7066 mOutDevice = value;
7067 status = BAD_VALUE;
7068 } else {
7069 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007070 if (value != AUDIO_DEVICE_NONE) {
7071 mPrevInDevice = value;
7072 }
Eric Laurent10351942014-05-08 18:49:52 -07007073 // disable AEC and NS if the device is a BT SCO headset supporting those
7074 // pre processings
7075 if (mTracks.size() > 0) {
7076 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7077 mAudioFlinger->btNrecIsOff();
7078 for (size_t i = 0; i < mTracks.size(); i++) {
7079 sp<RecordTrack> track = mTracks[i];
7080 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7081 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007082 }
7083 }
7084 }
Eric Laurent10351942014-05-08 18:49:52 -07007085 }
7086 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7087 mAudioSource != (audio_source_t)value) {
7088 // forward device change to effects that have requested to be
7089 // aware of attached audio device.
7090 for (size_t i = 0; i < mEffectChains.size(); i++) {
7091 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007092 }
Eric Laurent10351942014-05-08 18:49:52 -07007093 mAudioSource = (audio_source_t)value;
7094 }
Glenn Kastene198c362013-08-13 09:13:36 -07007095
Eric Laurent10351942014-05-08 18:49:52 -07007096 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007097 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007098 if (status == INVALID_OPERATION) {
7099 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007100 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007101 }
7102 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007103 if (status == BAD_VALUE) {
7104 uint32_t sRate;
7105 audio_channel_mask_t channelMask;
7106 audio_format_t format;
7107 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7108 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7109 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7110 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7111 status = NO_ERROR;
7112 }
Eric Laurent81784c32012-11-19 14:55:58 -08007113 }
Eric Laurent10351942014-05-08 18:49:52 -07007114 if (status == NO_ERROR) {
7115 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007116 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007117 }
7118 }
Eric Laurent81784c32012-11-19 14:55:58 -08007119 }
Eric Laurent10351942014-05-08 18:49:52 -07007120
Eric Laurent81784c32012-11-19 14:55:58 -08007121 return reconfig;
7122}
7123
7124String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7125{
Eric Laurent81784c32012-11-19 14:55:58 -08007126 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007127 if (initCheck() == NO_ERROR) {
7128 String8 out_s8;
7129 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7130 return out_s8;
7131 }
Eric Laurent81784c32012-11-19 14:55:58 -08007132 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007133 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007134}
7135
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007136void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007137 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7138
7139 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007140
7141 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007142 case AUDIO_INPUT_OPENED:
7143 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007144 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007145 desc->mChannelMask = mChannelMask;
7146 desc->mSamplingRate = mSampleRate;
7147 desc->mFormat = mFormat;
7148 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007149 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007150 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007151 break;
7152
Eric Laurent73e26b62015-04-27 16:55:58 -07007153 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007154 default:
7155 break;
7156 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007157 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007158}
7159
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007160void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007161{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007162 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7163 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007164 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007165 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007166 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007167 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7168 result = mInput->stream->getFrameSize(&mFrameSize);
7169 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7170 result = mInput->stream->getBufferSize(&mBufferSize);
7171 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007172 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007173 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007174 // 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 -07007175 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007176 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007177 // A larger value should allow more old data to be read after a track calls start(),
7178 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007179 //
7180 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007181 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007182 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007183 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007184 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007185
7186 // TODO optimize audio capture buffer sizes ...
7187 // Here we calculate the size of the sliding buffer used as a source
7188 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7189 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7190 // be better to have it derived from the pipe depth in the long term.
7191 // The current value is higher than necessary. However it should not add to latency.
7192
Glenn Kasten85948432013-08-19 12:09:05 -07007193 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007194 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7195 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7196 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007197
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007198 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7199 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007200}
7201
Glenn Kasten5f972c02014-01-13 09:59:31 -08007202uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007203{
7204 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007205 uint32_t result;
7206 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7207 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007208 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007209 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007210}
7211
Eric Laurent4c415062016-06-17 16:14:16 -07007212// hasAudioSession_l() must be called with ThreadBase::mLock held
7213uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007214{
Eric Laurent81784c32012-11-19 14:55:58 -08007215 uint32_t result = 0;
7216 if (getEffectChain_l(sessionId) != 0) {
7217 result = EFFECT_SESSION;
7218 }
7219
7220 for (size_t i = 0; i < mTracks.size(); ++i) {
7221 if (sessionId == mTracks[i]->sessionId()) {
7222 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007223 if (mTracks[i]->isFastTrack()) {
7224 result |= FAST_SESSION;
7225 }
Eric Laurent81784c32012-11-19 14:55:58 -08007226 break;
7227 }
7228 }
7229
7230 return result;
7231}
7232
Glenn Kastend848eb42016-03-08 13:42:11 -08007233KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007234{
Glenn Kastend848eb42016-03-08 13:42:11 -08007235 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007236 Mutex::Autolock _l(mLock);
7237 for (size_t j = 0; j < mTracks.size(); ++j) {
7238 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007239 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007240 if (ids.indexOfKey(sessionId) < 0) {
7241 ids.add(sessionId, true);
7242 }
7243 }
7244 return ids;
7245}
7246
7247AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7248{
7249 Mutex::Autolock _l(mLock);
7250 AudioStreamIn *input = mInput;
7251 mInput = NULL;
7252 return input;
7253}
7254
7255// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007256sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007257{
7258 if (mInput == NULL) {
7259 return NULL;
7260 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007261 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007262}
7263
7264status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7265{
7266 // only one chain per input thread
7267 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007268 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007269 return INVALID_OPERATION;
7270 }
7271 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007272 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007273 chain->setInBuffer(NULL);
7274 chain->setOutBuffer(NULL);
7275
7276 checkSuspendOnAddEffectChain_l(chain);
7277
Eric Laurent1b928682014-10-02 19:41:47 -07007278 // make sure enabled pre processing effects state is communicated to the HAL as we
7279 // just moved them to a new input stream.
7280 chain->syncHalEffectsState();
7281
Eric Laurent81784c32012-11-19 14:55:58 -08007282 mEffectChains.add(chain);
7283
7284 return NO_ERROR;
7285}
7286
7287size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7288{
7289 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7290 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007291 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007292 chain.get(), mEffectChains.size(), this);
7293 if (mEffectChains.size() == 1) {
7294 mEffectChains.removeAt(0);
7295 }
7296 return 0;
7297}
7298
Eric Laurent1c333e22014-05-20 10:48:17 -07007299status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7300 audio_patch_handle_t *handle)
7301{
7302 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007303
7304 // store new device and send to effects
7305 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007306 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007307 for (size_t i = 0; i < mEffectChains.size(); i++) {
7308 mEffectChains[i]->setDevice_l(mInDevice);
7309 }
7310
7311 // disable AEC and NS if the device is a BT SCO headset supporting those
7312 // pre processings
7313 if (mTracks.size() > 0) {
7314 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7315 mAudioFlinger->btNrecIsOff();
7316 for (size_t i = 0; i < mTracks.size(); i++) {
7317 sp<RecordTrack> track = mTracks[i];
7318 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7319 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7320 }
7321 }
7322
7323 // store new source and send to effects
7324 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7325 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007326 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007327 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007328 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007329 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007330
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007331 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007332 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7333 status = hwDevice->createAudioPatch(patch->num_sources,
7334 patch->sources,
7335 patch->num_sinks,
7336 patch->sinks,
7337 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007338 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007339 char *address;
7340 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7341 address = audio_device_address_to_parameter(
7342 patch->sources[0].ext.device.type,
7343 patch->sources[0].ext.device.address);
7344 } else {
7345 address = (char *)calloc(1, 1);
7346 }
7347 AudioParameter param = AudioParameter(String8(address));
7348 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007349 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007350 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007351 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007352 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007353 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007354 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007355 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007356
Eric Laurente8726fe2015-06-26 09:39:24 -07007357 if (mInDevice != mPrevInDevice) {
7358 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7359 mPrevInDevice = mInDevice;
7360 }
Eric Laurent296fb132015-05-01 11:38:42 -07007361
Eric Laurent1c333e22014-05-20 10:48:17 -07007362 return status;
7363}
7364
7365status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7366{
7367 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007368
7369 mInDevice = AUDIO_DEVICE_NONE;
7370
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007371 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007372 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7373 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007374 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007375 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007376 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007377 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007378 }
7379 return status;
7380}
7381
Eric Laurent83b88082014-06-20 18:31:16 -07007382void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7383{
7384 Mutex::Autolock _l(mLock);
7385 mTracks.add(record);
7386}
7387
7388void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7389{
7390 Mutex::Autolock _l(mLock);
7391 destroyTrack_l(record);
7392}
7393
7394void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7395{
7396 ThreadBase::getAudioPortConfig(config);
7397 config->role = AUDIO_PORT_ROLE_SINK;
7398 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7399 config->ext.mix.usecase.source = mAudioSource;
7400}
Eric Laurent1c333e22014-05-20 10:48:17 -07007401
Eric Laurent6acd1d42017-01-04 14:23:29 -08007402// ----------------------------------------------------------------------------
7403// Mmap
7404// ----------------------------------------------------------------------------
7405
7406AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7407 : mThread(thread)
7408{
7409}
7410
7411AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7412{
7413 MmapThread *thread = mThread.get();
7414 // clear our strong reference before disconnecting the thread: the last strong reference
7415 // will be removed when closeInput/closeOutput is executed upono call from audio policy manager
7416 // and the thread removed from mMMapThreads list causing the thread destruction.
7417 mThread.clear();
7418 if (thread != nullptr) {
7419 thread->disconnect();
7420 }
7421}
7422
7423status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7424 struct audio_mmap_buffer_info *info)
7425{
7426 if (mThread == 0) {
7427 return NO_INIT;
7428 }
7429 return mThread->createMmapBuffer(minSizeFrames, info);
7430}
7431
7432status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7433{
7434 if (mThread == 0) {
7435 return NO_INIT;
7436 }
7437 return mThread->getMmapPosition(position);
7438}
7439
7440status_t AudioFlinger::MmapThreadHandle::start(const MmapStreamInterface::Client& client, audio_port_handle_t *handle)
7441
7442{
7443 if (mThread == 0) {
7444 return NO_INIT;
7445 }
7446 return mThread->start(client, handle);
7447}
7448
7449status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7450{
7451 if (mThread == 0) {
7452 return NO_INIT;
7453 }
7454 return mThread->stop(handle);
7455}
7456
7457
7458AudioFlinger::MmapThread::MmapThread(
7459 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7460 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7461 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7462 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
7463 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev)
7464{
7465 readHalParameters_l();
7466}
7467
7468AudioFlinger::MmapThread::~MmapThread()
7469{
7470}
7471
7472void AudioFlinger::MmapThread::onFirstRef()
7473{
7474 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7475}
7476
7477void AudioFlinger::MmapThread::disconnect()
7478{
7479 for (const sp<MmapTrack> &t : mActiveTracks) {
7480 stop(t->portId());
7481 }
7482 // this will cause the destruction of this thread.
7483 if (isOutput()) {
7484 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7485 } else {
7486 AudioSystem::releaseInput(mId, mSessionId);
7487 }
7488}
7489
7490
7491void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7492 audio_stream_type_t streamType __unused,
7493 audio_session_t sessionId,
7494 const sp<MmapStreamCallback>& callback,
7495 audio_port_handle_t portId)
7496{
7497 mAttr = *attr;
7498 mSessionId = sessionId;
7499 mCallback = callback;
7500 mPortId = portId;
7501}
7502
7503status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7504 struct audio_mmap_buffer_info *info)
7505{
7506 if (mHalStream == 0) {
7507 return NO_INIT;
7508 }
7509 return mHalStream->createMmapBuffer(minSizeFrames, info);
7510}
7511
7512status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7513{
7514 if (mHalStream == 0) {
7515 return NO_INIT;
7516 }
7517 return mHalStream->getMmapPosition(position);
7518}
7519
7520status_t AudioFlinger::MmapThread::start(const MmapStreamInterface::Client& client,
7521 audio_port_handle_t *handle)
7522{
7523 ALOGV("%s clientUid %d", __FUNCTION__, client.clientUid);
7524 if (mHalStream == 0) {
7525 return NO_INIT;
7526 }
7527
7528 status_t ret;
7529 audio_session_t sessionId;
7530 audio_port_handle_t portId;
7531
7532 if (mActiveTracks.size() == 0) {
7533 // for the first track, reuse portId and session allocated when the stream was opened
7534 mHalStream->start();
7535 portId = mPortId;
7536 sessionId = mSessionId;
7537 } else {
7538 // for other tracks than first one, get a new port ID from APM.
7539 sessionId = (audio_session_t)mAudioFlinger->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
7540 audio_io_handle_t io;
7541 if (isOutput()) {
7542 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7543 config.sample_rate = mSampleRate;
7544 config.channel_mask = mChannelMask;
7545 config.format = mFormat;
7546 audio_stream_type_t stream = streamType();
7547 audio_output_flags_t flags =
7548 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
7549 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7550 sessionId,
7551 &stream,
7552 client.clientUid,
7553 &config,
7554 flags,
7555 AUDIO_PORT_HANDLE_NONE,
7556 &portId);
7557 } else {
7558 audio_config_base_t config;
7559 config.sample_rate = mSampleRate;
7560 config.channel_mask = mChannelMask;
7561 config.format = mFormat;
7562 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7563 sessionId,
7564 client.clientPid,
7565 client.clientUid,
7566 &config,
7567 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7568 AUDIO_PORT_HANDLE_NONE,
7569 &portId);
7570 }
7571 // APM should not chose a different input or output stream for the same set of attributes
7572 // and audo configuration
7573 if (ret != NO_ERROR || io != mId) {
7574 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7575 __FUNCTION__, ret, io, mId);
7576 return BAD_VALUE;
7577 }
7578 }
7579
7580 if (isOutput()) {
7581 ret = AudioSystem::startOutput(mId, streamType(), sessionId);
7582 } else {
7583 ret = AudioSystem::startInput(mId, sessionId);
7584 }
7585
7586 // abort if start is rejected by audio policy manager
7587 if (ret != NO_ERROR) {
7588 if (mActiveTracks.size() != 0) {
7589 if (isOutput()) {
7590 AudioSystem::releaseOutput(mId, streamType(), sessionId);
7591 } else {
7592 AudioSystem::releaseInput(mId, sessionId);
7593 }
7594 }
7595 return PERMISSION_DENIED;
7596 }
7597
7598 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, sessionId,
7599 client.clientUid, portId);
7600
7601 mActiveTracks.add(track);
7602 sp<EffectChain> chain = getEffectChain_l(sessionId);
7603 if (chain != 0) {
7604 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7605 chain->incTrackCnt();
7606 chain->incActiveTrackCnt();
7607 }
7608
7609 *handle = portId;
7610
7611 broadcast_l();
7612
7613 ALOGV("%s DONE handle %d", __FUNCTION__, portId);
7614
7615 return NO_ERROR;
7616}
7617
7618status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7619{
7620
7621 ALOGV("%s handle %d", __FUNCTION__, handle);
7622
7623 if (mHalStream == 0) {
7624 return NO_INIT;
7625 }
7626
7627 sp<MmapTrack> track;
7628 for (const sp<MmapTrack> &t : mActiveTracks) {
7629 if (handle == t->portId()) {
7630 track = t;
7631 break;
7632 }
7633 }
7634 if (track == 0) {
7635 return BAD_VALUE;
7636 }
7637
7638 mActiveTracks.remove(track);
7639
7640 if (isOutput()) {
7641 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
7642 if (mActiveTracks.size() != 0) {
7643 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
7644 }
7645 } else {
7646 AudioSystem::stopInput(mId, track->sessionId());
7647 if (mActiveTracks.size() != 0) {
7648 AudioSystem::releaseInput(mId, track->sessionId());
7649 }
7650 }
7651
7652 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7653 if (chain != 0) {
7654 chain->decActiveTrackCnt();
7655 chain->decTrackCnt();
7656 }
7657
7658 broadcast_l();
7659
7660 if (mActiveTracks.size() == 0) {
7661 mHalStream->stop();
7662 }
7663 return NO_ERROR;
7664}
7665
7666
7667void AudioFlinger::MmapThread::readHalParameters_l()
7668{
7669 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7670 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7671 mFormat = mHALFormat;
7672 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7673 result = mHalStream->getFrameSize(&mFrameSize);
7674 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7675 result = mHalStream->getBufferSize(&mBufferSize);
7676 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7677 mFrameCount = mBufferSize / mFrameSize;
7678}
7679
7680bool AudioFlinger::MmapThread::threadLoop()
7681{
7682 acquireWakeLock();
7683
7684 checkSilentMode_l();
7685
7686 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7687
7688 while (!exitPending())
7689 {
7690 Mutex::Autolock _l(mLock);
7691 Vector< sp<EffectChain> > effectChains;
7692
7693 if (mSignalPending) {
7694 // A signal was raised while we were unlocked
7695 mSignalPending = false;
7696 } else {
7697 if (mConfigEvents.isEmpty()) {
7698 // we're about to wait, flush the binder command buffer
7699 IPCThreadState::self()->flushCommands();
7700
7701 if (exitPending()) {
7702 break;
7703 }
7704
7705 bool wakelockReleased = false;
7706 if (mActiveTracks.size() == 0) {
7707 releaseWakeLock_l();
7708 wakelockReleased = true;
7709 }
7710 // wait until we have something to do...
7711 ALOGV("%s going to sleep", myName.string());
7712 mWaitWorkCV.wait(mLock);
7713 ALOGV("%s waking up", myName.string());
7714 if (wakelockReleased) {
7715 acquireWakeLock_l();
7716 }
7717
7718 checkSilentMode_l();
7719
7720 continue;
7721 }
7722 }
7723
7724 processConfigEvents_l();
7725
7726 processVolume_l();
7727
7728 checkInvalidTracks_l();
7729
7730 mActiveTracks.updatePowerState(this);
7731
7732 lockEffectChains_l(effectChains);
7733 for (size_t i = 0; i < effectChains.size(); i ++) {
7734 effectChains[i]->process_l();
7735 }
7736 // enable changes in effect chain
7737 unlockEffectChains(effectChains);
7738 // Effect chains will be actually deleted here if they were removed from
7739 // mEffectChains list during mixing or effects processing
7740 }
7741
7742 threadLoop_exit();
7743
7744 if (!mStandby) {
7745 threadLoop_standby();
7746 mStandby = true;
7747 }
7748
7749 releaseWakeLock();
7750
7751 ALOGV("Thread %p type %d exiting", this, mType);
7752 return false;
7753}
7754
7755// checkForNewParameter_l() must be called with ThreadBase::mLock held
7756bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7757 status_t& status)
7758{
7759 AudioParameter param = AudioParameter(keyValuePair);
7760 int value;
7761 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7762 // forward device change to effects that have requested to be
7763 // aware of attached audio device.
7764 if (value != AUDIO_DEVICE_NONE) {
7765 mOutDevice = value;
7766 for (size_t i = 0; i < mEffectChains.size(); i++) {
7767 mEffectChains[i]->setDevice_l(mOutDevice);
7768 }
7769 }
7770 }
7771 status = mHalStream->setParameters(keyValuePair);
7772
7773 return false;
7774}
7775
7776String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7777{
7778 Mutex::Autolock _l(mLock);
7779 String8 out_s8;
7780 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7781 return out_s8;
7782 }
7783 return String8();
7784}
7785
7786void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7787 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7788
7789 desc->mIoHandle = mId;
7790
7791 switch (event) {
7792 case AUDIO_INPUT_OPENED:
7793 case AUDIO_INPUT_CONFIG_CHANGED:
7794 case AUDIO_OUTPUT_OPENED:
7795 case AUDIO_OUTPUT_CONFIG_CHANGED:
7796 desc->mPatch = mPatch;
7797 desc->mChannelMask = mChannelMask;
7798 desc->mSamplingRate = mSampleRate;
7799 desc->mFormat = mFormat;
7800 desc->mFrameCount = mFrameCount;
7801 desc->mFrameCountHAL = mFrameCount;
7802 desc->mLatency = 0;
7803 break;
7804
7805 case AUDIO_INPUT_CLOSED:
7806 case AUDIO_OUTPUT_CLOSED:
7807 default:
7808 break;
7809 }
7810 mAudioFlinger->ioConfigChanged(event, desc, pid);
7811}
7812
7813status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7814 audio_patch_handle_t *handle)
7815{
7816 status_t status = NO_ERROR;
7817
7818 // store new device and send to effects
7819 audio_devices_t type = AUDIO_DEVICE_NONE;
7820 audio_port_handle_t deviceId;
7821 if (isOutput()) {
7822 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7823 type |= patch->sinks[i].ext.device.type;
7824 }
7825 deviceId = patch->sinks[0].id;
7826 } else {
7827 type = patch->sources[0].ext.device.type;
7828 deviceId = patch->sources[0].id;
7829 }
7830
7831 for (size_t i = 0; i < mEffectChains.size(); i++) {
7832 mEffectChains[i]->setDevice_l(type);
7833 }
7834
7835 if (isOutput()) {
7836 mOutDevice = type;
7837 } else {
7838 mInDevice = type;
7839 // store new source and send to effects
7840 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7841 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7842 for (size_t i = 0; i < mEffectChains.size(); i++) {
7843 mEffectChains[i]->setAudioSource_l(mAudioSource);
7844 }
7845 }
7846 }
7847
7848 if (mAudioHwDev->supportsAudioPatches()) {
7849 status = mHalDevice->createAudioPatch(patch->num_sources,
7850 patch->sources,
7851 patch->num_sinks,
7852 patch->sinks,
7853 handle);
7854 } else {
7855 char *address;
7856 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7857 //FIXME: we only support address on first sink with HAL version < 3.0
7858 address = audio_device_address_to_parameter(
7859 patch->sinks[0].ext.device.type,
7860 patch->sinks[0].ext.device.address);
7861 } else {
7862 address = (char *)calloc(1, 1);
7863 }
7864 AudioParameter param = AudioParameter(String8(address));
7865 free(address);
7866 param.addInt(String8(AudioParameter::keyRouting), (int)type);
7867 if (!isOutput()) {
7868 param.addInt(String8(AudioParameter::keyInputSource),
7869 (int)patch->sinks[0].ext.mix.usecase.source);
7870 }
7871 status = mHalStream->setParameters(param.toString());
7872 *handle = AUDIO_PATCH_HANDLE_NONE;
7873 }
7874
7875 if (isOutput() && mPrevOutDevice != mOutDevice) {
7876 mPrevOutDevice = type;
7877 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
7878 if (mCallback != 0) {
7879 mCallback->onRoutingChanged(deviceId);
7880 }
7881 }
7882 if (!isOutput() && mPrevInDevice != mInDevice) {
7883 mPrevInDevice = type;
7884 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7885 if (mCallback != 0) {
7886 mCallback->onRoutingChanged(deviceId);
7887 }
7888 }
7889 return status;
7890}
7891
7892status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7893{
7894 status_t status = NO_ERROR;
7895
7896 mInDevice = AUDIO_DEVICE_NONE;
7897
7898 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
7899 supportsAudioPatches : false;
7900
7901 if (supportsAudioPatches) {
7902 status = mHalDevice->releaseAudioPatch(handle);
7903 } else {
7904 AudioParameter param;
7905 param.addInt(String8(AudioParameter::keyRouting), 0);
7906 status = mHalStream->setParameters(param.toString());
7907 }
7908 return status;
7909}
7910
7911void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
7912{
7913 ThreadBase::getAudioPortConfig(config);
7914 if (isOutput()) {
7915 config->role = AUDIO_PORT_ROLE_SOURCE;
7916 config->ext.mix.hw_module = mAudioHwDev->handle();
7917 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
7918 } else {
7919 config->role = AUDIO_PORT_ROLE_SINK;
7920 config->ext.mix.hw_module = mAudioHwDev->handle();
7921 config->ext.mix.usecase.source = mAudioSource;
7922 }
7923}
7924
7925status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
7926{
7927 audio_session_t session = chain->sessionId();
7928
7929 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
7930 // Attach all tracks with same session ID to this chain.
7931 // indicate all active tracks in the chain
7932 for (const sp<MmapTrack> &track : mActiveTracks) {
7933 if (session == track->sessionId()) {
7934 chain->incTrackCnt();
7935 chain->incActiveTrackCnt();
7936 }
7937 }
7938
7939 chain->setThread(this);
7940 chain->setInBuffer(nullptr);
7941 chain->setOutBuffer(nullptr);
7942 chain->syncHalEffectsState();
7943
7944 mEffectChains.add(chain);
7945 checkSuspendOnAddEffectChain_l(chain);
7946 return NO_ERROR;
7947}
7948
7949size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
7950{
7951 audio_session_t session = chain->sessionId();
7952
7953 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
7954
7955 for (size_t i = 0; i < mEffectChains.size(); i++) {
7956 if (chain == mEffectChains[i]) {
7957 mEffectChains.removeAt(i);
7958 // detach all active tracks from the chain
7959 // detach all tracks with same session ID from this chain
7960 for (const sp<MmapTrack> &track : mActiveTracks) {
7961 if (session == track->sessionId()) {
7962 chain->decActiveTrackCnt();
7963 chain->decTrackCnt();
7964 }
7965 }
7966 break;
7967 }
7968 }
7969 return mEffectChains.size();
7970}
7971
7972// hasAudioSession_l() must be called with ThreadBase::mLock held
7973uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
7974{
7975 uint32_t result = 0;
7976 if (getEffectChain_l(sessionId) != 0) {
7977 result = EFFECT_SESSION;
7978 }
7979
7980 for (size_t i = 0; i < mActiveTracks.size(); i++) {
7981 sp<MmapTrack> track = mActiveTracks[i];
7982 if (sessionId == track->sessionId()) {
7983 result |= TRACK_SESSION;
7984 if (track->isFastTrack()) {
7985 result |= FAST_SESSION;
7986 }
7987 break;
7988 }
7989 }
7990
7991 return result;
7992}
7993
7994void AudioFlinger::MmapThread::threadLoop_standby()
7995{
7996 mHalStream->standby();
7997}
7998
7999void AudioFlinger::MmapThread::threadLoop_exit()
8000{
8001 if (mCallback != 0) {
8002 mCallback->onTearDown();
8003 }
8004}
8005
8006status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8007{
8008 return BAD_VALUE;
8009}
8010
8011bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8012{
8013 return false;
8014}
8015
8016status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8017 const effect_descriptor_t *desc, audio_session_t sessionId)
8018{
8019 // No global effect sessions on mmap threads
8020 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8021 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8022 desc->name, mThreadName);
8023 return BAD_VALUE;
8024 }
8025
8026 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8027 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8028 desc->name);
8029 return BAD_VALUE;
8030 }
8031 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
8032 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap thread",
8033 desc->name);
8034 return BAD_VALUE;
8035 }
8036
8037 // Only allow effects without processing load or latency
8038 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8039 return BAD_VALUE;
8040 }
8041
8042 return NO_ERROR;
8043
8044}
8045
8046void AudioFlinger::MmapThread::checkInvalidTracks_l()
8047{
8048 for (const sp<MmapTrack> &track : mActiveTracks) {
8049 if (track->isInvalid()) {
8050 if (mCallback != 0) {
8051 mCallback->onTearDown();
8052 }
8053 break;
8054 }
8055 }
8056}
8057
8058void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8059{
8060 dumpInternals(fd, args);
8061 dumpTracks(fd, args);
8062 dumpEffectChains(fd, args);
8063}
8064
8065void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8066{
8067 dprintf(fd, "\nMmap thread %p:\n", this);
8068
8069 dumpBase(fd, args);
8070
8071 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8072 mAttr.content_type, mAttr.usage, mAttr.source);
8073 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8074 if (mActiveTracks.size() == 0) {
8075 dprintf(fd, " No active clients\n");
8076 }
8077}
8078
8079void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8080{
8081 const size_t SIZE = 256;
8082 char buffer[SIZE];
8083 String8 result;
8084
8085 size_t numtracks = mActiveTracks.size();
8086 dprintf(fd, " %zu Tracks", numtracks);
8087 if (numtracks) {
8088 MmapTrack::appendDumpHeader(result);
8089 for (size_t i = 0; i < numtracks ; ++i) {
8090 sp<MmapTrack> track = mActiveTracks[i];
8091 track->dump(buffer, SIZE);
8092 result.append(buffer);
8093 }
8094 } else {
8095 dprintf(fd, "\n");
8096 }
8097 write(fd, result.string(), result.size());
8098}
8099
8100AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8101 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8102 AudioHwDevice *hwDev, AudioStreamOut *output,
8103 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8104 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8105 mStreamType(AUDIO_STREAM_MUSIC),
8106 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8107{
8108 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8109 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8110 mMasterVolume = audioFlinger->masterVolume_l();
8111 mMasterMute = audioFlinger->masterMute_l();
8112 if (mAudioHwDev) {
8113 if (mAudioHwDev->canSetMasterVolume()) {
8114 mMasterVolume = 1.0;
8115 }
8116
8117 if (mAudioHwDev->canSetMasterMute()) {
8118 mMasterMute = false;
8119 }
8120 }
8121}
8122
8123void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8124 audio_stream_type_t streamType,
8125 audio_session_t sessionId,
8126 const sp<MmapStreamCallback>& callback,
8127 audio_port_handle_t portId)
8128{
8129 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8130 mStreamType = streamType;
8131}
8132
8133AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8134{
8135 Mutex::Autolock _l(mLock);
8136 AudioStreamOut *output = mOutput;
8137 mOutput = NULL;
8138 return output;
8139}
8140
8141void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8142{
8143 Mutex::Autolock _l(mLock);
8144 // Don't apply master volume in SW if our HAL can do it for us.
8145 if (mAudioHwDev &&
8146 mAudioHwDev->canSetMasterVolume()) {
8147 mMasterVolume = 1.0;
8148 } else {
8149 mMasterVolume = value;
8150 }
8151}
8152
8153void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8154{
8155 Mutex::Autolock _l(mLock);
8156 // Don't apply master mute in SW if our HAL can do it for us.
8157 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8158 mMasterMute = false;
8159 } else {
8160 mMasterMute = muted;
8161 }
8162}
8163
8164void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8165{
8166 Mutex::Autolock _l(mLock);
8167 if (stream == mStreamType) {
8168 mStreamVolume = value;
8169 broadcast_l();
8170 }
8171}
8172
8173float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8174{
8175 Mutex::Autolock _l(mLock);
8176 if (stream == mStreamType) {
8177 return mStreamVolume;
8178 }
8179 return 0.0f;
8180}
8181
8182void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8183{
8184 Mutex::Autolock _l(mLock);
8185 if (stream == mStreamType) {
8186 mStreamMute= muted;
8187 broadcast_l();
8188 }
8189}
8190
8191void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8192{
8193 Mutex::Autolock _l(mLock);
8194 if (streamType == mStreamType) {
8195 for (const sp<MmapTrack> &track : mActiveTracks) {
8196 track->invalidate();
8197 }
8198 broadcast_l();
8199 }
8200}
8201
8202void AudioFlinger::MmapPlaybackThread::processVolume_l()
8203{
8204 float volume;
8205
8206 if (mMasterMute || mStreamMute) {
8207 volume = 0;
8208 } else {
8209 volume = mMasterVolume * mStreamVolume;
8210 }
8211
8212 if (volume != mHalVolFloat) {
8213 mHalVolFloat = volume;
8214
8215 // Convert volumes from float to 8.24
8216 uint32_t vol = (uint32_t)(volume * (1 << 24));
8217
8218 // Delegate volume control to effect in track effect chain if needed
8219 // only one effect chain can be present on DirectOutputThread, so if
8220 // there is one, the track is connected to it
8221 if (!mEffectChains.isEmpty()) {
8222 mEffectChains[0]->setVolume_l(&vol, &vol);
8223 volume = (float)vol / (1 << 24);
8224 }
8225
8226 mOutput->stream->setVolume(volume, volume);
8227
8228 if (mCallback != 0) {
8229 int channelCount;
8230 if (isOutput()) {
8231 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8232 } else {
8233 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8234 }
8235 Vector<float> values;
8236 for (int i = 0; i < channelCount; i++) {
8237 values.add(volume);
8238 }
8239 mCallback->onVolumeChanged(mChannelMask, values);
8240 }
8241 }
8242}
8243
8244void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8245{
8246 if (!mMasterMute) {
8247 char value[PROPERTY_VALUE_MAX];
8248 if (property_get("ro.audio.silent", value, "0") > 0) {
8249 char *endptr;
8250 unsigned long ul = strtoul(value, &endptr, 0);
8251 if (*endptr == '\0' && ul != 0) {
8252 ALOGD("Silence is golden");
8253 // The setprop command will not allow a property to be changed after
8254 // the first time it is set, so we don't have to worry about un-muting.
8255 setMasterMute_l(true);
8256 }
8257 }
8258 }
8259}
8260
8261void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8262{
8263 MmapThread::dumpInternals(fd, args);
8264
8265 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n", mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
8266 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8267}
8268
8269AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8270 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8271 AudioHwDevice *hwDev, AudioStreamIn *input,
8272 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8273 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8274 mInput(input)
8275{
8276 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8277 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8278}
8279
8280AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8281{
8282 Mutex::Autolock _l(mLock);
8283 AudioStreamIn *input = mInput;
8284 mInput = NULL;
8285 return input;
8286}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008287} // namespace android