blob: a1d81f9498af0456b4bdb1f796c7de571a0474fb [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)),
Andy Hungdae27702016-10-31 14:01:16 -0700513 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800514{
Eric Laurent296fb132015-05-01 11:38:42 -0700515 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800516}
517
518AudioFlinger::ThreadBase::~ThreadBase()
519{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700521 mConfigEvents.clear();
522
Eric Laurent81784c32012-11-19 14:55:58 -0800523 // do not lock the mutex in destructor
524 releaseWakeLock_l();
525 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800526 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800527 binder->unlinkToDeath(mDeathRecipient);
528 }
529}
530
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700531status_t AudioFlinger::ThreadBase::readyToRun()
532{
533 status_t status = initCheck();
534 if (status == NO_ERROR) {
535 ALOGI("AudioFlinger's thread %p ready to run", this);
536 } else {
537 ALOGE("No working audio driver found.");
538 }
539 return status;
540}
541
Eric Laurent81784c32012-11-19 14:55:58 -0800542void AudioFlinger::ThreadBase::exit()
543{
544 ALOGV("ThreadBase::exit");
545 // do any cleanup required for exit to succeed
546 preExit();
547 {
548 // This lock prevents the following race in thread (uniprocessor for illustration):
549 // if (!exitPending()) {
550 // // context switch from here to exit()
551 // // exit() calls requestExit(), what exitPending() observes
552 // // exit() calls signal(), which is dropped since no waiters
553 // // context switch back from exit() to here
554 // mWaitWorkCV.wait(...);
555 // // now thread is hung
556 // }
557 AutoMutex lock(mLock);
558 requestExit();
559 mWaitWorkCV.broadcast();
560 }
561 // When Thread::requestExitAndWait is made virtual and this method is renamed to
562 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
563 requestExitAndWait();
564}
565
566status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
567{
Eric Laurent81784c32012-11-19 14:55:58 -0800568 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
569 Mutex::Autolock _l(mLock);
570
Eric Laurent10351942014-05-08 18:49:52 -0700571 return sendSetParameterConfigEvent_l(keyValuePairs);
572}
573
574// sendConfigEvent_l() must be called with ThreadBase::mLock held
575// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
576status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
577{
578 status_t status = NO_ERROR;
579
Eric Laurent72e3f392015-05-20 14:43:50 -0700580 if (event->mRequiresSystemReady && !mSystemReady) {
581 event->mWaitStatus = false;
582 mPendingConfigEvents.add(event);
583 return status;
584 }
Eric Laurent10351942014-05-08 18:49:52 -0700585 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700586 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800587 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700588 mLock.unlock();
589 {
590 Mutex::Autolock _l(event->mLock);
591 while (event->mWaitStatus) {
592 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
593 event->mStatus = TIMED_OUT;
594 event->mWaitStatus = false;
595 }
596 }
597 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800598 }
Eric Laurent10351942014-05-08 18:49:52 -0700599 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800600 return status;
601}
602
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700603void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800604{
605 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700606 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800607}
608
609// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700610void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800611{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700612 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700613 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800614}
615
Eric Laurent72e3f392015-05-20 14:43:50 -0700616void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
617{
618 Mutex::Autolock _l(mLock);
619 sendPrioConfigEvent_l(pid, tid, prio);
620}
621
Eric Laurent81784c32012-11-19 14:55:58 -0800622// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
623void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
624{
Eric Laurent10351942014-05-08 18:49:52 -0700625 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
626 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800627}
628
Eric Laurent10351942014-05-08 18:49:52 -0700629// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
630status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
Andy Hung2ddee192015-12-18 17:34:44 -0800632 sp<ConfigEvent> configEvent;
633 AudioParameter param(keyValuePair);
634 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700635 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800636 setMasterMono_l(value != 0);
637 if (param.size() == 1) {
638 return NO_ERROR; // should be a solo parameter - we don't pass down
639 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700640 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800641 configEvent = new SetParameterConfigEvent(param.toString());
642 } else {
643 configEvent = new SetParameterConfigEvent(keyValuePair);
644 }
Eric Laurent10351942014-05-08 18:49:52 -0700645 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700646}
647
Eric Laurent1c333e22014-05-20 10:48:17 -0700648status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
649 const struct audio_patch *patch,
650 audio_patch_handle_t *handle)
651{
652 Mutex::Autolock _l(mLock);
653 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
654 status_t status = sendConfigEvent_l(configEvent);
655 if (status == NO_ERROR) {
656 CreateAudioPatchConfigEventData *data =
657 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
658 *handle = data->mHandle;
659 }
660 return status;
661}
662
663status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
664 const audio_patch_handle_t handle)
665{
666 Mutex::Autolock _l(mLock);
667 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
668 return sendConfigEvent_l(configEvent);
669}
670
671
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700672// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700673void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700674{
Eric Laurent10351942014-05-08 18:49:52 -0700675 bool configChanged = false;
676
Eric Laurent81784c32012-11-19 14:55:58 -0800677 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700678 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700679 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800680 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700681 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700682 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700683 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
684 // FIXME Need to understand why this has to be done asynchronously
685 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700686 true /*asynchronous*/);
687 if (err != 0) {
688 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700689 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700690 }
691 } break;
692 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700693 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700694 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700695 } break;
696 case CFG_EVENT_SET_PARAMETER: {
697 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
698 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
699 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700700 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700701 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700702 case CFG_EVENT_CREATE_AUDIO_PATCH: {
703 CreateAudioPatchConfigEventData *data =
704 (CreateAudioPatchConfigEventData *)event->mData.get();
705 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
706 } break;
707 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
708 ReleaseAudioPatchConfigEventData *data =
709 (ReleaseAudioPatchConfigEventData *)event->mData.get();
710 event->mStatus = releaseAudioPatch_l(data->mHandle);
711 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700712 default:
Eric Laurent10351942014-05-08 18:49:52 -0700713 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700714 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800715 }
Eric Laurent10351942014-05-08 18:49:52 -0700716 {
717 Mutex::Autolock _l(event->mLock);
718 if (event->mWaitStatus) {
719 event->mWaitStatus = false;
720 event->mCond.signal();
721 }
722 }
723 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
724 }
725
726 if (configChanged) {
727 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800728 }
Eric Laurent81784c32012-11-19 14:55:58 -0800729}
730
Marco Nelissenb2208842014-02-07 14:00:50 -0800731String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
732 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700733 const audio_channel_representation_t representation =
734 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700735
736 switch (representation) {
737 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
738 if (output) {
739 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
740 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
741 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
742 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
743 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
744 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
745 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
746 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
747 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
748 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
749 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
750 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
751 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
753 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
754 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
755 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
756 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
757 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
758 } else {
759 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
760 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
761 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
762 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
763 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
764 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
765 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
766 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
767 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
768 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
769 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
770 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
771 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
772 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
773 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
774 }
775 const int len = s.length();
776 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700777 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700778 s.unlockBuffer(len - 2); // remove trailing ", "
779 }
780 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800781 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700782 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
783 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
784 return s;
785 default:
786 s.appendFormat("unknown mask, representation:%d bits:%#x",
787 representation, audio_channel_mask_get_bits(mask));
788 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800789 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800790}
791
Glenn Kasten0f11b512014-01-31 16:18:54 -0800792void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800793{
794 const size_t SIZE = 256;
795 char buffer[SIZE];
796 String8 result;
797
798 bool locked = AudioFlinger::dumpTryLock(mLock);
799 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700800 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800801 }
802
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800803 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700804 dprintf(fd, " I/O handle: %d\n", mId);
805 dprintf(fd, " TID: %d\n", getTid());
806 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700807 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700808 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700809 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700810 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700811 dprintf(fd, " Channel count: %u\n", mChannelCount);
812 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800813 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700814 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700815 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700816 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800817 size_t numConfig = mConfigEvents.size();
818 if (numConfig) {
819 for (size_t i = 0; i < numConfig; i++) {
820 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800822 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800824 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700825 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800826 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700827 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
828 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800829 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800830
831 if (locked) {
832 mLock.unlock();
833 }
834}
835
836void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
837{
838 const size_t SIZE = 256;
839 char buffer[SIZE];
840 String8 result;
841
Marco Nelissenb2208842014-02-07 14:00:50 -0800842 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000843 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800844 write(fd, buffer, strlen(buffer));
845
Marco Nelissenb2208842014-02-07 14:00:50 -0800846 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800847 sp<EffectChain> chain = mEffectChains[i];
848 if (chain != 0) {
849 chain->dump(fd, args);
850 }
851 }
852}
853
Andy Hungdae27702016-10-31 14:01:16 -0700854void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800855{
856 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700857 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800858}
859
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100860String16 AudioFlinger::ThreadBase::getWakeLockTag()
861{
862 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800863 case MIXER:
864 return String16("AudioMix");
865 case DIRECT:
866 return String16("AudioDirectOut");
867 case DUPLICATING:
868 return String16("AudioDup");
869 case RECORD:
870 return String16("AudioIn");
871 case OFFLOAD:
872 return String16("AudioOffload");
873 default:
874 ALOG_ASSERT(false);
875 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100876 }
877}
878
Andy Hungdae27702016-10-31 14:01:16 -0700879void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800880{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800881 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800882 if (mPowerManager != 0) {
883 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700884 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
885 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700886 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100887 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700888 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700889 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800890 if (status == NO_ERROR) {
891 mWakeLockToken = binder;
892 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800893 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800894 }
Wei Jia3f273d12015-11-24 09:06:49 -0800895
Andy Hung3f0c9022016-01-15 17:49:46 -0800896 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800897 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
898 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800899}
900
901void AudioFlinger::ThreadBase::releaseWakeLock()
902{
903 Mutex::Autolock _l(mLock);
904 releaseWakeLock_l();
905}
906
907void AudioFlinger::ThreadBase::releaseWakeLock_l()
908{
Andy Hung3f0c9022016-01-15 17:49:46 -0800909 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800911 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800912 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700913 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
914 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800915 }
916 mWakeLockToken.clear();
917 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800918}
919
920void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700921 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800922 // use checkService() to avoid blocking if power service is not up yet
923 sp<IBinder> binder =
924 defaultServiceManager()->checkService(String16("power"));
925 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800926 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800927 } else {
928 mPowerManager = interface_cast<IPowerManager>(binder);
929 binder->linkToDeath(mDeathRecipient);
930 }
931 }
932}
933
Andy Hungd01b0f12016-11-07 16:10:30 -0800934void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800935 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700936
937#if !LOG_NDEBUG
938 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800939 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700940 s << uid << " ";
941 }
942 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
943#endif
944
Andy Hung438e7572015-12-14 15:51:17 -0800945 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
946 if (mSystemReady) {
947 ALOGE("no wake lock to update, but system ready!");
948 } else {
949 ALOGW("no wake lock to update, system not ready yet");
950 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 return;
952 }
953 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800954 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
955 status_t status = mPowerManager->updateWakeLockUids(
956 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
957 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800958 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800959 }
960}
961
Eric Laurent81784c32012-11-19 14:55:58 -0800962void AudioFlinger::ThreadBase::clearPowerManager()
963{
964 Mutex::Autolock _l(mLock);
965 releaseWakeLock_l();
966 mPowerManager.clear();
967}
968
Glenn Kasten0f11b512014-01-31 16:18:54 -0800969void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800970{
971 sp<ThreadBase> thread = mThread.promote();
972 if (thread != 0) {
973 thread->clearPowerManager();
974 }
975 ALOGW("power manager service died !!!");
976}
977
978void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800979 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800980{
981 Mutex::Autolock _l(mLock);
982 setEffectSuspended_l(type, suspend, sessionId);
983}
984
985void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800986 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800987{
988 sp<EffectChain> chain = getEffectChain_l(sessionId);
989 if (chain != 0) {
990 if (type != NULL) {
991 chain->setEffectSuspended_l(type, suspend);
992 } else {
993 chain->setEffectSuspendedAll_l(suspend);
994 }
995 }
996
997 updateSuspendedSessions_l(type, suspend, sessionId);
998}
999
1000void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1001{
1002 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1003 if (index < 0) {
1004 return;
1005 }
1006
1007 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1008 mSuspendedSessions.valueAt(index);
1009
1010 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001011 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001012 for (int j = 0; j < desc->mRefCount; j++) {
1013 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1014 chain->setEffectSuspendedAll_l(true);
1015 } else {
1016 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1017 desc->mType.timeLow);
1018 chain->setEffectSuspended_l(&desc->mType, true);
1019 }
1020 }
1021 }
1022}
1023
1024void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1025 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001026 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001027{
1028 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1029
1030 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1031
1032 if (suspend) {
1033 if (index >= 0) {
1034 sessionEffects = mSuspendedSessions.valueAt(index);
1035 } else {
1036 mSuspendedSessions.add(sessionId, sessionEffects);
1037 }
1038 } else {
1039 if (index < 0) {
1040 return;
1041 }
1042 sessionEffects = mSuspendedSessions.valueAt(index);
1043 }
1044
1045
1046 int key = EffectChain::kKeyForSuspendAll;
1047 if (type != NULL) {
1048 key = type->timeLow;
1049 }
1050 index = sessionEffects.indexOfKey(key);
1051
1052 sp<SuspendedSessionDesc> desc;
1053 if (suspend) {
1054 if (index >= 0) {
1055 desc = sessionEffects.valueAt(index);
1056 } else {
1057 desc = new SuspendedSessionDesc();
1058 if (type != NULL) {
1059 desc->mType = *type;
1060 }
1061 sessionEffects.add(key, desc);
1062 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1063 }
1064 desc->mRefCount++;
1065 } else {
1066 if (index < 0) {
1067 return;
1068 }
1069 desc = sessionEffects.valueAt(index);
1070 if (--desc->mRefCount == 0) {
1071 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1072 sessionEffects.removeItemsAt(index);
1073 if (sessionEffects.isEmpty()) {
1074 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1075 sessionId);
1076 mSuspendedSessions.removeItem(sessionId);
1077 }
1078 }
1079 }
1080 if (!sessionEffects.isEmpty()) {
1081 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1082 }
1083}
1084
1085void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1086 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001087 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001088{
1089 Mutex::Autolock _l(mLock);
1090 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1091}
1092
1093void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1094 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001095 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001096{
1097 if (mType != RECORD) {
1098 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1099 // another session. This gives the priority to well behaved effect control panels
1100 // and applications not using global effects.
1101 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1102 // global effects
1103 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1104 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1105 }
1106 }
1107
1108 sp<EffectChain> chain = getEffectChain_l(sessionId);
1109 if (chain != 0) {
1110 chain->checkSuspendOnEffectEnabled(effect, enabled);
1111 }
1112}
1113
Eric Laurent4c415062016-06-17 16:14:16 -07001114// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1115status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1116 const effect_descriptor_t *desc, audio_session_t sessionId)
1117{
1118 // No global effect sessions on record threads
1119 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1120 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1121 desc->name, mThreadName);
1122 return BAD_VALUE;
1123 }
1124 // only pre processing effects on record thread
1125 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1126 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1127 desc->name, mThreadName);
1128 return BAD_VALUE;
1129 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001130
1131 // always allow effects without processing load or latency
1132 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1133 return NO_ERROR;
1134 }
1135
Eric Laurent4c415062016-06-17 16:14:16 -07001136 audio_input_flags_t flags = mInput->flags;
1137 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1138 if (flags & AUDIO_INPUT_FLAG_RAW) {
1139 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1140 desc->name, mThreadName);
1141 return BAD_VALUE;
1142 }
1143 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1144 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1145 desc->name, mThreadName);
1146 return BAD_VALUE;
1147 }
1148 }
1149 return NO_ERROR;
1150}
1151
1152// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1153status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1154 const effect_descriptor_t *desc, audio_session_t sessionId)
1155{
1156 // no preprocessing on playback threads
1157 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1158 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1159 " thread %s", desc->name, mThreadName);
1160 return BAD_VALUE;
1161 }
1162
1163 switch (mType) {
1164 case MIXER: {
1165 // Reject any effect on mixer multichannel sinks.
1166 // TODO: fix both format and multichannel issues with effects.
1167 if (mChannelCount != FCC_2) {
1168 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1169 " thread %s", desc->name, mChannelCount, mThreadName);
1170 return BAD_VALUE;
1171 }
1172 audio_output_flags_t flags = mOutput->flags;
1173 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1174 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1175 // global effects are applied only to non fast tracks if they are SW
1176 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1177 break;
1178 }
1179 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1180 // only post processing on output stage session
1181 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1182 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1183 " on output stage session", desc->name);
1184 return BAD_VALUE;
1185 }
1186 } else {
1187 // no restriction on effects applied on non fast tracks
1188 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1189 break;
1190 }
1191 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001192
1193 // always allow effects without processing load or latency
1194 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1195 break;
1196 }
Eric Laurent4c415062016-06-17 16:14:16 -07001197 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1198 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1199 desc->name);
1200 return BAD_VALUE;
1201 }
1202 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1203 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1204 " in fast mode", desc->name);
1205 return BAD_VALUE;
1206 }
1207 }
1208 } break;
1209 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001210 // nothing actionable on offload threads, if the effect:
1211 // - is offloadable: the effect can be created
1212 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1213 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001214 break;
1215 case DIRECT:
1216 // Reject any effect on Direct output threads for now, since the format of
1217 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1218 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1219 desc->name, mThreadName);
1220 return BAD_VALUE;
1221 case DUPLICATING:
1222 // Reject any effect on mixer multichannel sinks.
1223 // TODO: fix both format and multichannel issues with effects.
1224 if (mChannelCount != FCC_2) {
1225 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1226 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1227 return BAD_VALUE;
1228 }
1229 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1230 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1231 " thread %s", desc->name, mThreadName);
1232 return BAD_VALUE;
1233 }
1234 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1235 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1236 " DUPLICATING thread %s", desc->name, mThreadName);
1237 return BAD_VALUE;
1238 }
1239 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1240 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1241 " DUPLICATING thread %s", desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 break;
1245 default:
1246 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1247 }
1248
1249 return NO_ERROR;
1250}
1251
Eric Laurent81784c32012-11-19 14:55:58 -08001252// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1253sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1254 const sp<AudioFlinger::Client>& client,
1255 const sp<IEffectClient>& effectClient,
1256 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001257 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001258 effect_descriptor_t *desc,
1259 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001260 status_t *status,
1261 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001262{
1263 sp<EffectModule> effect;
1264 sp<EffectHandle> handle;
1265 status_t lStatus;
1266 sp<EffectChain> chain;
1267 bool chainCreated = false;
1268 bool effectCreated = false;
1269 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001270 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001271
1272 lStatus = initCheck();
1273 if (lStatus != NO_ERROR) {
1274 ALOGW("createEffect_l() Audio driver not initialized.");
1275 goto Exit;
1276 }
1277
Eric Laurent81784c32012-11-19 14:55:58 -08001278 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1279
1280 { // scope for mLock
1281 Mutex::Autolock _l(mLock);
1282
Eric Laurent4c415062016-06-17 16:14:16 -07001283 lStatus = checkEffectCompatibility_l(desc, sessionId);
1284 if (lStatus != NO_ERROR) {
1285 goto Exit;
1286 }
1287
Eric Laurent81784c32012-11-19 14:55:58 -08001288 // check for existing effect chain with the requested audio session
1289 chain = getEffectChain_l(sessionId);
1290 if (chain == 0) {
1291 // create a new chain for this session
1292 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1293 chain = new EffectChain(this, sessionId);
1294 addEffectChain_l(chain);
1295 chain->setStrategy(getStrategyForSession_l(sessionId));
1296 chainCreated = true;
1297 } else {
1298 effect = chain->getEffectFromDesc_l(desc);
1299 }
1300
1301 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1302
1303 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001304 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001305 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001306 lStatus = AudioSystem::registerEffect(
1307 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001308 if (lStatus != NO_ERROR) {
1309 goto Exit;
1310 }
1311 effectRegistered = true;
1312 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001313 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001314 if (lStatus != NO_ERROR) {
1315 goto Exit;
1316 }
1317 effectCreated = true;
1318
1319 effect->setDevice(mOutDevice);
1320 effect->setDevice(mInDevice);
1321 effect->setMode(mAudioFlinger->getMode());
1322 effect->setAudioSource(mAudioSource);
1323 }
1324 // create effect handle and connect it to effect module
1325 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001326 lStatus = handle->initCheck();
1327 if (lStatus == OK) {
1328 lStatus = effect->addHandle(handle.get());
1329 }
Eric Laurent81784c32012-11-19 14:55:58 -08001330 if (enabled != NULL) {
1331 *enabled = (int)effect->isEnabled();
1332 }
1333 }
1334
1335Exit:
1336 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1337 Mutex::Autolock _l(mLock);
1338 if (effectCreated) {
1339 chain->removeEffect_l(effect);
1340 }
1341 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001342 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001343 }
1344 if (chainCreated) {
1345 removeEffectChain_l(chain);
1346 }
1347 handle.clear();
1348 }
1349
Glenn Kasten9156ef32013-08-06 15:39:08 -07001350 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001351 return handle;
1352}
1353
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001354void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1355 bool unpinIfLast)
1356{
1357 bool remove = false;
1358 sp<EffectModule> effect;
1359 {
1360 Mutex::Autolock _l(mLock);
1361
1362 effect = handle->effect().promote();
1363 if (effect == 0) {
1364 return;
1365 }
1366 // restore suspended effects if the disconnected handle was enabled and the last one.
1367 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1368 if (remove) {
1369 removeEffect_l(effect, true);
1370 }
1371 }
1372 if (remove) {
1373 mAudioFlinger->updateOrphanEffectChains(effect);
1374 AudioSystem::unregisterEffect(effect->id());
1375 if (handle->enabled()) {
1376 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1377 }
1378 }
1379}
1380
Glenn Kastend848eb42016-03-08 13:42:11 -08001381sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1382 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001383{
1384 Mutex::Autolock _l(mLock);
1385 return getEffect_l(sessionId, effectId);
1386}
1387
Glenn Kastend848eb42016-03-08 13:42:11 -08001388sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1389 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001390{
1391 sp<EffectChain> chain = getEffectChain_l(sessionId);
1392 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1393}
1394
1395// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1396// PlaybackThread::mLock held
1397status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1398{
1399 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001400 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001401 sp<EffectChain> chain = getEffectChain_l(sessionId);
1402 bool chainCreated = false;
1403
Eric Laurent5baf2af2013-09-12 17:37:00 -07001404 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1405 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1406 this, effect->desc().name, effect->desc().flags);
1407
Eric Laurent81784c32012-11-19 14:55:58 -08001408 if (chain == 0) {
1409 // create a new chain for this session
1410 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1411 chain = new EffectChain(this, sessionId);
1412 addEffectChain_l(chain);
1413 chain->setStrategy(getStrategyForSession_l(sessionId));
1414 chainCreated = true;
1415 }
1416 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1417
1418 if (chain->getEffectFromId_l(effect->id()) != 0) {
1419 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1420 this, effect->desc().name, chain.get());
1421 return BAD_VALUE;
1422 }
1423
Eric Laurent5baf2af2013-09-12 17:37:00 -07001424 effect->setOffloaded(mType == OFFLOAD, mId);
1425
Eric Laurent81784c32012-11-19 14:55:58 -08001426 status_t status = chain->addEffect_l(effect);
1427 if (status != NO_ERROR) {
1428 if (chainCreated) {
1429 removeEffectChain_l(chain);
1430 }
1431 return status;
1432 }
1433
1434 effect->setDevice(mOutDevice);
1435 effect->setDevice(mInDevice);
1436 effect->setMode(mAudioFlinger->getMode());
1437 effect->setAudioSource(mAudioSource);
1438 return NO_ERROR;
1439}
1440
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001441void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001442
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001443 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001444 effect_descriptor_t desc = effect->desc();
1445 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1446 detachAuxEffect_l(effect->id());
1447 }
1448
1449 sp<EffectChain> chain = effect->chain().promote();
1450 if (chain != 0) {
1451 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001452 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001453 removeEffectChain_l(chain);
1454 }
1455 } else {
1456 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1457 }
1458}
1459
1460void AudioFlinger::ThreadBase::lockEffectChains_l(
1461 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1462{
1463 effectChains = mEffectChains;
1464 for (size_t i = 0; i < mEffectChains.size(); i++) {
1465 mEffectChains[i]->lock();
1466 }
1467}
1468
1469void AudioFlinger::ThreadBase::unlockEffectChains(
1470 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1471{
1472 for (size_t i = 0; i < effectChains.size(); i++) {
1473 effectChains[i]->unlock();
1474 }
1475}
1476
Glenn Kastend848eb42016-03-08 13:42:11 -08001477sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001478{
1479 Mutex::Autolock _l(mLock);
1480 return getEffectChain_l(sessionId);
1481}
1482
Glenn Kastend848eb42016-03-08 13:42:11 -08001483sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1484 const
Eric Laurent81784c32012-11-19 14:55:58 -08001485{
1486 size_t size = mEffectChains.size();
1487 for (size_t i = 0; i < size; i++) {
1488 if (mEffectChains[i]->sessionId() == sessionId) {
1489 return mEffectChains[i];
1490 }
1491 }
1492 return 0;
1493}
1494
1495void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1496{
1497 Mutex::Autolock _l(mLock);
1498 size_t size = mEffectChains.size();
1499 for (size_t i = 0; i < size; i++) {
1500 mEffectChains[i]->setMode_l(mode);
1501 }
1502}
1503
Eric Laurent83b88082014-06-20 18:31:16 -07001504void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1505{
1506 config->type = AUDIO_PORT_TYPE_MIX;
1507 config->ext.mix.handle = mId;
1508 config->sample_rate = mSampleRate;
1509 config->format = mFormat;
1510 config->channel_mask = mChannelMask;
1511 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1512 AUDIO_PORT_CONFIG_FORMAT;
1513}
1514
Eric Laurent72e3f392015-05-20 14:43:50 -07001515void AudioFlinger::ThreadBase::systemReady()
1516{
1517 Mutex::Autolock _l(mLock);
1518 if (mSystemReady) {
1519 return;
1520 }
1521 mSystemReady = true;
1522
1523 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1524 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1525 }
1526 mPendingConfigEvents.clear();
1527}
1528
Andy Hungdae27702016-10-31 14:01:16 -07001529template <typename T>
1530ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1531 ssize_t index = mActiveTracks.indexOf(track);
1532 if (index >= 0) {
1533 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1534 return index;
1535 }
1536 mActiveTracksGeneration++;
1537 mLatestActiveTrack = track;
1538 ++mBatteryCounter[track->uid()].second;
1539 return mActiveTracks.add(track);
1540}
1541
1542template <typename T>
1543ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1544 ssize_t index = mActiveTracks.remove(track);
1545 if (index < 0) {
1546 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1547 return index;
1548 }
1549 mActiveTracksGeneration++;
1550 --mBatteryCounter[track->uid()].second;
1551 // mLatestActiveTrack is not cleared even if is the same as track.
1552 return index;
1553}
1554
1555template <typename T>
1556void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1557 for (const sp<T> &track : mActiveTracks) {
1558 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1559 }
1560 mLastActiveTracksGeneration = mActiveTracksGeneration;
1561 mActiveTracks.clear();
1562 mLatestActiveTrack.clear();
1563 mBatteryCounter.clear();
1564}
1565
1566template <typename T>
1567void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1568 sp<ThreadBase> thread, bool force) {
1569 // Updates ActiveTracks client uids to the thread wakelock.
1570 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1571 thread->updateWakeLockUids_l(getWakeLockUids());
1572 mLastActiveTracksGeneration = mActiveTracksGeneration;
1573 }
1574
1575 // Updates BatteryNotifier uids
1576 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1577 const uid_t uid = it->first;
1578 ssize_t &previous = it->second.first;
1579 ssize_t &current = it->second.second;
1580 if (current > 0) {
1581 if (previous == 0) {
1582 BatteryNotifier::getInstance().noteStartAudio(uid);
1583 }
1584 previous = current;
1585 ++it;
1586 } else if (current == 0) {
1587 if (previous > 0) {
1588 BatteryNotifier::getInstance().noteStopAudio(uid);
1589 }
1590 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1591 } else /* (current < 0) */ {
1592 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1593 }
1594 }
1595}
Eric Laurent83b88082014-06-20 18:31:16 -07001596
Eric Laurent81784c32012-11-19 14:55:58 -08001597// ----------------------------------------------------------------------------
1598// Playback
1599// ----------------------------------------------------------------------------
1600
1601AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1602 AudioStreamOut* output,
1603 audio_io_handle_t id,
1604 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001605 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001606 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001607 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001608 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001609 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001610 mMixerBuffer(NULL),
1611 mMixerBufferSize(0),
1612 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1613 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001614 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001615 mEffectBuffer(NULL),
1616 mEffectBufferSize(0),
1617 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1618 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001619 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001620 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001621 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001622 // mStreamTypes[] initialized in constructor body
1623 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001624 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001625 mMixerStatus(MIXER_IDLE),
1626 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001627 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001628 mBytesRemaining(0),
1629 mCurrentWriteLength(0),
1630 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001631 mWriteAckSequence(0),
1632 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001633 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001634 mScreenState(AudioFlinger::mScreenState),
1635 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001636 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001637 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001638{
Glenn Kastend7dca052015-03-05 16:05:54 -08001639 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1640 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001641
1642 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1643 // it would be safer to explicitly pass initial masterVolume/masterMute as
1644 // parameter.
1645 //
1646 // If the HAL we are using has support for master volume or master mute,
1647 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1648 // and the mute set to false).
1649 mMasterVolume = audioFlinger->masterVolume_l();
1650 mMasterMute = audioFlinger->masterMute_l();
1651 if (mOutput && mOutput->audioHwDev) {
1652 if (mOutput->audioHwDev->canSetMasterVolume()) {
1653 mMasterVolume = 1.0;
1654 }
1655
1656 if (mOutput->audioHwDev->canSetMasterMute()) {
1657 mMasterMute = false;
1658 }
1659 }
1660
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001661 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001662
Eric Laurent223fd5c2014-11-11 13:43:36 -08001663 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001664 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001665 stream = (audio_stream_type_t) (stream + 1)) {
1666 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1667 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1668 }
Eric Laurent81784c32012-11-19 14:55:58 -08001669}
1670
1671AudioFlinger::PlaybackThread::~PlaybackThread()
1672{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001673 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001674 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001675 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001676 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001677}
1678
1679void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1680{
1681 dumpInternals(fd, args);
1682 dumpTracks(fd, args);
1683 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001684 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001685}
1686
Glenn Kasten0f11b512014-01-31 16:18:54 -08001687void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001688{
1689 const size_t SIZE = 256;
1690 char buffer[SIZE];
1691 String8 result;
1692
Marco Nelissenb2208842014-02-07 14:00:50 -08001693 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001694 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1695 const stream_type_t *st = &mStreamTypes[i];
1696 if (i > 0) {
1697 result.appendFormat(", ");
1698 }
1699 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1700 if (st->mute) {
1701 result.append("M");
1702 }
1703 }
1704 result.append("\n");
1705 write(fd, result.string(), result.length());
1706 result.clear();
1707
Eric Laurent81784c32012-11-19 14:55:58 -08001708 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1709 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001710 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001711 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001712
1713 size_t numtracks = mTracks.size();
1714 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001715 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001716 size_t numactiveseen = 0;
1717 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001718 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001719 Track::appendDumpHeader(result);
1720 for (size_t i = 0; i < numtracks; ++i) {
1721 sp<Track> track = mTracks[i];
1722 if (track != 0) {
1723 bool active = mActiveTracks.indexOf(track) >= 0;
1724 if (active) {
1725 numactiveseen++;
1726 }
1727 track->dump(buffer, SIZE, active);
1728 result.append(buffer);
1729 }
1730 }
1731 } else {
1732 result.append("\n");
1733 }
1734 if (numactiveseen != numactive) {
1735 // some tracks in the active list were not in the tracks list
1736 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1737 " not in the track list\n");
1738 result.append(buffer);
1739 Track::appendDumpHeader(result);
1740 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001741 sp<Track> track = mActiveTracks[i];
1742 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001743 track->dump(buffer, SIZE, true);
1744 result.append(buffer);
1745 }
1746 }
1747 }
1748
1749 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001750}
1751
1752void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1753{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001754 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001755
1756 dumpBase(fd, args);
1757
Elliott Hughes87cebad2014-05-22 10:14:43 -07001758 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001759 dprintf(fd, " Last write occurred (msecs): %llu\n",
1760 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001761 dprintf(fd, " Total writes: %d\n", mNumWrites);
1762 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1763 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1764 dprintf(fd, " Suspend count: %d\n", mSuspended);
1765 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1766 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1767 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1768 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001769 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001770 AudioStreamOut *output = mOutput;
1771 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001772 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1773 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001774 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1775 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1776 if (mPipeSink.get() != nullptr) {
1777 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1778 }
1779 if (output != nullptr) {
1780 dprintf(fd, " Hal stream dump:\n");
1781 (void)output->stream->dump(fd);
1782 }
Eric Laurent81784c32012-11-19 14:55:58 -08001783}
1784
1785// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001786
1787void AudioFlinger::PlaybackThread::onFirstRef()
1788{
Glenn Kastend7dca052015-03-05 16:05:54 -08001789 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001790}
1791
1792// ThreadBase virtuals
1793void AudioFlinger::PlaybackThread::preExit()
1794{
1795 ALOGV(" preExit()");
1796 // FIXME this is using hard-coded strings but in the future, this functionality will be
1797 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001798 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1799 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001800}
1801
1802// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1803sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1804 const sp<AudioFlinger::Client>& client,
1805 audio_stream_type_t streamType,
1806 uint32_t sampleRate,
1807 audio_format_t format,
1808 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001809 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001810 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001811 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001812 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001813 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001814 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001815 status_t *status,
1816 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001817{
Glenn Kasten74935e42013-12-19 08:56:45 -08001818 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001819 sp<Track> track;
1820 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001821 audio_output_flags_t outputFlags = mOutput->flags;
1822
1823 // special case for FAST flag considered OK if fast mixer is present
1824 if (hasFastMixer()) {
1825 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1826 }
1827
1828 // Check if requested flags are compatible with output stream flags
1829 if ((*flags & outputFlags) != *flags) {
1830 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1831 *flags, outputFlags);
1832 *flags = (audio_output_flags_t)(*flags & outputFlags);
1833 }
Eric Laurent81784c32012-11-19 14:55:58 -08001834
Eric Laurent81784c32012-11-19 14:55:58 -08001835 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001836 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001837 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001838 // PCM data
1839 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001840 // TODO: extract as a data library function that checks that a computationally
1841 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001842 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001843 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1844 (channelMask == AUDIO_CHANNEL_OUT_MONO
1845 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001846 // hardware sample rate
1847 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001848 // normal mixer has an associated fast mixer
1849 hasFastMixer() &&
1850 // there are sufficient fast track slots available
1851 (mFastTrackAvailMask != 0)
1852 // FIXME test that MixerThread for this fast track has a capable output HAL
1853 // FIXME add a permission test also?
1854 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001855 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1856 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001857 // read the fast track multiplier property the first time it is needed
1858 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1859 if (ok != 0) {
1860 ALOGE("%s pthread_once failed: %d", __func__, ok);
1861 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001862 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001863 }
Eric Laurent4c415062016-06-17 16:14:16 -07001864
1865 // check compatibility with audio effects.
1866 { // scope for mLock
1867 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001868 for (audio_session_t session : {
1869 AUDIO_SESSION_OUTPUT_STAGE,
1870 AUDIO_SESSION_OUTPUT_MIX,
1871 sessionId,
1872 }) {
1873 sp<EffectChain> chain = getEffectChain_l(session);
1874 if (chain.get() != nullptr) {
1875 audio_output_flags_t old = *flags;
1876 chain->checkOutputFlagCompatibility(flags);
1877 if (old != *flags) {
1878 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1879 (int)session, (int)old, (int)*flags);
1880 }
Eric Laurent4c415062016-06-17 16:14:16 -07001881 }
1882 }
1883 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001884 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001885 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1886 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001887 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001888 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1889 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001890 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001891 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001892 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001893 audio_is_linear_pcm(format),
1894 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001895 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001896 }
1897 }
1898 // For normal PCM streaming tracks, update minimum frame count.
1899 // For compatibility with AudioTrack calculation, buffer depth is forced
1900 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1901 // This is probably too conservative, but legacy application code may depend on it.
1902 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001903 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001904 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001905 // this must match AudioTrack.cpp calculateMinFrameCount().
1906 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001907 uint32_t latencyMs = 0;
1908 lStatus = mOutput->stream->getLatency(&latencyMs);
1909 if (lStatus != OK) {
1910 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1911 goto Exit;
1912 }
Eric Laurent81784c32012-11-19 14:55:58 -08001913 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1914 if (minBufCount < 2) {
1915 minBufCount = 2;
1916 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001917 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1918 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001919 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001920 minBufCount * sourceFramesNeededWithTimestretch(
1921 sampleRate, mNormalFrameCount,
1922 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001923 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001924 frameCount = minFrameCount;
1925 }
Eric Laurent81784c32012-11-19 14:55:58 -08001926 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001927 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001928
Glenn Kastenc3df8382014-03-13 15:05:25 -07001929 switch (mType) {
1930
1931 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001932 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001933 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001934 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1935 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001936 sampleRate, format, channelMask, mOutput, mFormat);
1937 lStatus = BAD_VALUE;
1938 goto Exit;
1939 }
1940 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001941 break;
1942
1943 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001944 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001945 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1946 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001947 sampleRate, format, channelMask, mOutput, mFormat);
1948 lStatus = BAD_VALUE;
1949 goto Exit;
1950 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001951 break;
1952
1953 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001954 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001955 ALOGE("createTrack_l() Bad parameter: format %#x \""
1956 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001957 format, mOutput, mFormat);
1958 lStatus = BAD_VALUE;
1959 goto Exit;
1960 }
Andy Hungcd044842014-08-07 11:04:34 -07001961 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001962 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1963 lStatus = BAD_VALUE;
1964 goto Exit;
1965 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001966 break;
1967
Eric Laurent81784c32012-11-19 14:55:58 -08001968 }
1969
1970 lStatus = initCheck();
1971 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001972 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001973 goto Exit;
1974 }
1975
1976 { // scope for mLock
1977 Mutex::Autolock _l(mLock);
1978
1979 // all tracks in same audio session must share the same routing strategy otherwise
1980 // conflicts will happen when tracks are moved from one output to another by audio policy
1981 // manager
1982 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1983 for (size_t i = 0; i < mTracks.size(); ++i) {
1984 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001985 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001986 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1987 if (sessionId == t->sessionId() && strategy != actual) {
1988 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1989 strategy, actual);
1990 lStatus = BAD_VALUE;
1991 goto Exit;
1992 }
1993 }
1994 }
1995
Glenn Kastend79072e2016-01-06 08:41:20 -08001996 track = new Track(this, client, streamType, sampleRate, format,
1997 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001998 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07001999
Glenn Kasten03003332013-08-06 15:40:54 -07002000 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2001 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002002 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002003 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002004 goto Exit;
2005 }
2006 mTracks.add(track);
2007
2008 sp<EffectChain> chain = getEffectChain_l(sessionId);
2009 if (chain != 0) {
2010 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2011 track->setMainBuffer(chain->inBuffer());
2012 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2013 chain->incTrackCnt();
2014 }
2015
Eric Laurent05067782016-06-01 18:27:28 -07002016 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002017 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2018 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2019 // so ask activity manager to do this on our behalf
2020 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2021 }
2022 }
2023
2024 lStatus = NO_ERROR;
2025
2026Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002027 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002028 return track;
2029}
2030
2031uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2032{
2033 return latency;
2034}
2035
2036uint32_t AudioFlinger::PlaybackThread::latency() const
2037{
2038 Mutex::Autolock _l(mLock);
2039 return latency_l();
2040}
2041uint32_t AudioFlinger::PlaybackThread::latency_l() const
2042{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002043 uint32_t latency;
2044 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2045 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002046 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002047 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002048}
2049
2050void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2051{
2052 Mutex::Autolock _l(mLock);
2053 // Don't apply master volume in SW if our HAL can do it for us.
2054 if (mOutput && mOutput->audioHwDev &&
2055 mOutput->audioHwDev->canSetMasterVolume()) {
2056 mMasterVolume = 1.0;
2057 } else {
2058 mMasterVolume = value;
2059 }
2060}
2061
2062void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2063{
2064 Mutex::Autolock _l(mLock);
2065 // Don't apply master mute in SW if our HAL can do it for us.
2066 if (mOutput && mOutput->audioHwDev &&
2067 mOutput->audioHwDev->canSetMasterMute()) {
2068 mMasterMute = false;
2069 } else {
2070 mMasterMute = muted;
2071 }
2072}
2073
2074void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2075{
2076 Mutex::Autolock _l(mLock);
2077 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002078 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002079}
2080
2081void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2082{
2083 Mutex::Autolock _l(mLock);
2084 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002085 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002086}
2087
2088float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2089{
2090 Mutex::Autolock _l(mLock);
2091 return mStreamTypes[stream].volume;
2092}
2093
2094// addTrack_l() must be called with ThreadBase::mLock held
2095status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2096{
2097 status_t status = ALREADY_EXISTS;
2098
Eric Laurent81784c32012-11-19 14:55:58 -08002099 if (mActiveTracks.indexOf(track) < 0) {
2100 // the track is newly added, make sure it fills up all its
2101 // buffers before playing. This is to ensure the client will
2102 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002103 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002104 TrackBase::track_state state = track->mState;
2105 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002106 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002107 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002108 mLock.lock();
2109 // abort track was stopped/paused while we released the lock
2110 if (state != track->mState) {
2111 if (status == NO_ERROR) {
2112 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002113 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002114 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002115 mLock.lock();
2116 }
2117 return INVALID_OPERATION;
2118 }
2119 // abort if start is rejected by audio policy manager
2120 if (status != NO_ERROR) {
2121 return PERMISSION_DENIED;
2122 }
2123#ifdef ADD_BATTERY_DATA
2124 // to track the speaker usage
2125 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2126#endif
2127 }
2128
Eric Laurent51716182016-02-29 18:00:56 -08002129 // set retry count for buffer fill
2130 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002131 if (track->isStopping_1()) {
2132 track->mRetryCount = kMaxTrackStopRetriesOffload;
2133 } else {
2134 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2135 }
2136 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002137 } else {
2138 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002139 track->mFillingUpStatus =
2140 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002141 }
2142
Eric Laurent81784c32012-11-19 14:55:58 -08002143 track->mResetDone = false;
2144 track->mPresentationCompleteFrames = 0;
2145 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002146 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2147 if (chain != 0) {
2148 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2149 track->sessionId());
2150 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002151 }
2152
Andy Hung2148bf02016-11-28 19:01:02 -08002153 char buffer[256];
2154 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2155 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2156
Eric Laurent81784c32012-11-19 14:55:58 -08002157 status = NO_ERROR;
2158 }
2159
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002160 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002161 return status;
2162}
2163
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002165{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002166 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002167 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002168 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2169 track->mState = TrackBase::STOPPED;
2170 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002171 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002172 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002173 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002174 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002175
2176 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002177}
2178
2179void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2180{
2181 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002182
2183 char buffer[256];
2184 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2185 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2186
Eric Laurent81784c32012-11-19 14:55:58 -08002187 mTracks.remove(track);
2188 deleteTrackName_l(track->name());
2189 // redundant as track is about to be destroyed, for dumpsys only
2190 track->mName = -1;
2191 if (track->isFastTrack()) {
2192 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002193 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002194 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2195 mFastTrackAvailMask |= 1 << index;
2196 // redundant as track is about to be destroyed, for dumpsys only
2197 track->mFastIndex = -1;
2198 }
2199 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2200 if (chain != 0) {
2201 chain->decTrackCnt();
2202 }
2203}
2204
Eric Laurentede6c3b2013-09-19 14:37:46 -07002205void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206{
2207 // Thread could be blocked waiting for async
2208 // so signal it to handle state changes immediately
2209 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2210 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2211 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002212 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002213}
2214
Eric Laurent81784c32012-11-19 14:55:58 -08002215String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2216{
Eric Laurent81784c32012-11-19 14:55:58 -08002217 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002218 String8 out_s8;
2219 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2220 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002221 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002222 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002223}
2224
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002225void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002226 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2227 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002228
Eric Laurent73e26b62015-04-27 16:55:58 -07002229 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002230
2231 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002232 case AUDIO_OUTPUT_OPENED:
2233 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002234 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002235 desc->mChannelMask = mChannelMask;
2236 desc->mSamplingRate = mSampleRate;
2237 desc->mFormat = mFormat;
2238 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002239 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002240 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002241 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002242 break;
2243
Eric Laurent73e26b62015-04-27 16:55:58 -07002244 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002245 default:
2246 break;
2247 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002248 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002249}
2250
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002251void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002252{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002253 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002254}
2255
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002256void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002257{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002258 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002259}
2260
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002261void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002262{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002263 mCallbackThread->setAsyncError();
2264}
2265
Eric Laurent3b4529e2013-09-05 18:09:19 -07002266void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002267{
2268 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002269 // reject out of sequence requests
2270 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2271 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002272 mWaitWorkCV.signal();
2273 }
2274}
2275
Eric Laurent3b4529e2013-09-05 18:09:19 -07002276void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002277{
2278 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002279 // reject out of sequence requests
2280 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2281 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002282 mWaitWorkCV.signal();
2283 }
2284}
2285
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002286void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002287{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002288 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002289 mSampleRate = mOutput->getSampleRate();
2290 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002291 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002292 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002293 }
Andy Hung9a592762014-07-21 21:56:01 -07002294 if ((mType == MIXER || mType == DUPLICATING)
2295 && !isValidPcmSinkChannelMask(mChannelMask)) {
2296 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2297 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002298 }
Andy Hunge5412692014-05-16 11:25:07 -07002299 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002300
2301 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002302 status_t result = mOutput->stream->getFormat(&mHALFormat);
2303 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002304 // Get format from the shim, which will be different than the HAL format
2305 // if playing compressed audio over HDMI passthrough.
2306 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002307 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002308 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002309 }
Andy Hung6146c082014-03-18 11:56:15 -07002310 if ((mType == MIXER || mType == DUPLICATING)
2311 && !isValidPcmSinkFormat(mFormat)) {
2312 LOG_FATAL("HAL format %#x not supported for mixed output",
2313 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002314 }
Phil Burk062e67a2015-02-11 13:40:50 -08002315 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002316 result = mOutput->stream->getBufferSize(&mBufferSize);
2317 LOG_ALWAYS_FATAL_IF(result != OK,
2318 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002319 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002320 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002321 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002322 mFrameCount);
2323 }
2324
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002325 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2326 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002327 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002328 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002329 }
2330 }
2331
Eric Laurentd1f69b02014-12-15 14:33:13 -08002332 mHwSupportsPause = false;
2333 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002334 bool supportsPause = false, supportsResume = false;
2335 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2336 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002337 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002338 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002339 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002340 } else if (supportsResume) {
2341 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002342 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002343 }
2344 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002345 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2346 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2347 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002348
Andy Hungfbfc3952015-01-15 13:33:51 -08002349 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2350 // For best precision, we use float instead of the associated output
2351 // device format (typically PCM 16 bit).
2352
2353 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2354 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2355 mBufferSize = mFrameSize * mFrameCount;
2356
2357 // TODO: We currently use the associated output device channel mask and sample rate.
2358 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2359 // (if a valid mask) to avoid premature downmix.
2360 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2361 // instead of the output device sample rate to avoid loss of high frequency information.
2362 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2363 }
2364
Andy Hung09a50072014-02-27 14:30:47 -08002365 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002366 double multiplier = 1.0;
2367 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2368 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002369 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2370 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002371
Eric Laurent81784c32012-11-19 14:55:58 -08002372 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2373 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2374 maxNormalFrameCount = maxNormalFrameCount & ~15;
2375 if (maxNormalFrameCount < minNormalFrameCount) {
2376 maxNormalFrameCount = minNormalFrameCount;
2377 }
2378 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2379 if (multiplier <= 1.0) {
2380 multiplier = 1.0;
2381 } else if (multiplier <= 2.0) {
2382 if (2 * mFrameCount <= maxNormalFrameCount) {
2383 multiplier = 2.0;
2384 } else {
2385 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2386 }
2387 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002388 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002389 }
2390 }
2391 mNormalFrameCount = multiplier * mFrameCount;
2392 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002393 if (mType == MIXER || mType == DUPLICATING) {
2394 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2395 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002396 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002397 mNormalFrameCount);
2398
Andy Hung08fb1742015-05-31 23:22:10 -07002399 // Check if we want to throttle the processing to no more than 2x normal rate
2400 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002401 mThreadThrottleTimeMs = 0;
2402 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002403 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2404
Andy Hung010a1a12014-03-13 13:57:33 -07002405 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2406 // Originally this was int16_t[] array, need to remove legacy implications.
2407 free(mSinkBuffer);
2408 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002409 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2410 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2411 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002412 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002413
Andy Hung69aed5f2014-02-25 17:24:40 -08002414 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2415 // drives the output.
2416 free(mMixerBuffer);
2417 mMixerBuffer = NULL;
2418 if (mMixerBufferEnabled) {
2419 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2420 mMixerBufferSize = mNormalFrameCount * mChannelCount
2421 * audio_bytes_per_sample(mMixerBufferFormat);
2422 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2423 }
Andy Hung98ef9782014-03-04 14:46:50 -08002424 free(mEffectBuffer);
2425 mEffectBuffer = NULL;
2426 if (mEffectBufferEnabled) {
2427 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2428 mEffectBufferSize = mNormalFrameCount * mChannelCount
2429 * audio_bytes_per_sample(mEffectBufferFormat);
2430 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2431 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002432
Eric Laurent81784c32012-11-19 14:55:58 -08002433 // force reconfiguration of effect chains and engines to take new buffer size and audio
2434 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002435 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002436 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2437 // matter.
2438 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2439 Vector< sp<EffectChain> > effectChains = mEffectChains;
2440 for (size_t i = 0; i < effectChains.size(); i ++) {
2441 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2442 }
2443}
2444
2445
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002446status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002447{
2448 if (halFrames == NULL || dspFrames == NULL) {
2449 return BAD_VALUE;
2450 }
2451 Mutex::Autolock _l(mLock);
2452 if (initCheck() != NO_ERROR) {
2453 return INVALID_OPERATION;
2454 }
Andy Hung818e7a32016-02-16 18:08:07 -08002455 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002456 *halFrames = framesWritten;
2457
2458 if (isSuspended()) {
2459 // return an estimation of rendered frames when the output is suspended
2460 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002461 *dspFrames = (uint32_t)
2462 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002463 return NO_ERROR;
2464 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002465 status_t status;
2466 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002467 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002468 *dspFrames = (size_t)frames;
2469 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002470 }
2471}
2472
Eric Laurent4c415062016-06-17 16:14:16 -07002473// hasAudioSession_l() must be called with ThreadBase::mLock held
2474uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002475{
Eric Laurent81784c32012-11-19 14:55:58 -08002476 uint32_t result = 0;
2477 if (getEffectChain_l(sessionId) != 0) {
2478 result = EFFECT_SESSION;
2479 }
2480
2481 for (size_t i = 0; i < mTracks.size(); ++i) {
2482 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002483 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002484 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002485 if (track->isFastTrack()) {
2486 result |= FAST_SESSION;
2487 }
Eric Laurent81784c32012-11-19 14:55:58 -08002488 break;
2489 }
2490 }
2491
2492 return result;
2493}
2494
Glenn Kastend848eb42016-03-08 13:42:11 -08002495uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002496{
2497 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2498 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2499 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2500 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2501 }
2502 for (size_t i = 0; i < mTracks.size(); i++) {
2503 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002504 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002505 return AudioSystem::getStrategyForStream(track->streamType());
2506 }
2507 }
2508 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2509}
2510
2511
Phil Burk062e67a2015-02-11 13:40:50 -08002512AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002513{
2514 Mutex::Autolock _l(mLock);
2515 return mOutput;
2516}
2517
Phil Burk062e67a2015-02-11 13:40:50 -08002518AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002519{
2520 Mutex::Autolock _l(mLock);
2521 AudioStreamOut *output = mOutput;
2522 mOutput = NULL;
2523 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2524 // must push a NULL and wait for ack
2525 mOutputSink.clear();
2526 mPipeSink.clear();
2527 mNormalSink.clear();
2528 return output;
2529}
2530
2531// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002532sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002533{
2534 if (mOutput == NULL) {
2535 return NULL;
2536 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002537 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002538}
2539
2540uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2541{
2542 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2543}
2544
2545status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2546{
2547 if (!isValidSyncEvent(event)) {
2548 return BAD_VALUE;
2549 }
2550
2551 Mutex::Autolock _l(mLock);
2552
2553 for (size_t i = 0; i < mTracks.size(); ++i) {
2554 sp<Track> track = mTracks[i];
2555 if (event->triggerSession() == track->sessionId()) {
2556 (void) track->setSyncEvent(event);
2557 return NO_ERROR;
2558 }
2559 }
2560
2561 return NAME_NOT_FOUND;
2562}
2563
2564bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2565{
2566 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2567}
2568
2569void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2570 const Vector< sp<Track> >& tracksToRemove)
2571{
2572 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002573 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002574 for (size_t i = 0 ; i < count ; i++) {
2575 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002576 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002577 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002578 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002579#ifdef ADD_BATTERY_DATA
2580 // to track the speaker usage
2581 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2582#endif
2583 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002584 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002585 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002586 }
Eric Laurent81784c32012-11-19 14:55:58 -08002587 }
2588 }
2589 }
Eric Laurent81784c32012-11-19 14:55:58 -08002590}
2591
2592void AudioFlinger::PlaybackThread::checkSilentMode_l()
2593{
2594 if (!mMasterMute) {
2595 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002596 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2597 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2598 return;
2599 }
Eric Laurent81784c32012-11-19 14:55:58 -08002600 if (property_get("ro.audio.silent", value, "0") > 0) {
2601 char *endptr;
2602 unsigned long ul = strtoul(value, &endptr, 0);
2603 if (*endptr == '\0' && ul != 0) {
2604 ALOGD("Silence is golden");
2605 // The setprop command will not allow a property to be changed after
2606 // the first time it is set, so we don't have to worry about un-muting.
2607 setMasterMute_l(true);
2608 }
2609 }
2610 }
2611}
2612
2613// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002614ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002615{
Eric Laurent81784c32012-11-19 14:55:58 -08002616 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002617 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002618 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002619
2620 // If an NBAIO sink is present, use it to write the normal mixer's submix
2621 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002622
Andy Hung010a1a12014-03-13 13:57:33 -07002623 const size_t count = mBytesRemaining / mFrameSize;
2624
Simon Wilson2d590962012-11-29 15:18:50 -08002625 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002626 // update the setpoint when AudioFlinger::mScreenState changes
2627 uint32_t screenState = AudioFlinger::mScreenState;
2628 if (screenState != mScreenState) {
2629 mScreenState = screenState;
2630 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2631 if (pipe != NULL) {
2632 pipe->setAvgFrames((mScreenState & 1) ?
2633 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2634 }
2635 }
Andy Hung010a1a12014-03-13 13:57:33 -07002636 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002637 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002638 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002639 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002640 } else {
2641 bytesWritten = framesWritten;
2642 }
2643 // otherwise use the HAL / AudioStreamOut directly
2644 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002645 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002646
Eric Laurentbfb1b832013-01-07 09:53:42 -08002647 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002648 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2649 mWriteAckSequence += 2;
2650 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002652 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002653 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002654 // FIXME We should have an implementation of timestamps for direct output threads.
2655 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002656 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002657
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 if (mUseAsyncWrite &&
2659 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2660 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002661 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002662 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002663 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 }
Eric Laurent81784c32012-11-19 14:55:58 -08002665 }
2666
Eric Laurent81784c32012-11-19 14:55:58 -08002667 mNumWrites++;
2668 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002669 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002670 return bytesWritten;
2671}
2672
2673void AudioFlinger::PlaybackThread::threadLoop_drain()
2674{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002675 bool supportsDrain = false;
2676 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2678 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002679 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2680 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002681 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002682 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002683 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002684 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002685 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686 }
2687}
2688
2689void AudioFlinger::PlaybackThread::threadLoop_exit()
2690{
Eric Laurent275e8e92014-11-30 15:14:47 -08002691 {
2692 Mutex::Autolock _l(mLock);
2693 for (size_t i = 0; i < mTracks.size(); i++) {
2694 sp<Track> track = mTracks[i];
2695 track->invalidate();
2696 }
Andy Hungdae27702016-10-31 14:01:16 -07002697 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2698 // After we exit there are no more track changes sent to BatteryNotifier
2699 // because that requires an active threadLoop.
2700 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2701 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002702 }
Eric Laurent81784c32012-11-19 14:55:58 -08002703}
2704
2705/*
2706The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002707 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002708 - mActiveSleepTimeUs from activeSleepTimeUs()
2709 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002710 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2711 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002712 - maxPeriod from frame count and sample rate (MIXER only)
2713
2714The parameters that affect these derived values are:
2715 - frame count
2716 - frame size
2717 - sample rate
2718 - device type: A2DP or not
2719 - device latency
2720 - format: PCM or not
2721 - active sleep time
2722 - idle sleep time
2723*/
2724
2725void AudioFlinger::PlaybackThread::cacheParameters_l()
2726{
Andy Hung25c2dac2014-02-27 14:56:00 -08002727 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002728 mActiveSleepTimeUs = activeSleepTimeUs();
2729 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002730
2731 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2732 // truncating audio when going to standby.
2733 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2734 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2735 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2736 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2737 }
2738 }
Eric Laurent81784c32012-11-19 14:55:58 -08002739}
2740
Eric Laurent13084622016-05-17 10:51:49 -07002741bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002742{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002743 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002744 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002745 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002746 size_t size = mTracks.size();
2747 for (size_t i = 0; i < size; i++) {
2748 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002749 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002750 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002751 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002752 }
2753 }
Eric Laurent13084622016-05-17 10:51:49 -07002754 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002755}
2756
Haynes Mathew George05317d22016-05-03 16:34:26 -07002757void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2758{
2759 Mutex::Autolock _l(mLock);
2760 invalidateTracks_l(streamType);
2761}
2762
Eric Laurent81784c32012-11-19 14:55:58 -08002763status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2764{
Glenn Kastend848eb42016-03-08 13:42:11 -08002765 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002766 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2767 status_t result = EffectBufferHalInterface::mirror(
2768 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2769 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2770 &halInBuffer);
2771 if (result != OK) return result;
2772 halOutBuffer = halInBuffer;
2773 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002774
2775 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002776 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002777 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002778 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002779 if (mType != DIRECT) {
2780 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002781 status_t result = EffectBufferHalInterface::allocate(
2782 numSamples * sizeof(int16_t),
2783 &halInBuffer);
2784 if (result != OK) return result;
2785 buffer = halInBuffer->audioBuffer()->s16;
2786 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2787 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002788 }
2789
2790 // Attach all tracks with same session ID to this chain.
2791 for (size_t i = 0; i < mTracks.size(); ++i) {
2792 sp<Track> track = mTracks[i];
2793 if (session == track->sessionId()) {
2794 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2795 buffer);
2796 track->setMainBuffer(buffer);
2797 chain->incTrackCnt();
2798 }
2799 }
2800
2801 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002802 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002803 if (session == track->sessionId()) {
2804 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2805 chain->incActiveTrackCnt();
2806 }
2807 }
2808 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002809 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002810 chain->setInBuffer(halInBuffer);
2811 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002812 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002813 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002814 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2815 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002816 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002817 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002818 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002819 // Effect chain for other sessions are inserted at beginning of effect
2820 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002821 // sessions is not important.
2822 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2823 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2824 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002825 size_t size = mEffectChains.size();
2826 size_t i = 0;
2827 for (i = 0; i < size; i++) {
2828 if (mEffectChains[i]->sessionId() < session) {
2829 break;
2830 }
2831 }
2832 mEffectChains.insertAt(chain, i);
2833 checkSuspendOnAddEffectChain_l(chain);
2834
2835 return NO_ERROR;
2836}
2837
2838size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2839{
Glenn Kastend848eb42016-03-08 13:42:11 -08002840 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002841
2842 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2843
2844 for (size_t i = 0; i < mEffectChains.size(); i++) {
2845 if (chain == mEffectChains[i]) {
2846 mEffectChains.removeAt(i);
2847 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002848 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002849 if (session == track->sessionId()) {
2850 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2851 chain.get(), session);
2852 chain->decActiveTrackCnt();
2853 }
2854 }
2855
2856 // detach all tracks with same session ID from this chain
2857 for (size_t i = 0; i < mTracks.size(); ++i) {
2858 sp<Track> track = mTracks[i];
2859 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002860 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002861 chain->decTrackCnt();
2862 }
2863 }
2864 break;
2865 }
2866 }
2867 return mEffectChains.size();
2868}
2869
2870status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002871 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002872{
2873 Mutex::Autolock _l(mLock);
2874 return attachAuxEffect_l(track, EffectId);
2875}
2876
2877status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002878 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002879{
2880 status_t status = NO_ERROR;
2881
2882 if (EffectId == 0) {
2883 track->setAuxBuffer(0, NULL);
2884 } else {
2885 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2886 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2887 if (effect != 0) {
2888 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2889 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2890 } else {
2891 status = INVALID_OPERATION;
2892 }
2893 } else {
2894 status = BAD_VALUE;
2895 }
2896 }
2897 return status;
2898}
2899
2900void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2901{
2902 for (size_t i = 0; i < mTracks.size(); ++i) {
2903 sp<Track> track = mTracks[i];
2904 if (track->auxEffectId() == effectId) {
2905 attachAuxEffect_l(track, 0);
2906 }
2907 }
2908}
2909
2910bool AudioFlinger::PlaybackThread::threadLoop()
2911{
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002912 logWriterTLS = mNBLogWriter.get();
2913
Eric Laurent81784c32012-11-19 14:55:58 -08002914 Vector< sp<Track> > tracksToRemove;
2915
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002916 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002917 nsecs_t lastWriteFinished = -1; // time last server write completed
2918 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002919
2920 // MIXER
2921 nsecs_t lastWarning = 0;
2922
2923 // DUPLICATING
2924 // FIXME could this be made local to while loop?
2925 writeFrames = 0;
2926
2927 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002928 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002929
2930 if (mType == MIXER) {
2931 sleepTimeShift = 0;
2932 }
2933
2934 CpuStats cpuStats;
2935 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2936
2937 acquireWakeLock();
2938
Glenn Kasten9e58b552013-01-18 15:09:48 -08002939 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2940 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2941 // and then that string will be logged at the next convenient opportunity.
2942 const char *logString = NULL;
2943
Eric Laurent664539d2013-09-23 18:24:31 -07002944 checkSilentMode_l();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002945#if 0
2946 int z = 0; // used in logFormat example
2947#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002948 while (!exitPending())
2949 {
2950 cpuStats.sample(myName);
2951
2952 Vector< sp<EffectChain> > effectChains;
2953
Eric Laurent81784c32012-11-19 14:55:58 -08002954 { // scope for mLock
2955
2956 Mutex::Autolock _l(mLock);
2957
Eric Laurent021cf962014-05-13 10:18:14 -07002958 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002959
Glenn Kasten9e58b552013-01-18 15:09:48 -08002960 if (logString != NULL) {
2961 mNBLogWriter->logTimestamp();
2962 mNBLogWriter->log(logString);
2963 logString = NULL;
2964 }
2965
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002966 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002967 // and associate with the sink frames written out. We need
2968 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002969 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002970 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002971 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002972 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002973 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002974 ExtendedTimestamp timestamp; // use private copy to fetch
2975 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002976
2977 // We keep track of the last valid kernel position in case we are in underrun
2978 // and the normal mixer period is the same as the fast mixer period, or there
2979 // is some error from the HAL.
2980 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2981 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2982 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2983 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2984 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2985
2986 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2987 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2988 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2989 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002990 }
2991
2992 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2993 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002994 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002995 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002996 }
2997
Andy Hung818e7a32016-02-16 18:08:07 -08002998 // copy over kernel info
2999 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003000 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3001 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003002 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3003 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003004 }
3005 // mFramesWritten for non-offloaded tracks are contiguous
3006 // even after standby() is called. This is useful for the track frame
3007 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003008 bool serverLocationUpdate = false;
3009 if (mFramesWritten != lastFramesWritten) {
3010 serverLocationUpdate = true;
3011 lastFramesWritten = mFramesWritten;
3012 }
3013 // Only update timestamps if there is a meaningful change.
3014 // Either the kernel timestamp must be valid or we have written something.
3015 if (kernelLocationUpdate || serverLocationUpdate) {
3016 if (serverLocationUpdate) {
3017 // use the time before we called the HAL write - it is a bit more accurate
3018 // to when the server last read data than the current time here.
3019 //
3020 // If we haven't written anything, mLastWriteTime will be -1
3021 // and we use systemTime().
3022 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3023 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3024 ? systemTime() : mLastWriteTime;
3025 }
Andy Hungdae27702016-10-31 14:01:16 -07003026
3027 for (const sp<Track> &t : mActiveTracks) {
3028 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003029 t->updateTrackFrameInfo(
3030 t->mAudioTrackServerProxy->framesReleased(),
3031 mFramesWritten,
3032 mTimestamp);
3033 }
Andy Hunge10393e2015-06-12 13:59:33 -07003034 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003035 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003036#if 0
3037 // logFormat example
3038 if (!(z % 100)) {
3039 timespec ts;
3040 clock_gettime(CLOCK_MONOTONIC, &ts);
3041 LOGF("This is an integer %d, this is a float %f, this is my "
3042 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
3043 LOGF("A deceptive null-terminated string %\0");
3044 }
3045 ++z;
3046#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003047 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003048 if (mSignalPending) {
3049 // A signal was raised while we were unlocked
3050 mSignalPending = false;
3051 } else if (waitingAsyncCallback_l()) {
3052 if (exitPending()) {
3053 break;
3054 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003055 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003056 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003057 releaseWakeLock_l();
3058 released = true;
3059 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003060 ALOGV("wait async completion");
3061 mWaitWorkCV.wait(mLock);
3062 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003063 if (released) {
3064 acquireWakeLock_l();
3065 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003066 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3067 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003068
3069 continue;
3070 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003071 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003072 isSuspended()) {
3073 // put audio hardware into standby after short delay
3074 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003075
3076 threadLoop_standby();
3077
3078 mStandby = true;
3079 }
3080
3081 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3082 // we're about to wait, flush the binder command buffer
3083 IPCThreadState::self()->flushCommands();
3084
3085 clearOutputTracks();
3086
3087 if (exitPending()) {
3088 break;
3089 }
3090
3091 releaseWakeLock_l();
3092 // wait until we have something to do...
3093 ALOGV("%s going to sleep", myName.string());
3094 mWaitWorkCV.wait(mLock);
3095 ALOGV("%s waking up", myName.string());
3096 acquireWakeLock_l();
3097
3098 mMixerStatus = MIXER_IDLE;
3099 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3100 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003101 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003102 checkSilentMode_l();
3103
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003104 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3105 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003106 if (mType == MIXER) {
3107 sleepTimeShift = 0;
3108 }
3109
3110 continue;
3111 }
3112 }
Eric Laurent81784c32012-11-19 14:55:58 -08003113 // mMixerStatusIgnoringFastTracks is also updated internally
3114 mMixerStatus = prepareTracks_l(&tracksToRemove);
3115
Andy Hungdae27702016-10-31 14:01:16 -07003116 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003117
Eric Laurent81784c32012-11-19 14:55:58 -08003118 // prevent any changes in effect chain list and in each effect chain
3119 // during mixing and effect process as the audio buffers could be deleted
3120 // or modified if an effect is created or deleted
3121 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003122 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003123
Eric Laurentbfb1b832013-01-07 09:53:42 -08003124 if (mBytesRemaining == 0) {
3125 mCurrentWriteLength = 0;
3126 if (mMixerStatus == MIXER_TRACKS_READY) {
3127 // threadLoop_mix() sets mCurrentWriteLength
3128 threadLoop_mix();
3129 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3130 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003131 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003132 // must be written to HAL
3133 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003134 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003135 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003136 }
3137 }
Andy Hung98ef9782014-03-04 14:46:50 -08003138 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003139 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003140 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3141 // or mSinkBuffer (if there are no effects).
3142 //
3143 // This is done pre-effects computation; if effects change to
3144 // support higher precision, this needs to move.
3145 //
3146 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003147 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003148 if (mMixerBufferValid) {
3149 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3150 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3151
Andy Hung2ddee192015-12-18 17:34:44 -08003152 // mono blend occurs for mixer threads only (not direct or offloaded)
3153 // and is handled here if we're going directly to the sink.
3154 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003155 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3156 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003157 }
3158
Andy Hung98ef9782014-03-04 14:46:50 -08003159 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3160 mNormalFrameCount * mChannelCount);
3161 }
3162
Eric Laurentbfb1b832013-01-07 09:53:42 -08003163 mBytesRemaining = mCurrentWriteLength;
3164 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003165 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3166 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3167 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3168 mBytesWritten += mBytesRemaining;
3169 mFramesWritten += framesRemaining;
3170 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003171 mBytesRemaining = 0;
3172 }
Eric Laurent81784c32012-11-19 14:55:58 -08003173
Eric Laurentbfb1b832013-01-07 09:53:42 -08003174 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003175 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003176 for (size_t i = 0; i < effectChains.size(); i ++) {
3177 effectChains[i]->process_l();
3178 }
Eric Laurent81784c32012-11-19 14:55:58 -08003179 }
3180 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003181 // Process effect chains for offloaded thread even if no audio
3182 // was read from audio track: process only updates effect state
3183 // and thus does have to be synchronized with audio writes but may have
3184 // to be called while waiting for async write callback
3185 if (mType == OFFLOAD) {
3186 for (size_t i = 0; i < effectChains.size(); i ++) {
3187 effectChains[i]->process_l();
3188 }
3189 }
Eric Laurent81784c32012-11-19 14:55:58 -08003190
Andy Hung98ef9782014-03-04 14:46:50 -08003191 // Only if the Effects buffer is enabled and there is data in the
3192 // Effects buffer (buffer valid), we need to
3193 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003194 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003195 if (mEffectBufferValid) {
3196 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003197
3198 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003199 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3200 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003201 }
3202
Andy Hung98ef9782014-03-04 14:46:50 -08003203 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3204 mNormalFrameCount * mChannelCount);
3205 }
3206
Eric Laurent81784c32012-11-19 14:55:58 -08003207 // enable changes in effect chain
3208 unlockEffectChains(effectChains);
3209
Eric Laurentbfb1b832013-01-07 09:53:42 -08003210 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003211 // mSleepTimeUs == 0 means we must write to audio hardware
3212 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003213 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003214 // We save lastWriteFinished here, as previousLastWriteFinished,
3215 // for throttling. On thread start, previousLastWriteFinished will be
3216 // set to -1, which properly results in no throttling after the first write.
3217 nsecs_t previousLastWriteFinished = lastWriteFinished;
3218 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003219 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003220 // FIXME rewrite to reduce number of system calls
3221 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003222 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003223 lastWriteFinished = systemTime();
3224 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003225 if (ret < 0) {
3226 mBytesRemaining = 0;
3227 } else {
3228 mBytesWritten += ret;
3229 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003230 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003231 }
3232 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3233 (mMixerStatus == MIXER_DRAIN_ALL)) {
3234 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003235 }
Andy Hung08fb1742015-05-31 23:22:10 -07003236 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003237 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003238 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003239 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003240 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003241 ATRACE_NAME("underrun");
3242 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003243 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003244 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003245 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003246 }
Andy Hung08fb1742015-05-31 23:22:10 -07003247
3248 if (mThreadThrottle
3249 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3250 && ret > 0) { // we wrote something
3251 // Limit MixerThread data processing to no more than twice the
3252 // expected processing rate.
3253 //
3254 // This helps prevent underruns with NuPlayer and other applications
3255 // which may set up buffers that are close to the minimum size, or use
3256 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3257 //
3258 // The throttle smooths out sudden large data drains from the device,
3259 // e.g. when it comes out of standby, which often causes problems with
3260 // (1) mixer threads without a fast mixer (which has its own warm-up)
3261 // (2) minimum buffer sized tracks (even if the track is full,
3262 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003263 //
3264 // Total time spent in last processing cycle equals time spent in
3265 // 1. threadLoop_write, as well as time spent in
3266 // 2. threadLoop_mix (significant for heavy mixing, especially
3267 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003268
Andy Hung69488c42016-05-16 18:43:33 -07003269 // it's OK if deltaMs is an overestimate.
3270 const int32_t deltaMs =
3271 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003272 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3273 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3274 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003275 // notify of throttle start on verbose log
3276 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3277 "mixer(%p) throttle begin:"
3278 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003279 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003280 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003281 // Throttle must be attributed to the previous mixer loop's write time
3282 // to allow back-to-back throttling.
3283 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003284 } else {
3285 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3286 if (diff > 0) {
3287 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003288 // but prevent spamming for bluetooth
3289 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3290 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003291 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3292 }
Andy Hung08fb1742015-05-31 23:22:10 -07003293 }
3294 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003295 }
Eric Laurent81784c32012-11-19 14:55:58 -08003296
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003298 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003299 Mutex::Autolock _l(mLock);
3300 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3301 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003302 }
Glenn Kastene7754022014-10-31 12:11:26 -07003303 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003304 }
Eric Laurent81784c32012-11-19 14:55:58 -08003305 }
3306
3307 // Finally let go of removed track(s), without the lock held
3308 // since we can't guarantee the destructors won't acquire that
3309 // same lock. This will also mutate and push a new fast mixer state.
3310 threadLoop_removeTracks(tracksToRemove);
3311 tracksToRemove.clear();
3312
3313 // FIXME I don't understand the need for this here;
3314 // it was in the original code but maybe the
3315 // assignment in saveOutputTracks() makes this unnecessary?
3316 clearOutputTracks();
3317
3318 // Effect chains will be actually deleted here if they were removed from
3319 // mEffectChains list during mixing or effects processing
3320 effectChains.clear();
3321
3322 // FIXME Note that the above .clear() is no longer necessary since effectChains
3323 // is now local to this block, but will keep it for now (at least until merge done).
3324 }
3325
Eric Laurentbfb1b832013-01-07 09:53:42 -08003326 threadLoop_exit();
3327
Eric Laurentcf817a22014-08-04 20:36:31 -07003328 if (!mStandby) {
3329 threadLoop_standby();
3330 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003331 }
3332
3333 releaseWakeLock();
3334
3335 ALOGV("Thread %p type %d exiting", this, mType);
3336 return false;
3337}
3338
Eric Laurentbfb1b832013-01-07 09:53:42 -08003339// removeTracks_l() must be called with ThreadBase::mLock held
3340void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3341{
3342 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003343 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003344 for (size_t i=0 ; i<count ; i++) {
3345 const sp<Track>& track = tracksToRemove.itemAt(i);
3346 mActiveTracks.remove(track);
3347 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3348 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3349 if (chain != 0) {
3350 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3351 track->sessionId());
3352 chain->decActiveTrackCnt();
3353 }
3354 if (track->isTerminated()) {
3355 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003356 } else { // inactive but not terminated
3357 char buffer[256];
3358 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3359 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003360 }
3361 }
3362 }
3363
3364}
Eric Laurent81784c32012-11-19 14:55:58 -08003365
Eric Laurentaccc1472013-09-20 09:36:34 -07003366status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3367{
3368 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003369 ExtendedTimestamp ets;
3370 status_t status = mNormalSink->getTimestamp(ets);
3371 if (status == NO_ERROR) {
3372 status = ets.getBestTimestamp(&timestamp);
3373 }
3374 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003375 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003376 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003377 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003378 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003379 timestamp.mPosition = (uint32_t)position64;
3380 return NO_ERROR;
3381 }
3382 }
3383 return INVALID_OPERATION;
3384}
Eric Laurent1c333e22014-05-20 10:48:17 -07003385
Eric Laurent054d9d32015-04-24 08:48:48 -07003386status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3387 audio_patch_handle_t *handle)
3388{
Andy Hungf60abce2016-08-26 11:37:54 -07003389 status_t status;
3390 if (property_get_bool("af.patch_park", false /* default_value */)) {
3391 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3392 // or if HAL does not properly lock against access.
3393 AutoPark<FastMixer> park(mFastMixer);
3394 status = PlaybackThread::createAudioPatch_l(patch, handle);
3395 } else {
3396 status = PlaybackThread::createAudioPatch_l(patch, handle);
3397 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003398 return status;
3399}
3400
Eric Laurent1c333e22014-05-20 10:48:17 -07003401status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3402 audio_patch_handle_t *handle)
3403{
3404 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003405
3406 // store new device and send to effects
3407 audio_devices_t type = AUDIO_DEVICE_NONE;
3408 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3409 type |= patch->sinks[i].ext.device.type;
3410 }
3411
3412#ifdef ADD_BATTERY_DATA
3413 // when changing the audio output device, call addBatteryData to notify
3414 // the change
3415 if (mOutDevice != type) {
3416 uint32_t params = 0;
3417 // check whether speaker is on
3418 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3419 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003420 }
3421
Eric Laurent054d9d32015-04-24 08:48:48 -07003422 audio_devices_t deviceWithoutSpeaker
3423 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3424 // check if any other device (except speaker) is on
3425 if (type & deviceWithoutSpeaker) {
3426 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3427 }
3428
3429 if (params != 0) {
3430 addBatteryData(params);
3431 }
3432 }
3433#endif
3434
3435 for (size_t i = 0; i < mEffectChains.size(); i++) {
3436 mEffectChains[i]->setDevice_l(type);
3437 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003438
3439 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3440 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3441 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003442 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003443 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003444
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003445 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003446 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3447 status = hwDevice->createAudioPatch(patch->num_sources,
3448 patch->sources,
3449 patch->num_sinks,
3450 patch->sinks,
3451 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003452 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003453 char *address;
3454 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3455 //FIXME: we only support address on first sink with HAL version < 3.0
3456 address = audio_device_address_to_parameter(
3457 patch->sinks[0].ext.device.type,
3458 patch->sinks[0].ext.device.address);
3459 } else {
3460 address = (char *)calloc(1, 1);
3461 }
3462 AudioParameter param = AudioParameter(String8(address));
3463 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003464 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003465 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003466 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003467 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003468 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003469 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003470 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3471 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003472 return status;
3473}
3474
Eric Laurent054d9d32015-04-24 08:48:48 -07003475status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3476{
Andy Hungf60abce2016-08-26 11:37:54 -07003477 status_t status;
3478 if (property_get_bool("af.patch_park", false /* default_value */)) {
3479 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3480 // or if HAL does not properly lock against access.
3481 AutoPark<FastMixer> park(mFastMixer);
3482 status = PlaybackThread::releaseAudioPatch_l(handle);
3483 } else {
3484 status = PlaybackThread::releaseAudioPatch_l(handle);
3485 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003486 return status;
3487}
3488
Eric Laurent1c333e22014-05-20 10:48:17 -07003489status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3490{
3491 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003492
3493 mOutDevice = AUDIO_DEVICE_NONE;
3494
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003495 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003496 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3497 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003498 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003499 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003500 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003501 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003502 }
3503 return status;
3504}
3505
Eric Laurent83b88082014-06-20 18:31:16 -07003506void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3507{
3508 Mutex::Autolock _l(mLock);
3509 mTracks.add(track);
3510}
3511
3512void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3513{
3514 Mutex::Autolock _l(mLock);
3515 destroyTrack_l(track);
3516}
3517
3518void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3519{
3520 ThreadBase::getAudioPortConfig(config);
3521 config->role = AUDIO_PORT_ROLE_SOURCE;
3522 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3523 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3524}
3525
Eric Laurent81784c32012-11-19 14:55:58 -08003526// ----------------------------------------------------------------------------
3527
3528AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003529 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3530 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003531 // mAudioMixer below
3532 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003533 mFastMixerFutex(0),
3534 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003535 // mOutputSink below
3536 // mPipeSink below
3537 // mNormalSink below
3538{
3539 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003540 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3541 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003542 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3543 mNormalFrameCount);
3544 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3545
Andy Hungfbfc3952015-01-15 13:33:51 -08003546 if (type == DUPLICATING) {
3547 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3548 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3549 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3550 return;
3551 }
Eric Laurent81784c32012-11-19 14:55:58 -08003552 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003553 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003554 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003555 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003556#if !LOG_NDEBUG
3557 ssize_t index =
3558#else
3559 (void)
3560#endif
3561 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003562 ALOG_ASSERT(index == 0);
3563
3564 // initialize fast mixer depending on configuration
3565 bool initFastMixer;
3566 switch (kUseFastMixer) {
3567 case FastMixer_Never:
3568 initFastMixer = false;
3569 break;
3570 case FastMixer_Always:
3571 initFastMixer = true;
3572 break;
3573 case FastMixer_Static:
3574 case FastMixer_Dynamic:
3575 initFastMixer = mFrameCount < mNormalFrameCount;
3576 break;
3577 }
3578 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003579 audio_format_t fastMixerFormat;
3580 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3581 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3582 } else {
3583 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3584 }
3585 if (mFormat != fastMixerFormat) {
3586 // change our Sink format to accept our intermediate precision
3587 mFormat = fastMixerFormat;
3588 free(mSinkBuffer);
3589 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3590 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3591 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3592 }
Eric Laurent81784c32012-11-19 14:55:58 -08003593
3594 // create a MonoPipe to connect our submix to FastMixer
3595 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003596#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003597 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003598#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003599 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003600 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003601 format.mFormat = fastMixerFormat;
3602 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3603
Eric Laurent81784c32012-11-19 14:55:58 -08003604 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3605 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3606 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3607 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3608 const NBAIO_Format offers[1] = {format};
3609 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003610#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003611 ssize_t index =
3612#else
3613 (void)
3614#endif
3615 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003616 ALOG_ASSERT(index == 0);
3617 monoPipe->setAvgFrames((mScreenState & 1) ?
3618 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3619 mPipeSink = monoPipe;
3620
Glenn Kasten46909e72013-02-26 09:20:22 -08003621#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003622 if (mTeeSinkOutputEnabled) {
3623 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003624 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3625 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003626 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003627 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003628 ALOG_ASSERT(index == 0);
3629 mTeeSink = teeSink;
3630 PipeReader *teeSource = new PipeReader(*teeSink);
3631 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003632 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003633 ALOG_ASSERT(index == 0);
3634 mTeeSource = teeSource;
3635 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003636#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003637
3638 // create fast mixer and configure it initially with just one fast track for our submix
3639 mFastMixer = new FastMixer();
3640 FastMixerStateQueue *sq = mFastMixer->sq();
3641#ifdef STATE_QUEUE_DUMP
3642 sq->setObserverDump(&mStateQueueObserverDump);
3643 sq->setMutatorDump(&mStateQueueMutatorDump);
3644#endif
3645 FastMixerState *state = sq->begin();
3646 FastTrack *fastTrack = &state->mFastTracks[0];
3647 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3648 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3649 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003650 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3651 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003652 fastTrack->mGeneration++;
3653 state->mFastTracksGen++;
3654 state->mTrackMask = 1;
3655 // fast mixer will use the HAL output sink
3656 state->mOutputSink = mOutputSink.get();
3657 state->mOutputSinkGen++;
3658 state->mFrameCount = mFrameCount;
3659 state->mCommand = FastMixerState::COLD_IDLE;
3660 // already done in constructor initialization list
3661 //mFastMixerFutex = 0;
3662 state->mColdFutexAddr = &mFastMixerFutex;
3663 state->mColdGen++;
3664 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003665#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003666 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003667#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003668 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3669 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003670 sq->end();
3671 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3672
3673 // start the fast mixer
3674 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3675 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003676 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003677 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003678
3679#ifdef AUDIO_WATCHDOG
3680 // create and start the watchdog
3681 mAudioWatchdog = new AudioWatchdog();
3682 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3683 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3684 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003685 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003686#endif
3687
Eric Laurent81784c32012-11-19 14:55:58 -08003688 }
3689
3690 switch (kUseFastMixer) {
3691 case FastMixer_Never:
3692 case FastMixer_Dynamic:
3693 mNormalSink = mOutputSink;
3694 break;
3695 case FastMixer_Always:
3696 mNormalSink = mPipeSink;
3697 break;
3698 case FastMixer_Static:
3699 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3700 break;
3701 }
3702}
3703
3704AudioFlinger::MixerThread::~MixerThread()
3705{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003706 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003707 FastMixerStateQueue *sq = mFastMixer->sq();
3708 FastMixerState *state = sq->begin();
3709 if (state->mCommand == FastMixerState::COLD_IDLE) {
3710 int32_t old = android_atomic_inc(&mFastMixerFutex);
3711 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003712 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003713 }
3714 }
3715 state->mCommand = FastMixerState::EXIT;
3716 sq->end();
3717 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3718 mFastMixer->join();
3719 // Though the fast mixer thread has exited, it's state queue is still valid.
3720 // We'll use that extract the final state which contains one remaining fast track
3721 // corresponding to our sub-mix.
3722 state = sq->begin();
3723 ALOG_ASSERT(state->mTrackMask == 1);
3724 FastTrack *fastTrack = &state->mFastTracks[0];
3725 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3726 delete fastTrack->mBufferProvider;
3727 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003728 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003729#ifdef AUDIO_WATCHDOG
3730 if (mAudioWatchdog != 0) {
3731 mAudioWatchdog->requestExit();
3732 mAudioWatchdog->requestExitAndWait();
3733 mAudioWatchdog.clear();
3734 }
3735#endif
3736 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003737 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003738 delete mAudioMixer;
3739}
3740
3741
3742uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3743{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003744 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003745 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3746 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3747 }
3748 return latency;
3749}
3750
3751
3752void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3753{
3754 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3755}
3756
Eric Laurentbfb1b832013-01-07 09:53:42 -08003757ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003758{
3759 // FIXME we should only do one push per cycle; confirm this is true
3760 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003761 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003762 FastMixerStateQueue *sq = mFastMixer->sq();
3763 FastMixerState *state = sq->begin();
3764 if (state->mCommand != FastMixerState::MIX_WRITE &&
3765 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3766 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003767
3768 // FIXME workaround for first HAL write being CPU bound on some devices
3769 ATRACE_BEGIN("write");
3770 mOutput->write((char *)mSinkBuffer, 0);
3771 ATRACE_END();
3772
Eric Laurent81784c32012-11-19 14:55:58 -08003773 int32_t old = android_atomic_inc(&mFastMixerFutex);
3774 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003775 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003776 }
3777#ifdef AUDIO_WATCHDOG
3778 if (mAudioWatchdog != 0) {
3779 mAudioWatchdog->resume();
3780 }
3781#endif
3782 }
3783 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003784#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003785 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003786 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003787#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003788 sq->end();
3789 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3790 if (kUseFastMixer == FastMixer_Dynamic) {
3791 mNormalSink = mPipeSink;
3792 }
3793 } else {
3794 sq->end(false /*didModify*/);
3795 }
3796 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003797 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003798}
3799
3800void AudioFlinger::MixerThread::threadLoop_standby()
3801{
3802 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003803 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003804 FastMixerStateQueue *sq = mFastMixer->sq();
3805 FastMixerState *state = sq->begin();
3806 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003807 // Report any frames trapped in the Monopipe
3808 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3809 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3810 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3811 "monoPipeWritten:%lld monoPipeLeft:%lld",
3812 (long long)mFramesWritten, (long long)mSuspendedFrames,
3813 (long long)mPipeSink->framesWritten(), pipeFrames);
3814 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3815
Eric Laurent81784c32012-11-19 14:55:58 -08003816 state->mCommand = FastMixerState::COLD_IDLE;
3817 state->mColdFutexAddr = &mFastMixerFutex;
3818 state->mColdGen++;
3819 mFastMixerFutex = 0;
3820 sq->end();
3821 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3822 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3823 if (kUseFastMixer == FastMixer_Dynamic) {
3824 mNormalSink = mOutputSink;
3825 }
3826#ifdef AUDIO_WATCHDOG
3827 if (mAudioWatchdog != 0) {
3828 mAudioWatchdog->pause();
3829 }
3830#endif
3831 } else {
3832 sq->end(false /*didModify*/);
3833 }
3834 }
3835 PlaybackThread::threadLoop_standby();
3836}
3837
Eric Laurentbfb1b832013-01-07 09:53:42 -08003838bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3839{
3840 return false;
3841}
3842
3843bool AudioFlinger::PlaybackThread::shouldStandby_l()
3844{
3845 return !mStandby;
3846}
3847
3848bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3849{
3850 Mutex::Autolock _l(mLock);
3851 return waitingAsyncCallback_l();
3852}
3853
Eric Laurent81784c32012-11-19 14:55:58 -08003854// shared by MIXER and DIRECT, overridden by DUPLICATING
3855void AudioFlinger::PlaybackThread::threadLoop_standby()
3856{
3857 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003858 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003859 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003860 // discard any pending drain or write ack by incrementing sequence
3861 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3862 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003863 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003864 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3865 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003866 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003867 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003868}
3869
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003870void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3871{
3872 ALOGV("signal playback thread");
3873 broadcast_l();
3874}
3875
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003876void AudioFlinger::PlaybackThread::onAsyncError()
3877{
3878 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3879 invalidateTracks((audio_stream_type_t)i);
3880 }
3881}
3882
Eric Laurent81784c32012-11-19 14:55:58 -08003883void AudioFlinger::MixerThread::threadLoop_mix()
3884{
Eric Laurent81784c32012-11-19 14:55:58 -08003885 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003886 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003887 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003888 // increase sleep time progressively when application underrun condition clears.
3889 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3890 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3891 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003892 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003893 sleepTimeShift--;
3894 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003895 mSleepTimeUs = 0;
3896 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003897 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003898
Eric Laurent81784c32012-11-19 14:55:58 -08003899}
3900
3901void AudioFlinger::MixerThread::threadLoop_sleepTime()
3902{
3903 // If no tracks are ready, sleep once for the duration of an output
3904 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003905 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003906 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003907 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3908 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3909 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003910 }
3911 // reduce sleep time in case of consecutive application underruns to avoid
3912 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3913 // duration we would end up writing less data than needed by the audio HAL if
3914 // the condition persists.
3915 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3916 sleepTimeShift++;
3917 }
3918 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003919 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003920 }
3921 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003922 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3923 // before effects processing or output.
3924 if (mMixerBufferValid) {
3925 memset(mMixerBuffer, 0, mMixerBufferSize);
3926 } else {
3927 memset(mSinkBuffer, 0, mSinkBufferSize);
3928 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003929 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003930 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3931 "anticipated start");
3932 }
3933 // TODO add standby time extension fct of effect tail
3934}
3935
3936// prepareTracks_l() must be called with ThreadBase::mLock held
3937AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3938 Vector< sp<Track> > *tracksToRemove)
3939{
3940
3941 mixer_state mixerStatus = MIXER_IDLE;
3942 // find out which tracks need to be processed
3943 size_t count = mActiveTracks.size();
3944 size_t mixedTracks = 0;
3945 size_t tracksWithEffect = 0;
3946 // counts only _active_ fast tracks
3947 size_t fastTracks = 0;
3948 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3949
3950 float masterVolume = mMasterVolume;
3951 bool masterMute = mMasterMute;
3952
3953 if (masterMute) {
3954 masterVolume = 0;
3955 }
3956 // Delegate master volume control to effect in output mix effect chain if needed
3957 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3958 if (chain != 0) {
3959 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3960 chain->setVolume_l(&v, &v);
3961 masterVolume = (float)((v + (1 << 23)) >> 24);
3962 chain.clear();
3963 }
3964
3965 // prepare a new state to push
3966 FastMixerStateQueue *sq = NULL;
3967 FastMixerState *state = NULL;
3968 bool didModify = false;
3969 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003970 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003971 sq = mFastMixer->sq();
3972 state = sq->begin();
3973 }
3974
Andy Hung69aed5f2014-02-25 17:24:40 -08003975 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003976 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003977
Eric Laurent81784c32012-11-19 14:55:58 -08003978 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07003979 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003980
3981 // this const just means the local variable doesn't change
3982 Track* const track = t.get();
3983
3984 // process fast tracks
3985 if (track->isFastTrack()) {
3986
3987 // It's theoretically possible (though unlikely) for a fast track to be created
3988 // and then removed within the same normal mix cycle. This is not a problem, as
3989 // the track never becomes active so it's fast mixer slot is never touched.
3990 // The converse, of removing an (active) track and then creating a new track
3991 // at the identical fast mixer slot within the same normal mix cycle,
3992 // is impossible because the slot isn't marked available until the end of each cycle.
3993 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003994 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003995 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3996 FastTrack *fastTrack = &state->mFastTracks[j];
3997
3998 // Determine whether the track is currently in underrun condition,
3999 // and whether it had a recent underrun.
4000 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4001 FastTrackUnderruns underruns = ftDump->mUnderruns;
4002 uint32_t recentFull = (underruns.mBitFields.mFull -
4003 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4004 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4005 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4006 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4007 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4008 uint32_t recentUnderruns = recentPartial + recentEmpty;
4009 track->mObservedUnderruns = underruns;
4010 // don't count underruns that occur while stopping or pausing
4011 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004012 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4013 recentUnderruns > 0) {
4014 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4015 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004016 } else {
4017 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004018 }
4019
4020 // This is similar to the state machine for normal tracks,
4021 // with a few modifications for fast tracks.
4022 bool isActive = true;
4023 switch (track->mState) {
4024 case TrackBase::STOPPING_1:
4025 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004026 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004027 track->mState = TrackBase::STOPPING_2;
4028 }
4029 break;
4030 case TrackBase::PAUSING:
4031 // ramp down is not yet implemented
4032 track->setPaused();
4033 break;
4034 case TrackBase::RESUMING:
4035 // ramp up is not yet implemented
4036 track->mState = TrackBase::ACTIVE;
4037 break;
4038 case TrackBase::ACTIVE:
4039 if (recentFull > 0 || recentPartial > 0) {
4040 // track has provided at least some frames recently: reset retry count
4041 track->mRetryCount = kMaxTrackRetries;
4042 }
4043 if (recentUnderruns == 0) {
4044 // no recent underruns: stay active
4045 break;
4046 }
4047 // there has recently been an underrun of some kind
4048 if (track->sharedBuffer() == 0) {
4049 // were any of the recent underruns "empty" (no frames available)?
4050 if (recentEmpty == 0) {
4051 // no, then ignore the partial underruns as they are allowed indefinitely
4052 break;
4053 }
4054 // there has recently been an "empty" underrun: decrement the retry counter
4055 if (--(track->mRetryCount) > 0) {
4056 break;
4057 }
4058 // indicate to client process that the track was disabled because of underrun;
4059 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004060 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004061 // remove from active list, but state remains ACTIVE [confusing but true]
4062 isActive = false;
4063 break;
4064 }
4065 // fall through
4066 case TrackBase::STOPPING_2:
4067 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004068 case TrackBase::STOPPED:
4069 case TrackBase::FLUSHED: // flush() while active
4070 // Check for presentation complete if track is inactive
4071 // We have consumed all the buffers of this track.
4072 // This would be incomplete if we auto-paused on underrun
4073 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004074 uint32_t latency = 0;
4075 status_t result = mOutput->stream->getLatency(&latency);
4076 ALOGE_IF(result != OK,
4077 "Error when retrieving output stream latency: %d", result);
4078 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004079 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004080 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4081 // track stays in active list until presentation is complete
4082 break;
4083 }
4084 }
4085 if (track->isStopping_2()) {
4086 track->mState = TrackBase::STOPPED;
4087 }
4088 if (track->isStopped()) {
4089 // Can't reset directly, as fast mixer is still polling this track
4090 // track->reset();
4091 // So instead mark this track as needing to be reset after push with ack
4092 resetMask |= 1 << i;
4093 }
4094 isActive = false;
4095 break;
4096 case TrackBase::IDLE:
4097 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004098 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004099 }
4100
4101 if (isActive) {
4102 // was it previously inactive?
4103 if (!(state->mTrackMask & (1 << j))) {
4104 ExtendedAudioBufferProvider *eabp = track;
4105 VolumeProvider *vp = track;
4106 fastTrack->mBufferProvider = eabp;
4107 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004108 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004109 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004110 fastTrack->mGeneration++;
4111 state->mTrackMask |= 1 << j;
4112 didModify = true;
4113 // no acknowledgement required for newly active tracks
4114 }
4115 // cache the combined master volume and stream type volume for fast mixer; this
4116 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004117 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004118 ++fastTracks;
4119 } else {
4120 // was it previously active?
4121 if (state->mTrackMask & (1 << j)) {
4122 fastTrack->mBufferProvider = NULL;
4123 fastTrack->mGeneration++;
4124 state->mTrackMask &= ~(1 << j);
4125 didModify = true;
4126 // If any fast tracks were removed, we must wait for acknowledgement
4127 // because we're about to decrement the last sp<> on those tracks.
4128 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4129 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004130 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4131 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4132 j, track->mState, state->mTrackMask, recentUnderruns,
4133 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004134 }
4135 tracksToRemove->add(track);
4136 // Avoids a misleading display in dumpsys
4137 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4138 }
4139 continue;
4140 }
4141
4142 { // local variable scope to avoid goto warning
4143
4144 audio_track_cblk_t* cblk = track->cblk();
4145
4146 // The first time a track is added we wait
4147 // for all its buffers to be filled before processing it
4148 int name = track->name();
4149 // make sure that we have enough frames to mix one full buffer.
4150 // enforce this condition only once to enable draining the buffer in case the client
4151 // app does not call stop() and relies on underrun to stop:
4152 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4153 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004154 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004155 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004156 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004157
4158 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004159 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004160 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4161 // add frames already consumed but not yet released by the resampler
4162 // because mAudioTrackServerProxy->framesReady() will include these frames
4163 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4164
Eric Laurent81784c32012-11-19 14:55:58 -08004165 uint32_t minFrames = 1;
4166 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4167 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004168 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004169 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004170
4171 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004172 if (ATRACE_ENABLED()) {
4173 // I wish we had formatted trace names
4174 char traceName[16];
4175 strcpy(traceName, "nRdy");
4176 int name = track->name();
4177 if (AudioMixer::TRACK0 <= name &&
4178 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4179 name -= AudioMixer::TRACK0;
4180 traceName[4] = (name / 10) + '0';
4181 traceName[5] = (name % 10) + '0';
4182 } else {
4183 traceName[4] = '?';
4184 traceName[5] = '?';
4185 }
4186 traceName[6] = '\0';
4187 ATRACE_INT(traceName, framesReady);
4188 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004189 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004190 !track->isPaused() && !track->isTerminated())
4191 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004192 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004193
4194 mixedTracks++;
4195
Andy Hung69aed5f2014-02-25 17:24:40 -08004196 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4197 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004198 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004199 if (track->mainBuffer() != mSinkBuffer &&
4200 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004201 if (mEffectBufferEnabled) {
4202 mEffectBufferValid = true; // Later can set directly.
4203 }
Eric Laurent81784c32012-11-19 14:55:58 -08004204 chain = getEffectChain_l(track->sessionId());
4205 // Delegate volume control to effect in track effect chain if needed
4206 if (chain != 0) {
4207 tracksWithEffect++;
4208 } else {
4209 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4210 "session %d",
4211 name, track->sessionId());
4212 }
4213 }
4214
4215
4216 int param = AudioMixer::VOLUME;
4217 if (track->mFillingUpStatus == Track::FS_FILLED) {
4218 // no ramp for the first volume setting
4219 track->mFillingUpStatus = Track::FS_ACTIVE;
4220 if (track->mState == TrackBase::RESUMING) {
4221 track->mState = TrackBase::ACTIVE;
4222 param = AudioMixer::RAMP_VOLUME;
4223 }
4224 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004225 // FIXME should not make a decision based on mServer
4226 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004227 // If the track is stopped before the first frame was mixed,
4228 // do not apply ramp
4229 param = AudioMixer::RAMP_VOLUME;
4230 }
4231
4232 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004233 uint32_t vl, vr; // in U8.24 integer format
4234 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004235 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004236 vl = vr = 0;
4237 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004238 if (track->isPausing()) {
4239 track->setPaused();
4240 }
4241 } else {
4242
4243 // read original volumes with volume control
4244 float typeVolume = mStreamTypes[track->streamType()].volume;
4245 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004246 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004247 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004248 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4249 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004250 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004251 if (vlf > GAIN_FLOAT_UNITY) {
4252 ALOGV("Track left volume out of range: %.3g", vlf);
4253 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004254 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004255 if (vrf > GAIN_FLOAT_UNITY) {
4256 ALOGV("Track right volume out of range: %.3g", vrf);
4257 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004258 }
4259 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004260 vlf *= v;
4261 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004262 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004263 // then derive vl and vr as U8.24 versions for the effect chain
4264 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4265 vl = (uint32_t) (scaleto8_24 * vlf);
4266 vr = (uint32_t) (scaleto8_24 * vrf);
4267 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004268 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004269 // send level comes from shared memory and so may be corrupt
4270 if (sendLevel > MAX_GAIN_INT) {
4271 ALOGV("Track send level out of range: %04X", sendLevel);
4272 sendLevel = MAX_GAIN_INT;
4273 }
Andy Hung6be49402014-05-30 10:42:03 -07004274 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4275 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004276 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004277
Eric Laurent81784c32012-11-19 14:55:58 -08004278 // Delegate volume control to effect in track effect chain if needed
4279 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4280 // Do not ramp volume if volume is controlled by effect
4281 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004282 // Update remaining floating point volume levels
4283 vlf = (float)vl / (1 << 24);
4284 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004285 track->mHasVolumeController = true;
4286 } else {
4287 // force no volume ramp when volume controller was just disabled or removed
4288 // from effect chain to avoid volume spike
4289 if (track->mHasVolumeController) {
4290 param = AudioMixer::VOLUME;
4291 }
4292 track->mHasVolumeController = false;
4293 }
4294
Eric Laurent81784c32012-11-19 14:55:58 -08004295 // XXX: these things DON'T need to be done each time
4296 mAudioMixer->setBufferProvider(name, track);
4297 mAudioMixer->enable(name);
4298
Andy Hung6be49402014-05-30 10:42:03 -07004299 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4300 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4301 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004302 mAudioMixer->setParameter(
4303 name,
4304 AudioMixer::TRACK,
4305 AudioMixer::FORMAT, (void *)track->format());
4306 mAudioMixer->setParameter(
4307 name,
4308 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004309 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004310 mAudioMixer->setParameter(
4311 name,
4312 AudioMixer::TRACK,
4313 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004314 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004315 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004316 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004317 if (reqSampleRate == 0) {
4318 reqSampleRate = mSampleRate;
4319 } else if (reqSampleRate > maxSampleRate) {
4320 reqSampleRate = maxSampleRate;
4321 }
Eric Laurent81784c32012-11-19 14:55:58 -08004322 mAudioMixer->setParameter(
4323 name,
4324 AudioMixer::RESAMPLE,
4325 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004326 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004327
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004328 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004329 mAudioMixer->setParameter(
4330 name,
4331 AudioMixer::TIMESTRETCH,
4332 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004333 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004334
Andy Hung69aed5f2014-02-25 17:24:40 -08004335 /*
4336 * Select the appropriate output buffer for the track.
4337 *
Andy Hung98ef9782014-03-04 14:46:50 -08004338 * Tracks with effects go into their own effects chain buffer
4339 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004340 *
4341 * Other tracks can use mMixerBuffer for higher precision
4342 * channel accumulation. If this buffer is enabled
4343 * (mMixerBufferEnabled true), then selected tracks will accumulate
4344 * into it.
4345 *
4346 */
4347 if (mMixerBufferEnabled
4348 && (track->mainBuffer() == mSinkBuffer
4349 || track->mainBuffer() == mMixerBuffer)) {
4350 mAudioMixer->setParameter(
4351 name,
4352 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004353 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004354 mAudioMixer->setParameter(
4355 name,
4356 AudioMixer::TRACK,
4357 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4358 // TODO: override track->mainBuffer()?
4359 mMixerBufferValid = true;
4360 } else {
4361 mAudioMixer->setParameter(
4362 name,
4363 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004364 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004365 mAudioMixer->setParameter(
4366 name,
4367 AudioMixer::TRACK,
4368 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4369 }
Eric Laurent81784c32012-11-19 14:55:58 -08004370 mAudioMixer->setParameter(
4371 name,
4372 AudioMixer::TRACK,
4373 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4374
4375 // reset retry count
4376 track->mRetryCount = kMaxTrackRetries;
4377
4378 // If one track is ready, set the mixer ready if:
4379 // - the mixer was not ready during previous round OR
4380 // - no other track is not ready
4381 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4382 mixerStatus != MIXER_TRACKS_ENABLED) {
4383 mixerStatus = MIXER_TRACKS_READY;
4384 }
4385 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004386 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004387 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4388 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004389 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004390 } else {
4391 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004392 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004393
Eric Laurent81784c32012-11-19 14:55:58 -08004394 // clear effect chain input buffer if an active track underruns to avoid sending
4395 // previous audio buffer again to effects
4396 chain = getEffectChain_l(track->sessionId());
4397 if (chain != 0) {
4398 chain->clearInputBuffer();
4399 }
4400
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004401 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004402 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4403 track->isStopped() || track->isPaused()) {
4404 // We have consumed all the buffers of this track.
4405 // Remove it from the list of active tracks.
4406 // TODO: use actual buffer filling status instead of latency when available from
4407 // audio HAL
4408 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004409 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004410 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4411 if (track->isStopped()) {
4412 track->reset();
4413 }
4414 tracksToRemove->add(track);
4415 }
4416 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004417 // No buffers for this track. Give it a few chances to
4418 // fill a buffer, then remove it from active list.
4419 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004420 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004421 tracksToRemove->add(track);
4422 // indicate to client process that the track was disabled because of underrun;
4423 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004424 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004425 // If one track is not ready, mark the mixer also not ready if:
4426 // - the mixer was ready during previous round OR
4427 // - no other track is ready
4428 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4429 mixerStatus != MIXER_TRACKS_READY) {
4430 mixerStatus = MIXER_TRACKS_ENABLED;
4431 }
4432 }
4433 mAudioMixer->disable(name);
4434 }
4435
4436 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004437
4438 }
4439
4440 // Push the new FastMixer state if necessary
4441 bool pauseAudioWatchdog = false;
4442 if (didModify) {
4443 state->mFastTracksGen++;
4444 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4445 if (kUseFastMixer == FastMixer_Dynamic &&
4446 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4447 state->mCommand = FastMixerState::COLD_IDLE;
4448 state->mColdFutexAddr = &mFastMixerFutex;
4449 state->mColdGen++;
4450 mFastMixerFutex = 0;
4451 if (kUseFastMixer == FastMixer_Dynamic) {
4452 mNormalSink = mOutputSink;
4453 }
4454 // If we go into cold idle, need to wait for acknowledgement
4455 // so that fast mixer stops doing I/O.
4456 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4457 pauseAudioWatchdog = true;
4458 }
Eric Laurent81784c32012-11-19 14:55:58 -08004459 }
4460 if (sq != NULL) {
4461 sq->end(didModify);
4462 sq->push(block);
4463 }
4464#ifdef AUDIO_WATCHDOG
4465 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4466 mAudioWatchdog->pause();
4467 }
4468#endif
4469
4470 // Now perform the deferred reset on fast tracks that have stopped
4471 while (resetMask != 0) {
4472 size_t i = __builtin_ctz(resetMask);
4473 ALOG_ASSERT(i < count);
4474 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004475 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004476 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4477 track->reset();
4478 }
4479
4480 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004481 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004482
Eric Laurent97d547d2014-09-02 14:45:53 -07004483 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4484 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004485 }
4486
4487 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004488 // as long as there are effects we should clear the effects buffer, to avoid
4489 // passing a non-clean buffer to the effect chain
4490 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004491 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004492 // sink or mix buffer must be cleared if all tracks are connected to an
4493 // effect chain as in this case the mixer will not write to the sink or mix buffer
4494 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004495 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4496 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004497 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004498 if (mMixerBufferValid) {
4499 memset(mMixerBuffer, 0, mMixerBufferSize);
4500 // TODO: In testing, mSinkBuffer below need not be cleared because
4501 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4502 // after mixing.
4503 //
4504 // To enforce this guarantee:
4505 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4506 // (mixedTracks == 0 && fastTracks > 0))
4507 // must imply MIXER_TRACKS_READY.
4508 // Later, we may clear buffers regardless, and skip much of this logic.
4509 }
Andy Hung98ef9782014-03-04 14:46:50 -08004510 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004511 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004512 }
4513
4514 // if any fast tracks, then status is ready
4515 mMixerStatusIgnoringFastTracks = mixerStatus;
4516 if (fastTracks > 0) {
4517 mixerStatus = MIXER_TRACKS_READY;
4518 }
4519 return mixerStatus;
4520}
4521
Eric Laurentad7dd962016-09-22 12:38:37 -07004522// trackCountForUid_l() must be called with ThreadBase::mLock held
4523uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4524{
4525 uint32_t trackCount = 0;
4526 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004527 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004528 trackCount++;
4529 }
4530 }
4531 return trackCount;
4532}
4533
Eric Laurent81784c32012-11-19 14:55:58 -08004534// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004535int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004536 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004537{
Eric Laurentad7dd962016-09-22 12:38:37 -07004538 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4539 return -1;
4540 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004541 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004542}
4543
4544// deleteTrackName_l() must be called with ThreadBase::mLock held
4545void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4546{
4547 ALOGV("remove track (%d) and delete from mixer", name);
4548 mAudioMixer->deleteTrackName(name);
4549}
4550
Eric Laurent10351942014-05-08 18:49:52 -07004551// checkForNewParameter_l() must be called with ThreadBase::mLock held
4552bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4553 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004554{
Eric Laurent81784c32012-11-19 14:55:58 -08004555 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004556 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004557
Eric Laurent10351942014-05-08 18:49:52 -07004558 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004559
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004560 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004561
Eric Laurent10351942014-05-08 18:49:52 -07004562 AudioParameter param = AudioParameter(keyValuePair);
4563 int value;
4564 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4565 reconfig = true;
4566 }
4567 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004568 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004569 status = BAD_VALUE;
4570 } else {
4571 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004572 reconfig = true;
4573 }
Eric Laurent10351942014-05-08 18:49:52 -07004574 }
4575 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004576 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004577 status = BAD_VALUE;
4578 } else {
4579 // no need to save value, since it's constant
4580 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004581 }
Eric Laurent10351942014-05-08 18:49:52 -07004582 }
4583 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4584 // do not accept frame count changes if tracks are open as the track buffer
4585 // size depends on frame count and correct behavior would not be guaranteed
4586 // if frame count is changed after track creation
4587 if (!mTracks.isEmpty()) {
4588 status = INVALID_OPERATION;
4589 } else {
4590 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004591 }
Eric Laurent10351942014-05-08 18:49:52 -07004592 }
4593 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004594#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004595 // when changing the audio output device, call addBatteryData to notify
4596 // the change
4597 if (mOutDevice != value) {
4598 uint32_t params = 0;
4599 // check whether speaker is on
4600 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4601 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004602 }
Eric Laurent10351942014-05-08 18:49:52 -07004603
4604 audio_devices_t deviceWithoutSpeaker
4605 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4606 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004607 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004608 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4609 }
4610
4611 if (params != 0) {
4612 addBatteryData(params);
4613 }
4614 }
Eric Laurent81784c32012-11-19 14:55:58 -08004615#endif
4616
Eric Laurent10351942014-05-08 18:49:52 -07004617 // forward device change to effects that have requested to be
4618 // aware of attached audio device.
4619 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004620 a2dpDeviceChanged =
4621 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004622 mOutDevice = value;
4623 for (size_t i = 0; i < mEffectChains.size(); i++) {
4624 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004625 }
4626 }
Eric Laurent10351942014-05-08 18:49:52 -07004627 }
Eric Laurent81784c32012-11-19 14:55:58 -08004628
Eric Laurent10351942014-05-08 18:49:52 -07004629 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004630 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004631 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004632 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004633 mStandby = true;
4634 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004635 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004636 }
Eric Laurent10351942014-05-08 18:49:52 -07004637 if (status == NO_ERROR && reconfig) {
4638 readOutputParameters_l();
4639 delete mAudioMixer;
4640 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4641 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004642 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004643 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004644 if (name < 0) {
4645 break;
4646 }
4647 mTracks[i]->mName = name;
4648 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004649 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004650 }
Eric Laurent81784c32012-11-19 14:55:58 -08004651 }
4652
Eric Laurent42537be2016-01-08 17:16:42 -08004653 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004654}
4655
4656
4657void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4658{
Eric Laurent81784c32012-11-19 14:55:58 -08004659 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004660 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004661 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004662 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004663
4664 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004665 // while we are dumping it. It may be inconsistent, but it won't mutate!
4666 // This is a large object so we place it on the heap.
4667 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4668 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4669 copy->dump(fd);
4670 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004671
4672#ifdef STATE_QUEUE_DUMP
4673 // Similar for state queue
4674 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4675 observerCopy.dump(fd);
4676 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4677 mutatorCopy.dump(fd);
4678#endif
4679
Glenn Kasten46909e72013-02-26 09:20:22 -08004680#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004681 // Write the tee output to a .wav file
4682 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004683#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004684
4685#ifdef AUDIO_WATCHDOG
4686 if (mAudioWatchdog != 0) {
4687 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4688 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4689 wdCopy.dump(fd);
4690 }
4691#endif
4692}
4693
4694uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4695{
4696 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4697}
4698
4699uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4700{
4701 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4702}
4703
4704void AudioFlinger::MixerThread::cacheParameters_l()
4705{
4706 PlaybackThread::cacheParameters_l();
4707
4708 // FIXME: Relaxed timing because of a certain device that can't meet latency
4709 // Should be reduced to 2x after the vendor fixes the driver issue
4710 // increase threshold again due to low power audio mode. The way this warning
4711 // threshold is calculated and its usefulness should be reconsidered anyway.
4712 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4713}
4714
4715// ----------------------------------------------------------------------------
4716
4717AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004718 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4719 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004720 // mLeftVolFloat, mRightVolFloat
4721{
4722}
4723
Eric Laurentbfb1b832013-01-07 09:53:42 -08004724AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4725 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004726 ThreadBase::type_t type, bool systemReady)
4727 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004728 // mLeftVolFloat, mRightVolFloat
4729{
4730}
4731
Eric Laurent81784c32012-11-19 14:55:58 -08004732AudioFlinger::DirectOutputThread::~DirectOutputThread()
4733{
4734}
4735
Eric Laurent5850c4c2016-11-10 13:04:31 -08004736void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004737{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004738 float left, right;
4739
4740 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4741 left = right = 0;
4742 } else {
4743 float typeVolume = mStreamTypes[track->streamType()].volume;
4744 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004745 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004746 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4747 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4748 if (left > GAIN_FLOAT_UNITY) {
4749 left = GAIN_FLOAT_UNITY;
4750 }
4751 left *= v;
4752 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4753 if (right > GAIN_FLOAT_UNITY) {
4754 right = GAIN_FLOAT_UNITY;
4755 }
4756 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004757 }
4758
4759 if (lastTrack) {
4760 if (left != mLeftVolFloat || right != mRightVolFloat) {
4761 mLeftVolFloat = left;
4762 mRightVolFloat = right;
4763
4764 // Convert volumes from float to 8.24
4765 uint32_t vl = (uint32_t)(left * (1 << 24));
4766 uint32_t vr = (uint32_t)(right * (1 << 24));
4767
4768 // Delegate volume control to effect in track effect chain if needed
4769 // only one effect chain can be present on DirectOutputThread, so if
4770 // there is one, the track is connected to it
4771 if (!mEffectChains.isEmpty()) {
4772 mEffectChains[0]->setVolume_l(&vl, &vr);
4773 left = (float)vl / (1 << 24);
4774 right = (float)vr / (1 << 24);
4775 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004776 status_t result = mOutput->stream->setVolume(left, right);
4777 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778 }
4779 }
4780}
4781
Phil Burk43b4dcc2015-06-09 16:53:44 -07004782void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4783{
4784 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004785 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004786
Eric Laurent0f0631e2015-07-06 18:01:25 -07004787 if (previousTrack != 0 && latestTrack != 0) {
4788 if (mType == DIRECT) {
4789 if (previousTrack.get() != latestTrack.get()) {
4790 mFlushPending = true;
4791 }
4792 } else /* mType == OFFLOAD */ {
4793 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4794 mFlushPending = true;
4795 }
4796 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004797 }
4798 PlaybackThread::onAddNewTrack_l();
4799}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004800
Eric Laurent81784c32012-11-19 14:55:58 -08004801AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4802 Vector< sp<Track> > *tracksToRemove
4803)
4804{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004805 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004806 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004807 bool doHwPause = false;
4808 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004809
4810 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004811 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004812 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004813 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004814 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004815 continue;
4816 }
4817
Eric Laurent5850c4c2016-11-10 13:04:31 -08004818 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004819#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004820 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004821#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004822 // Only consider last track started for volume and mixer state control.
4823 // In theory an older track could underrun and restart after the new one starts
4824 // but as we only care about the transition phase between two tracks on a
4825 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004826 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004827 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004828
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004829 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004830 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004831 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004832 doHwPause = true;
4833 mHwPaused = true;
4834 }
4835 tracksToRemove->add(track);
4836 } else if (track->isFlushPending()) {
4837 track->flushAck();
4838 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004839 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004840 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004841 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004842 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004843 if (last) {
4844 mLeftVolFloat = mRightVolFloat = -1.0;
4845 if (mHwPaused) {
4846 doHwResume = true;
4847 mHwPaused = false;
4848 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004849 }
4850 }
4851
Eric Laurent81784c32012-11-19 14:55:58 -08004852 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004853 // for all its buffers to be filled before processing it.
4854 // Allow draining the buffer in case the client
4855 // app does not call stop() and relies on underrun to stop:
4856 // hence the test on (track->mRetryCount > 1).
4857 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004858 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004859 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004860 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004861 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004862 minFrames = mNormalFrameCount;
4863 } else {
4864 minFrames = 1;
4865 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004866
Eric Laurentab5cdba2014-06-09 17:22:27 -07004867 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4868 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004869 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004870 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004871
4872 if (track->mFillingUpStatus == Track::FS_FILLED) {
4873 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004874 if (last) {
4875 // make sure processVolume_l() will apply new volume even if 0
4876 mLeftVolFloat = mRightVolFloat = -1.0;
4877 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004878 if (!mHwSupportsPause) {
4879 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004880 }
4881 }
4882
4883 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004884 processVolume_l(track, last);
4885 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004886 sp<Track> previousTrack = mPreviousTrack.promote();
4887 if (previousTrack != 0) {
4888 if (track != previousTrack.get()) {
4889 // Flush any data still being written from last track
4890 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004891 // Invalidate previous track to force a seek when resuming.
4892 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004893 }
4894 }
4895 mPreviousTrack = track;
4896
Eric Laurentd595b7c2013-04-03 17:27:56 -07004897 // reset retry count
4898 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004899 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004900 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004901 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004902 doHwResume = true;
4903 mHwPaused = false;
4904 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004905 }
Eric Laurent81784c32012-11-19 14:55:58 -08004906 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004907 // clear effect chain input buffer if the last active track started underruns
4908 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004909 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004910 mEffectChains[0]->clearInputBuffer();
4911 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004912 if (track->isStopping_1()) {
4913 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004914 if (last && mHwPaused) {
4915 doHwResume = true;
4916 mHwPaused = false;
4917 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004918 }
4919 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4920 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004921 // We have consumed all the buffers of this track.
4922 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004923 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004924 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004925 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4926 } else {
4927 audioHALFrames = 0;
4928 }
4929
Andy Hung818e7a32016-02-16 18:08:07 -08004930 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004931 if (mStandby || !last ||
4932 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004933 if (track->isStopping_2()) {
4934 track->mState = TrackBase::STOPPED;
4935 }
Eric Laurent81784c32012-11-19 14:55:58 -08004936 if (track->isStopped()) {
4937 track->reset();
4938 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004939 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004940 }
4941 } else {
4942 // No buffers for this track. Give it a few chances to
4943 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004944 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004945 if (--(track->mRetryCount) <= 0) {
4946 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004947 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004948 // indicate to client process that the track was disabled because of underrun;
4949 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004950 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004951 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004952 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4953 "minFrames = %u, mFormat = %#x",
4954 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004955 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004956 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004957 doHwPause = true;
4958 mHwPaused = true;
4959 }
Eric Laurent81784c32012-11-19 14:55:58 -08004960 }
4961 }
4962 }
4963 }
4964
Eric Laurentd1f69b02014-12-15 14:33:13 -08004965 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004966 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004967 for (size_t i = 0; i < mTracks.size(); i++) {
4968 if (mTracks[i]->isFlushPending()) {
4969 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004970 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004971 }
4972 }
4973 }
4974
4975 // make sure the pause/flush/resume sequence is executed in the right order.
4976 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4977 // before flush and then resume HW. This can happen in case of pause/flush/resume
4978 // if resume is received before pause is executed.
4979 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004980 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004981 status_t result = mOutput->stream->pause();
4982 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004983 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004984 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004985 flushHw_l();
4986 }
4987 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004988 status_t result = mOutput->stream->resume();
4989 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004990 }
Eric Laurent81784c32012-11-19 14:55:58 -08004991 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004992 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004993
4994 return mixerStatus;
4995}
4996
4997void AudioFlinger::DirectOutputThread::threadLoop_mix()
4998{
Eric Laurent81784c32012-11-19 14:55:58 -08004999 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005000 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005001 // output audio to hardware
5002 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005003 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005004 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005005 status_t status = mActiveTrack->getNextBuffer(&buffer);
5006 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005007 // no need to pad with 0 for compressed audio
5008 if (audio_has_proportional_frames(mFormat)) {
5009 memset(curBuf, 0, frameCount * mFrameSize);
5010 }
Eric Laurent81784c32012-11-19 14:55:58 -08005011 break;
5012 }
5013 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5014 frameCount -= buffer.frameCount;
5015 curBuf += buffer.frameCount * mFrameSize;
5016 mActiveTrack->releaseBuffer(&buffer);
5017 }
Andy Hung2098f272014-02-27 14:00:06 -08005018 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005019 mSleepTimeUs = 0;
5020 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005021 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005022}
5023
5024void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5025{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005026 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005027 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005028 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005029 return;
5030 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005031 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005032 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005033 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005034 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005035 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005036 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005037 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005038 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005039 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005040 }
5041}
5042
Eric Laurentd1f69b02014-12-15 14:33:13 -08005043void AudioFlinger::DirectOutputThread::threadLoop_exit()
5044{
5045 {
5046 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005047 for (size_t i = 0; i < mTracks.size(); i++) {
5048 if (mTracks[i]->isFlushPending()) {
5049 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005050 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005051 }
5052 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005053 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005054 flushHw_l();
5055 }
5056 }
5057 PlaybackThread::threadLoop_exit();
5058}
5059
5060// must be called with thread mutex locked
5061bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5062{
5063 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005064 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005065
vivek mehta9cd7ad12016-03-17 00:18:29 -07005066 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5067 return !mStandby;
5068 }
5069
Eric Laurentd1f69b02014-12-15 14:33:13 -08005070 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5071 // after a timeout and we will enter standby then.
5072 if (mTracks.size() > 0) {
5073 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005074 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5075 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005076 }
5077
Eric Laurent5cff4032015-05-26 13:49:58 -07005078 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005079}
5080
Eric Laurent81784c32012-11-19 14:55:58 -08005081// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005082int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005083 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005084{
Eric Laurentad7dd962016-09-22 12:38:37 -07005085 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5086 return -1;
5087 }
Eric Laurent81784c32012-11-19 14:55:58 -08005088 return 0;
5089}
5090
5091// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005092void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005093{
5094}
5095
Eric Laurent10351942014-05-08 18:49:52 -07005096// checkForNewParameter_l() must be called with ThreadBase::mLock held
5097bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5098 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005099{
5100 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005101 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005102
Eric Laurent10351942014-05-08 18:49:52 -07005103 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005104
Eric Laurent10351942014-05-08 18:49:52 -07005105 AudioParameter param = AudioParameter(keyValuePair);
5106 int value;
5107 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5108 // forward device change to effects that have requested to be
5109 // aware of attached audio device.
5110 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005111 a2dpDeviceChanged =
5112 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005113 mOutDevice = value;
5114 for (size_t i = 0; i < mEffectChains.size(); i++) {
5115 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005116 }
5117 }
Eric Laurent81784c32012-11-19 14:55:58 -08005118 }
Eric Laurent10351942014-05-08 18:49:52 -07005119 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5120 // do not accept frame count changes if tracks are open as the track buffer
5121 // size depends on frame count and correct behavior would not be garantied
5122 // if frame count is changed after track creation
5123 if (!mTracks.isEmpty()) {
5124 status = INVALID_OPERATION;
5125 } else {
5126 reconfig = true;
5127 }
5128 }
5129 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005130 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005131 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005132 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005133 mStandby = true;
5134 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005135 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005136 }
5137 if (status == NO_ERROR && reconfig) {
5138 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005139 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005140 }
5141 }
5142
Eric Laurent42537be2016-01-08 17:16:42 -08005143 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005144}
5145
5146uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5147{
5148 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005149 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005150 time = PlaybackThread::activeSleepTimeUs();
5151 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005152 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005153 }
5154 return time;
5155}
5156
5157uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5158{
5159 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005160 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005161 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5162 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005163 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005164 }
5165 return time;
5166}
5167
5168uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5169{
5170 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005171 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005172 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5173 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005174 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005175 }
5176 return time;
5177}
5178
5179void AudioFlinger::DirectOutputThread::cacheParameters_l()
5180{
5181 PlaybackThread::cacheParameters_l();
5182
5183 // use shorter standby delay as on normal output to release
5184 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005185 // no delay on outputs with HW A/V sync
5186 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005187 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005188 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005189 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005190 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005191 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005192 }
Eric Laurent81784c32012-11-19 14:55:58 -08005193}
5194
Eric Laurente659ef42014-09-29 13:06:46 -07005195void AudioFlinger::DirectOutputThread::flushHw_l()
5196{
Phil Burk062e67a2015-02-11 13:40:50 -08005197 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005198 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005199 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005200}
5201
Eric Laurent81784c32012-11-19 14:55:58 -08005202// ----------------------------------------------------------------------------
5203
Eric Laurentbfb1b832013-01-07 09:53:42 -08005204AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005205 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005206 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005207 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005208 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005209 mDrainSequence(0),
5210 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005211{
5212}
5213
5214AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5215{
5216}
5217
5218void AudioFlinger::AsyncCallbackThread::onFirstRef()
5219{
5220 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5221}
5222
5223bool AudioFlinger::AsyncCallbackThread::threadLoop()
5224{
5225 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005226 uint32_t writeAckSequence;
5227 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005228 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005229
5230 {
5231 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005232 while (!((mWriteAckSequence & 1) ||
5233 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005234 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005235 exitPending())) {
5236 mWaitWorkCV.wait(mLock);
5237 }
5238
Eric Laurentbfb1b832013-01-07 09:53:42 -08005239 if (exitPending()) {
5240 break;
5241 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005242 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5243 mWriteAckSequence, mDrainSequence);
5244 writeAckSequence = mWriteAckSequence;
5245 mWriteAckSequence &= ~1;
5246 drainSequence = mDrainSequence;
5247 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005248 asyncError = mAsyncError;
5249 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005250 }
5251 {
Eric Laurent4de95592013-09-26 15:28:21 -07005252 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5253 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005254 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005255 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005256 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005257 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005258 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005259 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005260 if (asyncError) {
5261 playbackThread->onAsyncError();
5262 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005263 }
5264 }
5265 }
5266 return false;
5267}
5268
5269void AudioFlinger::AsyncCallbackThread::exit()
5270{
5271 ALOGV("AsyncCallbackThread::exit");
5272 Mutex::Autolock _l(mLock);
5273 requestExit();
5274 mWaitWorkCV.broadcast();
5275}
5276
Eric Laurent3b4529e2013-09-05 18:09:19 -07005277void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005278{
5279 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005280 // bit 0 is cleared
5281 mWriteAckSequence = sequence << 1;
5282}
5283
5284void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5285{
5286 Mutex::Autolock _l(mLock);
5287 // ignore unexpected callbacks
5288 if (mWriteAckSequence & 2) {
5289 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005290 mWaitWorkCV.signal();
5291 }
5292}
5293
Eric Laurent3b4529e2013-09-05 18:09:19 -07005294void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005295{
5296 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005297 // bit 0 is cleared
5298 mDrainSequence = sequence << 1;
5299}
5300
5301void AudioFlinger::AsyncCallbackThread::resetDraining()
5302{
5303 Mutex::Autolock _l(mLock);
5304 // ignore unexpected callbacks
5305 if (mDrainSequence & 2) {
5306 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005307 mWaitWorkCV.signal();
5308 }
5309}
5310
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005311void AudioFlinger::AsyncCallbackThread::setAsyncError()
5312{
5313 Mutex::Autolock _l(mLock);
5314 mAsyncError = true;
5315 mWaitWorkCV.signal();
5316}
5317
Eric Laurentbfb1b832013-01-07 09:53:42 -08005318
5319// ----------------------------------------------------------------------------
5320AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005321 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5322 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005323 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5324 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005325{
Eric Laurentfd477972013-10-25 18:10:40 -07005326 //FIXME: mStandby should be set to true by ThreadBase constructor
5327 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005328 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005329}
5330
Eric Laurentbfb1b832013-01-07 09:53:42 -08005331void AudioFlinger::OffloadThread::threadLoop_exit()
5332{
5333 if (mFlushPending || mHwPaused) {
5334 // If a flush is pending or track was paused, just discard buffered data
5335 flushHw_l();
5336 } else {
5337 mMixerStatus = MIXER_DRAIN_ALL;
5338 threadLoop_drain();
5339 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005340 if (mUseAsyncWrite) {
5341 ALOG_ASSERT(mCallbackThread != 0);
5342 mCallbackThread->exit();
5343 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344 PlaybackThread::threadLoop_exit();
5345}
5346
5347AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5348 Vector< sp<Track> > *tracksToRemove
5349)
5350{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005351 size_t count = mActiveTracks.size();
5352
5353 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005354 bool doHwPause = false;
5355 bool doHwResume = false;
5356
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005357 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005358
Eric Laurentbfb1b832013-01-07 09:53:42 -08005359 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005360 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005361 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005362#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005363 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005364#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005365 // Only consider last track started for volume and mixer state control.
5366 // In theory an older track could underrun and restart after the new one starts
5367 // but as we only care about the transition phase between two tracks on a
5368 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005369 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005370 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005371
Haynes Mathew George7844f672014-01-15 12:32:55 -08005372 if (track->isInvalid()) {
5373 ALOGW("An invalidated track shouldn't be in active list");
5374 tracksToRemove->add(track);
5375 continue;
5376 }
5377
5378 if (track->mState == TrackBase::IDLE) {
5379 ALOGW("An idle track shouldn't be in active list");
5380 continue;
5381 }
5382
Eric Laurentbfb1b832013-01-07 09:53:42 -08005383 if (track->isPausing()) {
5384 track->setPaused();
5385 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005386 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005387 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005388 mHwPaused = true;
5389 }
5390 // If we were part way through writing the mixbuffer to
5391 // the HAL we must save this until we resume
5392 // BUG - this will be wrong if a different track is made active,
5393 // in that case we want to discard the pending data in the
5394 // mixbuffer and tell the client to present it again when the
5395 // track is resumed
5396 mPausedWriteLength = mCurrentWriteLength;
5397 mPausedBytesRemaining = mBytesRemaining;
5398 mBytesRemaining = 0; // stop writing
5399 }
5400 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005401 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005402 if (track->isStopping_1()) {
5403 track->mRetryCount = kMaxTrackStopRetriesOffload;
5404 } else {
5405 track->mRetryCount = kMaxTrackRetriesOffload;
5406 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005407 track->flushAck();
5408 if (last) {
5409 mFlushPending = true;
5410 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005411 } else if (track->isResumePending()){
5412 track->resumeAck();
5413 if (last) {
5414 if (mPausedBytesRemaining) {
5415 // Need to continue write that was interrupted
5416 mCurrentWriteLength = mPausedWriteLength;
5417 mBytesRemaining = mPausedBytesRemaining;
5418 mPausedBytesRemaining = 0;
5419 }
5420 if (mHwPaused) {
5421 doHwResume = true;
5422 mHwPaused = false;
5423 // threadLoop_mix() will handle the case that we need to
5424 // resume an interrupted write
5425 }
5426 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005427 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005428
Eric Laurent3df841a2016-07-15 15:15:40 -07005429 mLeftVolFloat = mRightVolFloat = -1.0;
5430
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005431 // Do not handle new data in this iteration even if track->framesReady()
5432 mixerStatus = MIXER_TRACKS_ENABLED;
5433 }
5434 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005435 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005436 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005437 if (track->mFillingUpStatus == Track::FS_FILLED) {
5438 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005439 if (last) {
5440 // make sure processVolume_l() will apply new volume even if 0
5441 mLeftVolFloat = mRightVolFloat = -1.0;
5442 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005443 }
5444
5445 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005446 sp<Track> previousTrack = mPreviousTrack.promote();
5447 if (previousTrack != 0) {
5448 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005449 // Flush any data still being written from last track
5450 mBytesRemaining = 0;
5451 if (mPausedBytesRemaining) {
5452 // Last track was paused so we also need to flush saved
5453 // mixbuffer state and invalidate track so that it will
5454 // re-submit that unwritten data when it is next resumed
5455 mPausedBytesRemaining = 0;
5456 // Invalidate is a bit drastic - would be more efficient
5457 // to have a flag to tell client that some of the
5458 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005459 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005460 }
5461 // flush data already sent to the DSP if changing audio session as audio
5462 // comes from a different source. Also invalidate previous track to force a
5463 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005464 if (previousTrack->sessionId() != track->sessionId()) {
5465 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005466 }
5467 }
5468 }
5469 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005470 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005471 if (track->isStopping_1()) {
5472 track->mRetryCount = kMaxTrackStopRetriesOffload;
5473 } else {
5474 track->mRetryCount = kMaxTrackRetriesOffload;
5475 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005476 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005477 mixerStatus = MIXER_TRACKS_READY;
5478 }
5479 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005480 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005481 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005482 if (--(track->mRetryCount) <= 0) {
5483 // Hardware buffer can hold a large amount of audio so we must
5484 // wait for all current track's data to drain before we say
5485 // that the track is stopped.
5486 if (mBytesRemaining == 0) {
5487 // Only start draining when all data in mixbuffer
5488 // has been written
5489 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5490 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5491 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5492 if (last && !mStandby) {
5493 // do not modify drain sequence if we are already draining. This happens
5494 // when resuming from pause after drain.
5495 if ((mDrainSequence & 1) == 0) {
5496 mSleepTimeUs = 0;
5497 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5498 mixerStatus = MIXER_DRAIN_TRACK;
5499 mDrainSequence += 2;
5500 }
5501 if (mHwPaused) {
5502 // It is possible to move from PAUSED to STOPPING_1 without
5503 // a resume so we must ensure hardware is running
5504 doHwResume = true;
5505 mHwPaused = false;
5506 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005507 }
5508 }
Eric Laurente93cc032016-05-05 10:15:10 -07005509 } else if (last) {
5510 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5511 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005512 }
5513 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005514 // Drain has completed or we are in standby, signal presentation complete
5515 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005516 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005517 uint32_t latency = 0;
5518 status_t result = mOutput->stream->getLatency(&latency);
5519 ALOGE_IF(result != OK,
5520 "Error when retrieving output stream latency: %d", result);
5521 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005522 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005523 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005524 track->presentationComplete(framesWritten, audioHALFrames);
5525 track->reset();
5526 tracksToRemove->add(track);
5527 }
5528 } else {
5529 // No buffers for this track. Give it a few chances to
5530 // fill a buffer, then remove it from active list.
5531 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005532 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005533 uint64_t position = 0;
5534 struct timespec unused;
5535 // The running check restarts the retry counter at least once.
5536 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5537 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5538 running = true;
5539 mOffloadUnderrunPosition = position;
5540 }
5541 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005542 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5543 (long long)position, (long long)mOffloadUnderrunPosition);
5544 }
5545 if (running) { // still running, give us more time.
5546 track->mRetryCount = kMaxTrackRetriesOffload;
5547 } else {
5548 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5549 track->name());
5550 tracksToRemove->add(track);
5551 // indicate to client process that the track was disabled because of underrun;
5552 // it will then automatically call start() when data is available
5553 track->disable();
5554 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005555 } else if (last){
5556 mixerStatus = MIXER_TRACKS_ENABLED;
5557 }
5558 }
5559 }
5560 // compute volume for this track
5561 processVolume_l(track, last);
5562 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005563
Eric Laurentea0fade2013-10-04 16:23:48 -07005564 // make sure the pause/flush/resume sequence is executed in the right order.
5565 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5566 // before flush and then resume HW. This can happen in case of pause/flush/resume
5567 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005568 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005569 status_t result = mOutput->stream->pause();
5570 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005571 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005572 if (mFlushPending) {
5573 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005574 }
Eric Laurentfd477972013-10-25 18:10:40 -07005575 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005576 status_t result = mOutput->stream->resume();
5577 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005578 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005579
Eric Laurentbfb1b832013-01-07 09:53:42 -08005580 // remove all the tracks that need to be...
5581 removeTracks_l(*tracksToRemove);
5582
5583 return mixerStatus;
5584}
5585
Eric Laurentbfb1b832013-01-07 09:53:42 -08005586// must be called with thread mutex locked
5587bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5588{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005589 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5590 mWriteAckSequence, mDrainSequence);
5591 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005592 return true;
5593 }
5594 return false;
5595}
5596
Eric Laurentbfb1b832013-01-07 09:53:42 -08005597bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5598{
5599 Mutex::Autolock _l(mLock);
5600 return waitingAsyncCallback_l();
5601}
5602
5603void AudioFlinger::OffloadThread::flushHw_l()
5604{
Eric Laurente659ef42014-09-29 13:06:46 -07005605 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005606 // Flush anything still waiting in the mixbuffer
5607 mCurrentWriteLength = 0;
5608 mBytesRemaining = 0;
5609 mPausedWriteLength = 0;
5610 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005611 // reset bytes written count to reflect that DSP buffers are empty after flush.
5612 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005613 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005614
Eric Laurentbfb1b832013-01-07 09:53:42 -08005615 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005616 // discard any pending drain or write ack by incrementing sequence
5617 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5618 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005619 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005620 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5621 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005622 }
5623}
5624
Haynes Mathew George05317d22016-05-03 16:34:26 -07005625void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5626{
5627 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005628 if (PlaybackThread::invalidateTracks_l(streamType)) {
5629 mFlushPending = true;
5630 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005631}
5632
Eric Laurentbfb1b832013-01-07 09:53:42 -08005633// ----------------------------------------------------------------------------
5634
Eric Laurent81784c32012-11-19 14:55:58 -08005635AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005636 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005637 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005638 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005639 mWaitTimeMs(UINT_MAX)
5640{
5641 addOutputTrack(mainThread);
5642}
5643
5644AudioFlinger::DuplicatingThread::~DuplicatingThread()
5645{
5646 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5647 mOutputTracks[i]->destroy();
5648 }
5649}
5650
5651void AudioFlinger::DuplicatingThread::threadLoop_mix()
5652{
5653 // mix buffers...
5654 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005655 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005656 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005657 if (mMixerBufferValid) {
5658 memset(mMixerBuffer, 0, mMixerBufferSize);
5659 } else {
5660 memset(mSinkBuffer, 0, mSinkBufferSize);
5661 }
Eric Laurent81784c32012-11-19 14:55:58 -08005662 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005663 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005664 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005665 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005666 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005667}
5668
5669void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5670{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005671 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005672 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005673 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005674 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005675 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005676 }
5677 } else if (mBytesWritten != 0) {
5678 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5679 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005680 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005681 } else {
5682 // flush remaining overflow buffers in output tracks
5683 writeFrames = 0;
5684 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005685 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005686 }
5687}
5688
Eric Laurentbfb1b832013-01-07 09:53:42 -08005689ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005690{
5691 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005692 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005693 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005694 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005695 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005696}
5697
5698void AudioFlinger::DuplicatingThread::threadLoop_standby()
5699{
5700 // DuplicatingThread implements standby by stopping all tracks
5701 for (size_t i = 0; i < outputTracks.size(); i++) {
5702 outputTracks[i]->stop();
5703 }
5704}
5705
5706void AudioFlinger::DuplicatingThread::saveOutputTracks()
5707{
5708 outputTracks = mOutputTracks;
5709}
5710
5711void AudioFlinger::DuplicatingThread::clearOutputTracks()
5712{
5713 outputTracks.clear();
5714}
5715
5716void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5717{
5718 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005719 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5720 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5721 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5722 const size_t frameCount =
5723 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5724 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5725 // from different OutputTracks and their associated MixerThreads (e.g. one may
5726 // nearly empty and the other may be dropping data).
5727
5728 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005729 this,
5730 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005731 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005732 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005733 frameCount,
5734 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005735 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5736 if (status != NO_ERROR) {
5737 ALOGE("addOutputTrack() initCheck failed %d", status);
5738 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005739 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005740 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5741 mOutputTracks.add(outputTrack);
5742 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5743 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005744}
5745
5746void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5747{
5748 Mutex::Autolock _l(mLock);
5749 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5750 if (mOutputTracks[i]->thread() == thread) {
5751 mOutputTracks[i]->destroy();
5752 mOutputTracks.removeAt(i);
5753 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005754 if (thread->getOutput() == mOutput) {
5755 mOutput = NULL;
5756 }
Eric Laurent81784c32012-11-19 14:55:58 -08005757 return;
5758 }
5759 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005760 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005761}
5762
5763// caller must hold mLock
5764void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5765{
5766 mWaitTimeMs = UINT_MAX;
5767 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5768 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5769 if (strong != 0) {
5770 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5771 if (waitTimeMs < mWaitTimeMs) {
5772 mWaitTimeMs = waitTimeMs;
5773 }
5774 }
5775 }
5776}
5777
5778
5779bool AudioFlinger::DuplicatingThread::outputsReady(
5780 const SortedVector< sp<OutputTrack> > &outputTracks)
5781{
5782 for (size_t i = 0; i < outputTracks.size(); i++) {
5783 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5784 if (thread == 0) {
5785 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5786 outputTracks[i].get());
5787 return false;
5788 }
5789 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5790 // see note at standby() declaration
5791 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5792 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5793 thread.get());
5794 return false;
5795 }
5796 }
5797 return true;
5798}
5799
5800uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5801{
5802 return (mWaitTimeMs * 1000) / 2;
5803}
5804
5805void AudioFlinger::DuplicatingThread::cacheParameters_l()
5806{
5807 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5808 updateWaitTime_l();
5809
5810 MixerThread::cacheParameters_l();
5811}
5812
5813// ----------------------------------------------------------------------------
5814// Record
5815// ----------------------------------------------------------------------------
5816
5817AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5818 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005819 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005820 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005821 audio_devices_t inDevice,
5822 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005823#ifdef TEE_SINK
5824 , const sp<NBAIO_Sink>& teeSink
5825#endif
5826 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005827 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005828 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005829 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005830 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005831#ifdef TEE_SINK
5832 , mTeeSink(teeSink)
5833#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005834 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5835 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005836 // mFastCapture below
5837 , mFastCaptureFutex(0)
5838 // mInputSource
5839 // mPipeSink
5840 // mPipeSource
5841 , mPipeFramesP2(0)
5842 // mPipeMemory
5843 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005844 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005845{
Glenn Kastend7dca052015-03-05 16:05:54 -08005846 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5847 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005848
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005849 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005850
5851 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005852 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005853 size_t numCounterOffers = 0;
5854 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005855#if !LOG_NDEBUG
5856 ssize_t index =
5857#else
5858 (void)
5859#endif
5860 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005861 ALOG_ASSERT(index == 0);
5862
5863 // initialize fast capture depending on configuration
5864 bool initFastCapture;
5865 switch (kUseFastCapture) {
5866 case FastCapture_Never:
5867 initFastCapture = false;
5868 break;
5869 case FastCapture_Always:
5870 initFastCapture = true;
5871 break;
5872 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005873 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005874 break;
5875 // case FastCapture_Dynamic:
5876 }
5877
5878 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005879 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005880 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005881 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5882 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005883 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5884 void *pipeBuffer;
5885 const sp<MemoryDealer> roHeap(readOnlyHeap());
5886 sp<IMemory> pipeMemory;
5887 if ((roHeap == 0) ||
5888 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5889 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5890 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5891 goto failed;
5892 }
5893 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5894 memset(pipeBuffer, 0, pipeSize);
5895 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5896 const NBAIO_Format offers[1] = {format};
5897 size_t numCounterOffers = 0;
5898 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5899 ALOG_ASSERT(index == 0);
5900 mPipeSink = pipe;
5901 PipeReader *pipeReader = new PipeReader(*pipe);
5902 numCounterOffers = 0;
5903 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5904 ALOG_ASSERT(index == 0);
5905 mPipeSource = pipeReader;
5906 mPipeFramesP2 = pipeFramesP2;
5907 mPipeMemory = pipeMemory;
5908
5909 // create fast capture
5910 mFastCapture = new FastCapture();
5911 FastCaptureStateQueue *sq = mFastCapture->sq();
5912#ifdef STATE_QUEUE_DUMP
5913 // FIXME
5914#endif
5915 FastCaptureState *state = sq->begin();
5916 state->mCblk = NULL;
5917 state->mInputSource = mInputSource.get();
5918 state->mInputSourceGen++;
5919 state->mPipeSink = pipe;
5920 state->mPipeSinkGen++;
5921 state->mFrameCount = mFrameCount;
5922 state->mCommand = FastCaptureState::COLD_IDLE;
5923 // already done in constructor initialization list
5924 //mFastCaptureFutex = 0;
5925 state->mColdFutexAddr = &mFastCaptureFutex;
5926 state->mColdGen++;
5927 state->mDumpState = &mFastCaptureDumpState;
5928#ifdef TEE_SINK
5929 // FIXME
5930#endif
5931 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5932 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5933 sq->end();
5934 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5935
5936 // start the fast capture
5937 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5938 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005939 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005940 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005941#ifdef AUDIO_WATCHDOG
5942 // FIXME
5943#endif
5944
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005945 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005946 }
5947failed: ;
5948
5949 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005950}
5951
Eric Laurent81784c32012-11-19 14:55:58 -08005952AudioFlinger::RecordThread::~RecordThread()
5953{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005954 if (mFastCapture != 0) {
5955 FastCaptureStateQueue *sq = mFastCapture->sq();
5956 FastCaptureState *state = sq->begin();
5957 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5958 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5959 if (old == -1) {
5960 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5961 }
5962 }
5963 state->mCommand = FastCaptureState::EXIT;
5964 sq->end();
5965 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5966 mFastCapture->join();
5967 mFastCapture.clear();
5968 }
5969 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005970 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005971 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005972}
5973
5974void AudioFlinger::RecordThread::onFirstRef()
5975{
Glenn Kastend7dca052015-03-05 16:05:54 -08005976 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005977}
5978
Eric Laurent81784c32012-11-19 14:55:58 -08005979bool AudioFlinger::RecordThread::threadLoop()
5980{
Eric Laurent81784c32012-11-19 14:55:58 -08005981 nsecs_t lastWarning = 0;
5982
5983 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005984
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005985reacquire_wakelock:
5986 sp<RecordTrack> activeTrack;
5987 {
5988 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07005989 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005990 }
5991
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005992 // used to request a deferred sleep, to be executed later while mutex is unlocked
5993 uint32_t sleepUs = 0;
5994
5995 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005996 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005997 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005998
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005999 // activeTracks accumulates a copy of a subset of mActiveTracks
6000 Vector< sp<RecordTrack> > activeTracks;
6001
Glenn Kasten735f45f2014-08-18 15:51:59 -07006002 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006003 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006004
Glenn Kasten735f45f2014-08-18 15:51:59 -07006005 // reference to a fast track which is about to be removed
6006 sp<RecordTrack> fastTrackToRemove;
6007
Eric Laurent81784c32012-11-19 14:55:58 -08006008 { // scope for mLock
6009 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006010
Eric Laurent021cf962014-05-13 10:18:14 -07006011 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006012
Eric Laurent000a4192014-01-29 15:17:32 -08006013 // check exitPending here because checkForNewParameters_l() and
6014 // checkForNewParameters_l() can temporarily release mLock
6015 if (exitPending()) {
6016 break;
6017 }
6018
Eric Laurent5c25d562016-07-13 17:17:45 -07006019 // sleep with mutex unlocked
6020 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006021 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006022 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6023 ATRACE_END();
6024 sleepUs = 0;
6025 continue;
6026 }
6027
Glenn Kasten2b806402013-11-20 16:37:38 -08006028 // if no active track(s), then standby and release wakelock
6029 size_t size = mActiveTracks.size();
6030 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006031 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006032 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006033 releaseWakeLock_l();
6034 ALOGV("RecordThread: loop stopping");
6035 // go to sleep
6036 mWaitWorkCV.wait(mLock);
6037 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006038 goto reacquire_wakelock;
6039 }
6040
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006041 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006042 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006043 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006044
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006045 activeTrack = mActiveTracks[i];
6046 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006047 if (activeTrack->isFastTrack()) {
6048 ALOG_ASSERT(fastTrackToRemove == 0);
6049 fastTrackToRemove = activeTrack;
6050 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006051 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006052 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006053 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006054 continue;
6055 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006056
6057 TrackBase::track_state activeTrackState = activeTrack->mState;
6058 switch (activeTrackState) {
6059
6060 case TrackBase::PAUSING:
6061 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006062 doBroadcast = true;
6063 size--;
6064 continue;
6065
6066 case TrackBase::STARTING_1:
6067 sleepUs = 10000;
6068 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006069 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006070 continue;
6071
6072 case TrackBase::STARTING_2:
6073 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006074 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006075 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006076 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006077 break;
6078
6079 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006080 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006081 break;
6082
6083 case TrackBase::IDLE:
6084 i++;
6085 continue;
6086
6087 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006088 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006089 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006090
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006091 activeTracks.add(activeTrack);
6092 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006093
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006094 if (activeTrack->isFastTrack()) {
6095 ALOG_ASSERT(!mFastTrackAvail);
6096 ALOG_ASSERT(fastTrack == 0);
6097 fastTrack = activeTrack;
6098 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006099 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006100
Andy Hungdae27702016-10-31 14:01:16 -07006101 mActiveTracks.updatePowerState(this);
6102
Eric Laurent5c25d562016-07-13 17:17:45 -07006103 if (allStopped) {
6104 standbyIfNotAlreadyInStandby();
6105 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006106 if (doBroadcast) {
6107 mStartStopCond.broadcast();
6108 }
6109
6110 // sleep if there are no active tracks to process
6111 if (activeTracks.size() == 0) {
6112 if (sleepUs == 0) {
6113 sleepUs = kRecordThreadSleepUs;
6114 }
6115 continue;
6116 }
6117 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006118
Eric Laurent81784c32012-11-19 14:55:58 -08006119 lockEffectChains_l(effectChains);
6120 }
6121
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006122 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006123
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006124 size_t size = effectChains.size();
6125 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006126 // thread mutex is not locked, but effect chain is locked
6127 effectChains[i]->process_l();
6128 }
6129
Glenn Kasten735f45f2014-08-18 15:51:59 -07006130 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006131 if (mFastCapture != 0) {
6132 FastCaptureStateQueue *sq = mFastCapture->sq();
6133 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006134 bool didModify = false;
6135 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006136 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6137 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6138 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6139 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6140 if (old == -1) {
6141 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6142 }
6143 }
6144 state->mCommand = FastCaptureState::READ_WRITE;
6145#if 0 // FIXME
6146 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006147 FastThreadDumpState::kSamplingNforLowRamDevice :
6148 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006149#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006150 didModify = true;
6151 }
6152 audio_track_cblk_t *cblkOld = state->mCblk;
6153 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6154 if (cblkNew != cblkOld) {
6155 state->mCblk = cblkNew;
6156 // block until acked if removing a fast track
6157 if (cblkOld != NULL) {
6158 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6159 }
6160 didModify = true;
6161 }
6162 sq->end(didModify);
6163 if (didModify) {
6164 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006165#if 0
6166 if (kUseFastCapture == FastCapture_Dynamic) {
6167 mNormalSource = mPipeSource;
6168 }
6169#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006170 }
6171 }
6172
Glenn Kasten735f45f2014-08-18 15:51:59 -07006173 // now run the fast track destructor with thread mutex unlocked
6174 fastTrackToRemove.clear();
6175
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006176 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6177 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6178 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6179 // If destination is non-contiguous, first read past the nominal end of buffer, then
6180 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006181
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006182 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006183 ssize_t framesRead;
6184
6185 // If an NBAIO source is present, use it to read the normal capture's data
6186 if (mPipeSource != 0) {
6187 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006188 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006189 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006190 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006191 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6192 // buffer size or at least for 20ms.
6193 size_t sleepFrames = max(
6194 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6195 if (framesRead <= (ssize_t) sleepFrames) {
6196 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6197 }
6198 if (framesRead < 0) {
6199 status_t status = (status_t) framesRead;
6200 switch (status) {
6201 case OVERRUN:
6202 ALOGW("overrun on read from pipe");
6203 framesRead = 0;
6204 break;
6205 case NEGOTIATE:
6206 ALOGE("re-negotiation is needed");
6207 framesRead = -1; // Will cause an attempt to recover.
6208 break;
6209 default:
6210 ALOGE("unknown error %d on read from pipe", status);
6211 break;
6212 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006213 }
6214 // otherwise use the HAL / AudioStreamIn directly
6215 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006216 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006217 size_t bytesRead;
6218 status_t result = mInput->stream->read(
6219 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006220 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006221 if (result < 0) {
6222 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006223 } else {
6224 framesRead = bytesRead / mFrameSize;
6225 }
6226 }
6227
Andy Hung3f0c9022016-01-15 17:49:46 -08006228 // Update server timestamp with server stats
6229 // systemTime() is optional if the hardware supports timestamps.
6230 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6231 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6232
6233 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006234 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006235 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006236 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006237 if (ret == NO_ERROR) {
6238 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6239 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6240 // Note: In general record buffers should tend to be empty in
6241 // a properly running pipeline.
6242 //
6243 // Also, it is not advantageous to call get_presentation_position during the read
6244 // as the read obtains a lock, preventing the timestamp call from executing.
6245 }
6246 }
6247 // Use this to track timestamp information
6248 // ALOGD("%s", mTimestamp.toString().c_str());
6249
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006250 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006251 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006252 // Force input into standby so that it tries to recover at next read attempt
6253 inputStandBy();
6254 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006255 }
6256 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006257 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006258 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006259 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006260
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006261 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006262 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006263 }
6264 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006265 {
6266 size_t part1 = mRsmpInFramesP2 - rear;
6267 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006268 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006269 (framesRead - part1) * mFrameSize);
6270 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006271 }
6272 rear = mRsmpInRear += framesRead;
6273
6274 size = activeTracks.size();
6275 // loop over each active track
6276 for (size_t i = 0; i < size; i++) {
6277 activeTrack = activeTracks[i];
6278
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006279 // skip fast tracks, as those are handled directly by FastCapture
6280 if (activeTrack->isFastTrack()) {
6281 continue;
6282 }
6283
Andy Hung73c02e42015-03-29 01:13:58 -07006284 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006285 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6286
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006287 enum {
6288 OVERRUN_UNKNOWN,
6289 OVERRUN_TRUE,
6290 OVERRUN_FALSE
6291 } overrun = OVERRUN_UNKNOWN;
6292
6293 // loop over getNextBuffer to handle circular sink
6294 for (;;) {
6295
6296 activeTrack->mSink.frameCount = ~0;
6297 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6298 size_t framesOut = activeTrack->mSink.frameCount;
6299 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6300
Andy Hung73c02e42015-03-29 01:13:58 -07006301 // check available frames and handle overrun conditions
6302 // if the record track isn't draining fast enough.
6303 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006304 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006305 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6306 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006307 overrun = OVERRUN_TRUE;
6308 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006309 if (framesOut == 0 || framesIn == 0) {
6310 break;
6311 }
6312
Andy Hung6770c6f2015-04-07 13:43:36 -07006313 // Don't allow framesOut to be larger than what is possible with resampling
6314 // from framesIn.
6315 // This isn't strictly necessary but helps limit buffer resizing in
6316 // RecordBufferConverter. TODO: remove when no longer needed.
6317 framesOut = min(framesOut,
6318 destinationFramesPossible(
6319 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006320 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6321 framesOut = activeTrack->mRecordBufferConverter->convert(
6322 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006323
6324 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6325 overrun = OVERRUN_FALSE;
6326 }
6327
6328 if (activeTrack->mFramesToDrop == 0) {
6329 if (framesOut > 0) {
6330 activeTrack->mSink.frameCount = framesOut;
6331 activeTrack->releaseBuffer(&activeTrack->mSink);
6332 }
6333 } else {
6334 // FIXME could do a partial drop of framesOut
6335 if (activeTrack->mFramesToDrop > 0) {
6336 activeTrack->mFramesToDrop -= framesOut;
6337 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006338 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006339 }
6340 } else {
6341 activeTrack->mFramesToDrop += framesOut;
6342 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6343 activeTrack->mSyncStartEvent->isCancelled()) {
6344 ALOGW("Synced record %s, session %d, trigger session %d",
6345 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6346 activeTrack->sessionId(),
6347 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006348 activeTrack->mSyncStartEvent->triggerSession() :
6349 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006350 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006351 }
6352 }
6353 }
6354
6355 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006356 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006357 }
6358 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006359
6360 switch (overrun) {
6361 case OVERRUN_TRUE:
6362 // client isn't retrieving buffers fast enough
6363 if (!activeTrack->setOverflow()) {
6364 nsecs_t now = systemTime();
6365 // FIXME should lastWarning per track?
6366 if ((now - lastWarning) > kWarningThrottleNs) {
6367 ALOGW("RecordThread: buffer overflow");
6368 lastWarning = now;
6369 }
6370 }
6371 break;
6372 case OVERRUN_FALSE:
6373 activeTrack->clearOverflow();
6374 break;
6375 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006376 break;
6377 }
6378
Andy Hung3f0c9022016-01-15 17:49:46 -08006379 // update frame information and push timestamp out
6380 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006381 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006382 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6383 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006384 }
6385
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006386unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006387 // enable changes in effect chain
6388 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006389 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006390 }
6391
Glenn Kasten93e471f2013-08-19 08:40:07 -07006392 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006393
6394 {
6395 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006396 for (size_t i = 0; i < mTracks.size(); i++) {
6397 sp<RecordTrack> track = mTracks[i];
6398 track->invalidate();
6399 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006400 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006401 mStartStopCond.broadcast();
6402 }
6403
6404 releaseWakeLock();
6405
6406 ALOGV("RecordThread %p exiting", this);
6407 return false;
6408}
6409
Glenn Kasten93e471f2013-08-19 08:40:07 -07006410void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006411{
6412 if (!mStandby) {
6413 inputStandBy();
6414 mStandby = true;
6415 }
6416}
6417
6418void AudioFlinger::RecordThread::inputStandBy()
6419{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006420 // Idle the fast capture if it's currently running
6421 if (mFastCapture != 0) {
6422 FastCaptureStateQueue *sq = mFastCapture->sq();
6423 FastCaptureState *state = sq->begin();
6424 if (!(state->mCommand & FastCaptureState::IDLE)) {
6425 state->mCommand = FastCaptureState::COLD_IDLE;
6426 state->mColdFutexAddr = &mFastCaptureFutex;
6427 state->mColdGen++;
6428 mFastCaptureFutex = 0;
6429 sq->end();
6430 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6431 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6432#if 0
6433 if (kUseFastCapture == FastCapture_Dynamic) {
6434 // FIXME
6435 }
6436#endif
6437#ifdef AUDIO_WATCHDOG
6438 // FIXME
6439#endif
6440 } else {
6441 sq->end(false /*didModify*/);
6442 }
6443 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006444 status_t result = mInput->stream->standby();
6445 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006446
6447 // If going into standby, flush the pipe source.
6448 if (mPipeSource.get() != nullptr) {
6449 const ssize_t flushed = mPipeSource->flush();
6450 if (flushed > 0) {
6451 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6452 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6453 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6454 }
6455 }
Eric Laurent81784c32012-11-19 14:55:58 -08006456}
6457
Glenn Kasten05997e22014-03-13 15:08:33 -07006458// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006459sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006460 const sp<AudioFlinger::Client>& client,
6461 uint32_t sampleRate,
6462 audio_format_t format,
6463 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006464 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006465 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006466 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006467 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006468 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006469 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006470 status_t *status,
6471 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006472{
Glenn Kasten74935e42013-12-19 08:56:45 -08006473 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006474 sp<RecordTrack> track;
6475 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006476 audio_input_flags_t inputFlags = mInput->flags;
6477
6478 // special case for FAST flag considered OK if fast capture is present
6479 if (hasFastCapture()) {
6480 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6481 }
6482
6483 // Check if requested flags are compatible with output stream flags
6484 if ((*flags & inputFlags) != *flags) {
6485 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6486 " input flags (%08x)",
6487 *flags, inputFlags);
6488 *flags = (audio_input_flags_t)(*flags & inputFlags);
6489 }
Eric Laurent81784c32012-11-19 14:55:58 -08006490
Glenn Kasten90e58b12013-07-31 16:16:02 -07006491 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006492 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006493 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006494 // we formerly checked for a callback handler (non-0 tid),
6495 // but that is no longer required for TRANSFER_OBTAIN mode
6496 //
Glenn Kasten74105912014-07-03 12:28:53 -07006497 // frame count is not specified, or is exactly the pipe depth
6498 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006499 // PCM data
6500 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006501 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006502 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006503 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006504 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006505 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006506 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006507 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006508 hasFastCapture() &&
6509 // there are sufficient fast track slots available
6510 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006511 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006512 // check compatibility with audio effects.
6513 Mutex::Autolock _l(mLock);
6514 // Do not accept FAST flag if the session has software effects
6515 sp<EffectChain> chain = getEffectChain_l(sessionId);
6516 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006517 audio_input_flags_t old = *flags;
6518 chain->checkInputFlagCompatibility(flags);
6519 if (old != *flags) {
6520 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6521 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006522 }
6523 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006524 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006525 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6526 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006527 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006528 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006529 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006530 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006531 frameCount, mFrameCount, mPipeFramesP2,
6532 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6533 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006534 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006535 }
6536 }
6537
6538 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006539 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006540 // fast track: frame count is exactly the pipe depth
6541 frameCount = mPipeFramesP2;
6542 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6543 *notificationFrames = mFrameCount;
6544 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006545 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6546 // or 20 ms if there is a fast capture
6547 // TODO This could be a roundupRatio inline, and const
6548 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6549 * sampleRate + mSampleRate - 1) / mSampleRate;
6550 // minimum number of notification periods is at least kMinNotifications,
6551 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6552 static const size_t kMinNotifications = 3;
6553 static const uint32_t kMinMs = 30;
6554 // TODO This could be a roundupRatio inline
6555 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6556 // TODO This could be a roundupRatio inline
6557 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6558 maxNotificationFrames;
6559 const size_t minFrameCount = maxNotificationFrames *
6560 max(kMinNotifications, minNotificationsByMs);
6561 frameCount = max(frameCount, minFrameCount);
6562 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6563 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006564 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006565 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006566 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006567
Glenn Kasten15e57982013-09-24 11:52:37 -07006568 lStatus = initCheck();
6569 if (lStatus != NO_ERROR) {
6570 ALOGE("createRecordTrack_l() audio driver not initialized");
6571 goto Exit;
6572 }
Eric Laurent81784c32012-11-19 14:55:58 -08006573
6574 { // scope for mLock
6575 Mutex::Autolock _l(mLock);
6576
6577 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006578 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006579 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006580
Glenn Kasten03003332013-08-06 15:40:54 -07006581 lStatus = track->initCheck();
6582 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006583 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006584 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006585 goto Exit;
6586 }
6587 mTracks.add(track);
6588
6589 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6590 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6591 mAudioFlinger->btNrecIsOff();
6592 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6593 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006594
Eric Laurent05067782016-06-01 18:27:28 -07006595 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006596 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6597 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6598 // so ask activity manager to do this on our behalf
6599 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6600 }
Eric Laurent81784c32012-11-19 14:55:58 -08006601 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006602
Eric Laurent81784c32012-11-19 14:55:58 -08006603 lStatus = NO_ERROR;
6604
6605Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006606 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006607 return track;
6608}
6609
6610status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6611 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006612 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006613{
6614 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6615 sp<ThreadBase> strongMe = this;
6616 status_t status = NO_ERROR;
6617
6618 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006619 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006620 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006621 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006622 triggerSession,
6623 recordTrack->sessionId(),
6624 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006625 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006626 // Sync event can be cancelled by the trigger session if the track is not in a
6627 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006628 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006629 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006630 } else {
6631 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006632 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006633 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006634 }
6635 }
6636
6637 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006638 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006639 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006640 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6641 if (recordTrack->mState == TrackBase::PAUSING) {
6642 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006643 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006644 } else {
6645 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006646 }
6647 return status;
6648 }
6649
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006650 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6651 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6652 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006653 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006654 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006655 status_t status = NO_ERROR;
6656 if (recordTrack->isExternalTrack()) {
6657 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006658 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006659 mLock.lock();
6660 // FIXME should verify that recordTrack is still in mActiveTracks
6661 if (status != NO_ERROR) {
6662 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006663 recordTrack->clearSyncStartEvent();
6664 ALOGV("RecordThread::start error %d", status);
6665 return status;
6666 }
Eric Laurent81784c32012-11-19 14:55:58 -08006667 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006668 // Catch up with current buffer indices if thread is already running.
6669 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6670 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6671 // see previously buffered data before it called start(), but with greater risk of overrun.
6672
Andy Hung73c02e42015-03-29 01:13:58 -07006673 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006674 // clear any converter state as new data will be discontinuous
6675 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006676 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006677 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006678 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006679 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006680 ALOGV("Record failed to start");
6681 status = BAD_VALUE;
6682 goto startError;
6683 }
Eric Laurent81784c32012-11-19 14:55:58 -08006684 return status;
6685 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006686
Eric Laurent81784c32012-11-19 14:55:58 -08006687startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006688 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006689 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006690 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006691 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006692 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006693 return status;
6694}
6695
Eric Laurent81784c32012-11-19 14:55:58 -08006696void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6697{
6698 sp<SyncEvent> strongEvent = event.promote();
6699
6700 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006701 sp<RefBase> ptr = strongEvent->cookie().promote();
6702 if (ptr != 0) {
6703 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6704 recordTrack->handleSyncStartEvent(strongEvent);
6705 }
Eric Laurent81784c32012-11-19 14:55:58 -08006706 }
6707}
6708
Glenn Kastena8356f62013-07-25 14:37:52 -07006709bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006710 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006711 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006712 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006713 return false;
6714 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006715 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006716 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006717 // signal thread to stop
6718 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006719 // do not wait for mStartStopCond if exiting
6720 if (exitPending()) {
6721 return true;
6722 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006723 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006724 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006725 // if we have been restarted, recordTrack is in mActiveTracks here
6726 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006727 ALOGV("Record stopped OK");
6728 return true;
6729 }
6730 return false;
6731}
6732
Glenn Kasten0f11b512014-01-31 16:18:54 -08006733bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006734{
6735 return false;
6736}
6737
Glenn Kasten0f11b512014-01-31 16:18:54 -08006738status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006739{
6740#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6741 if (!isValidSyncEvent(event)) {
6742 return BAD_VALUE;
6743 }
6744
Glenn Kastend848eb42016-03-08 13:42:11 -08006745 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006746 status_t ret = NAME_NOT_FOUND;
6747
6748 Mutex::Autolock _l(mLock);
6749
6750 for (size_t i = 0; i < mTracks.size(); i++) {
6751 sp<RecordTrack> track = mTracks[i];
6752 if (eventSession == track->sessionId()) {
6753 (void) track->setSyncEvent(event);
6754 ret = NO_ERROR;
6755 }
6756 }
6757 return ret;
6758#else
6759 return BAD_VALUE;
6760#endif
6761}
6762
6763// destroyTrack_l() must be called with ThreadBase::mLock held
6764void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6765{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006766 track->terminate();
6767 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006768 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006769 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006770 removeTrack_l(track);
6771 }
6772}
6773
6774void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6775{
6776 mTracks.remove(track);
6777 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006778 if (track->isFastTrack()) {
6779 ALOG_ASSERT(!mFastTrackAvail);
6780 mFastTrackAvail = true;
6781 }
Eric Laurent81784c32012-11-19 14:55:58 -08006782}
6783
6784void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6785{
6786 dumpInternals(fd, args);
6787 dumpTracks(fd, args);
6788 dumpEffectChains(fd, args);
6789}
6790
6791void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6792{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006793 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006794
Glenn Kasten44182c22015-03-05 17:12:23 -08006795 dumpBase(fd, args);
6796
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006797 AudioStreamIn *input = mInput;
6798 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6799 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6800 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006801 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006802 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006803 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006804 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006805 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006806
Glenn Kasten2f90c512015-12-02 11:40:09 -08006807 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6808 // while we are dumping it. It may be inconsistent, but it won't mutate!
6809 // This is a large object so we place it on the heap.
6810 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6811 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6812 copy->dump(fd);
6813 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006814}
6815
Glenn Kasten0f11b512014-01-31 16:18:54 -08006816void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006817{
6818 const size_t SIZE = 256;
6819 char buffer[SIZE];
6820 String8 result;
6821
Marco Nelissenb2208842014-02-07 14:00:50 -08006822 size_t numtracks = mTracks.size();
6823 size_t numactive = mActiveTracks.size();
6824 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006825 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006826 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006827 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006828 RecordTrack::appendDumpHeader(result);
6829 for (size_t i = 0; i < numtracks ; ++i) {
6830 sp<RecordTrack> track = mTracks[i];
6831 if (track != 0) {
6832 bool active = mActiveTracks.indexOf(track) >= 0;
6833 if (active) {
6834 numactiveseen++;
6835 }
6836 track->dump(buffer, SIZE, active);
6837 result.append(buffer);
6838 }
Eric Laurent81784c32012-11-19 14:55:58 -08006839 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006840 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006841 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006842 }
6843
Marco Nelissenb2208842014-02-07 14:00:50 -08006844 if (numactiveseen != numactive) {
6845 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6846 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006847 result.append(buffer);
6848 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006849 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006850 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006851 if (mTracks.indexOf(track) < 0) {
6852 track->dump(buffer, SIZE, true);
6853 result.append(buffer);
6854 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006855 }
Eric Laurent81784c32012-11-19 14:55:58 -08006856
6857 }
6858 write(fd, result.string(), result.size());
6859}
6860
Andy Hung73c02e42015-03-29 01:13:58 -07006861
6862void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6863{
6864 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6865 RecordThread *recordThread = (RecordThread *) threadBase.get();
6866 mRsmpInFront = recordThread->mRsmpInRear;
6867 mRsmpInUnrel = 0;
6868}
6869
6870void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6871 size_t *framesAvailable, bool *hasOverrun)
6872{
6873 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6874 RecordThread *recordThread = (RecordThread *) threadBase.get();
6875 const int32_t rear = recordThread->mRsmpInRear;
6876 const int32_t front = mRsmpInFront;
6877 const ssize_t filled = rear - front;
6878
6879 size_t framesIn;
6880 bool overrun = false;
6881 if (filled < 0) {
6882 // should not happen, but treat like a massive overrun and re-sync
6883 framesIn = 0;
6884 mRsmpInFront = rear;
6885 overrun = true;
6886 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6887 framesIn = (size_t) filled;
6888 } else {
6889 // client is not keeping up with server, but give it latest data
6890 framesIn = recordThread->mRsmpInFrames;
6891 mRsmpInFront = /* front = */ rear - framesIn;
6892 overrun = true;
6893 }
6894 if (framesAvailable != NULL) {
6895 *framesAvailable = framesIn;
6896 }
6897 if (hasOverrun != NULL) {
6898 *hasOverrun = overrun;
6899 }
6900}
6901
Eric Laurent81784c32012-11-19 14:55:58 -08006902// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006903status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006904 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006905{
Andy Hung73c02e42015-03-29 01:13:58 -07006906 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006907 if (threadBase == 0) {
6908 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006909 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006910 return NOT_ENOUGH_DATA;
6911 }
6912 RecordThread *recordThread = (RecordThread *) threadBase.get();
6913 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006914 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006915 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006916 // FIXME should not be P2 (don't want to increase latency)
6917 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006918 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006919 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006920 front &= recordThread->mRsmpInFramesP2 - 1;
6921 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006922 if (part1 > (size_t) filled) {
6923 part1 = filled;
6924 }
6925 size_t ask = buffer->frameCount;
6926 ALOG_ASSERT(ask > 0);
6927 if (part1 > ask) {
6928 part1 = ask;
6929 }
6930 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006931 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006932 buffer->raw = NULL;
6933 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006934 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006935 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006936 }
6937
Andy Hung57446612015-04-19 23:56:46 -07006938 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006939 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006940 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006941 return NO_ERROR;
6942}
6943
6944// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006945void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6946 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006947{
Glenn Kasten85948432013-08-19 12:09:05 -07006948 size_t stepCount = buffer->frameCount;
6949 if (stepCount == 0) {
6950 return;
6951 }
Andy Hung73c02e42015-03-29 01:13:58 -07006952 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6953 mRsmpInUnrel -= stepCount;
6954 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006955 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006956 buffer->frameCount = 0;
6957}
6958
Andy Hung97a893e2015-03-29 01:03:07 -07006959
Eric Laurent10351942014-05-08 18:49:52 -07006960bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6961 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006962{
6963 bool reconfig = false;
6964
Eric Laurent10351942014-05-08 18:49:52 -07006965 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006966
Eric Laurent10351942014-05-08 18:49:52 -07006967 audio_format_t reqFormat = mFormat;
6968 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006969 // 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 -07006970 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6971
6972 AudioParameter param = AudioParameter(keyValuePair);
6973 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07006974
6975 // scope for AutoPark extends to end of method
6976 AutoPark<FastCapture> park(mFastCapture);
6977
Eric Laurent10351942014-05-08 18:49:52 -07006978 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6979 // channel count change can be requested. Do we mandate the first client defines the
6980 // HAL sampling rate and channel count or do we allow changes on the fly?
6981 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6982 samplingRate = value;
6983 reconfig = true;
6984 }
6985 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006986 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006987 status = BAD_VALUE;
6988 } else {
6989 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006990 reconfig = true;
6991 }
Eric Laurent10351942014-05-08 18:49:52 -07006992 }
6993 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6994 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006995 if (!audio_is_input_channel(mask) ||
6996 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006997 status = BAD_VALUE;
6998 } else {
6999 channelMask = mask;
7000 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007001 }
Eric Laurent10351942014-05-08 18:49:52 -07007002 }
7003 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7004 // do not accept frame count changes if tracks are open as the track buffer
7005 // size depends on frame count and correct behavior would not be guaranteed
7006 // if frame count is changed after track creation
7007 if (mActiveTracks.size() > 0) {
7008 status = INVALID_OPERATION;
7009 } else {
7010 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007011 }
Eric Laurent10351942014-05-08 18:49:52 -07007012 }
7013 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7014 // forward device change to effects that have requested to be
7015 // aware of attached audio device.
7016 for (size_t i = 0; i < mEffectChains.size(); i++) {
7017 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007018 }
Eric Laurent81784c32012-11-19 14:55:58 -08007019
Eric Laurent10351942014-05-08 18:49:52 -07007020 // store input device and output device but do not forward output device to audio HAL.
7021 // Note that status is ignored by the caller for output device
7022 // (see AudioFlinger::setParameters()
7023 if (audio_is_output_devices(value)) {
7024 mOutDevice = value;
7025 status = BAD_VALUE;
7026 } else {
7027 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007028 if (value != AUDIO_DEVICE_NONE) {
7029 mPrevInDevice = value;
7030 }
Eric Laurent10351942014-05-08 18:49:52 -07007031 // disable AEC and NS if the device is a BT SCO headset supporting those
7032 // pre processings
7033 if (mTracks.size() > 0) {
7034 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7035 mAudioFlinger->btNrecIsOff();
7036 for (size_t i = 0; i < mTracks.size(); i++) {
7037 sp<RecordTrack> track = mTracks[i];
7038 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7039 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007040 }
7041 }
7042 }
Eric Laurent10351942014-05-08 18:49:52 -07007043 }
7044 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7045 mAudioSource != (audio_source_t)value) {
7046 // forward device change to effects that have requested to be
7047 // aware of attached audio device.
7048 for (size_t i = 0; i < mEffectChains.size(); i++) {
7049 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007050 }
Eric Laurent10351942014-05-08 18:49:52 -07007051 mAudioSource = (audio_source_t)value;
7052 }
Glenn Kastene198c362013-08-13 09:13:36 -07007053
Eric Laurent10351942014-05-08 18:49:52 -07007054 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007055 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007056 if (status == INVALID_OPERATION) {
7057 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007058 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007059 }
7060 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007061 if (status == BAD_VALUE) {
7062 uint32_t sRate;
7063 audio_channel_mask_t channelMask;
7064 audio_format_t format;
7065 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7066 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7067 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7068 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7069 status = NO_ERROR;
7070 }
Eric Laurent81784c32012-11-19 14:55:58 -08007071 }
Eric Laurent10351942014-05-08 18:49:52 -07007072 if (status == NO_ERROR) {
7073 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007074 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007075 }
7076 }
Eric Laurent81784c32012-11-19 14:55:58 -08007077 }
Eric Laurent10351942014-05-08 18:49:52 -07007078
Eric Laurent81784c32012-11-19 14:55:58 -08007079 return reconfig;
7080}
7081
7082String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7083{
Eric Laurent81784c32012-11-19 14:55:58 -08007084 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007085 if (initCheck() == NO_ERROR) {
7086 String8 out_s8;
7087 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7088 return out_s8;
7089 }
Eric Laurent81784c32012-11-19 14:55:58 -08007090 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007091 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007092}
7093
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007094void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007095 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7096
7097 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007098
7099 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007100 case AUDIO_INPUT_OPENED:
7101 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007102 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007103 desc->mChannelMask = mChannelMask;
7104 desc->mSamplingRate = mSampleRate;
7105 desc->mFormat = mFormat;
7106 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007107 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007108 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007109 break;
7110
Eric Laurent73e26b62015-04-27 16:55:58 -07007111 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007112 default:
7113 break;
7114 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007115 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007116}
7117
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007118void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007119{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007120 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7121 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007122 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007123 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007124 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007125 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7126 result = mInput->stream->getFrameSize(&mFrameSize);
7127 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7128 result = mInput->stream->getBufferSize(&mBufferSize);
7129 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007130 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007131 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007132 // 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 -07007133 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007134 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007135 // A larger value should allow more old data to be read after a track calls start(),
7136 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007137 //
7138 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007139 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007140 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007141 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007142 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007143
7144 // TODO optimize audio capture buffer sizes ...
7145 // Here we calculate the size of the sliding buffer used as a source
7146 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7147 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7148 // be better to have it derived from the pipe depth in the long term.
7149 // The current value is higher than necessary. However it should not add to latency.
7150
Glenn Kasten85948432013-08-19 12:09:05 -07007151 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007152 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7153 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7154 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007155
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007156 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7157 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007158}
7159
Glenn Kasten5f972c02014-01-13 09:59:31 -08007160uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007161{
7162 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007163 uint32_t result;
7164 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7165 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007166 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007167 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007168}
7169
Eric Laurent4c415062016-06-17 16:14:16 -07007170// hasAudioSession_l() must be called with ThreadBase::mLock held
7171uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007172{
Eric Laurent81784c32012-11-19 14:55:58 -08007173 uint32_t result = 0;
7174 if (getEffectChain_l(sessionId) != 0) {
7175 result = EFFECT_SESSION;
7176 }
7177
7178 for (size_t i = 0; i < mTracks.size(); ++i) {
7179 if (sessionId == mTracks[i]->sessionId()) {
7180 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007181 if (mTracks[i]->isFastTrack()) {
7182 result |= FAST_SESSION;
7183 }
Eric Laurent81784c32012-11-19 14:55:58 -08007184 break;
7185 }
7186 }
7187
7188 return result;
7189}
7190
Glenn Kastend848eb42016-03-08 13:42:11 -08007191KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007192{
Glenn Kastend848eb42016-03-08 13:42:11 -08007193 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007194 Mutex::Autolock _l(mLock);
7195 for (size_t j = 0; j < mTracks.size(); ++j) {
7196 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007197 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007198 if (ids.indexOfKey(sessionId) < 0) {
7199 ids.add(sessionId, true);
7200 }
7201 }
7202 return ids;
7203}
7204
7205AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7206{
7207 Mutex::Autolock _l(mLock);
7208 AudioStreamIn *input = mInput;
7209 mInput = NULL;
7210 return input;
7211}
7212
7213// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007214sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007215{
7216 if (mInput == NULL) {
7217 return NULL;
7218 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007219 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007220}
7221
7222status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7223{
7224 // only one chain per input thread
7225 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007226 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007227 return INVALID_OPERATION;
7228 }
7229 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007230 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007231 chain->setInBuffer(NULL);
7232 chain->setOutBuffer(NULL);
7233
7234 checkSuspendOnAddEffectChain_l(chain);
7235
Eric Laurent1b928682014-10-02 19:41:47 -07007236 // make sure enabled pre processing effects state is communicated to the HAL as we
7237 // just moved them to a new input stream.
7238 chain->syncHalEffectsState();
7239
Eric Laurent81784c32012-11-19 14:55:58 -08007240 mEffectChains.add(chain);
7241
7242 return NO_ERROR;
7243}
7244
7245size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7246{
7247 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7248 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007249 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007250 chain.get(), mEffectChains.size(), this);
7251 if (mEffectChains.size() == 1) {
7252 mEffectChains.removeAt(0);
7253 }
7254 return 0;
7255}
7256
Eric Laurent1c333e22014-05-20 10:48:17 -07007257status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7258 audio_patch_handle_t *handle)
7259{
7260 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007261
7262 // store new device and send to effects
7263 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007264 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007265 for (size_t i = 0; i < mEffectChains.size(); i++) {
7266 mEffectChains[i]->setDevice_l(mInDevice);
7267 }
7268
7269 // disable AEC and NS if the device is a BT SCO headset supporting those
7270 // pre processings
7271 if (mTracks.size() > 0) {
7272 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7273 mAudioFlinger->btNrecIsOff();
7274 for (size_t i = 0; i < mTracks.size(); i++) {
7275 sp<RecordTrack> track = mTracks[i];
7276 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7277 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7278 }
7279 }
7280
7281 // store new source and send to effects
7282 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7283 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007284 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007285 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007286 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007287 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007288
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007289 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007290 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7291 status = hwDevice->createAudioPatch(patch->num_sources,
7292 patch->sources,
7293 patch->num_sinks,
7294 patch->sinks,
7295 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007296 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007297 char *address;
7298 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7299 address = audio_device_address_to_parameter(
7300 patch->sources[0].ext.device.type,
7301 patch->sources[0].ext.device.address);
7302 } else {
7303 address = (char *)calloc(1, 1);
7304 }
7305 AudioParameter param = AudioParameter(String8(address));
7306 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007307 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007308 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007309 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007310 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007311 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007312 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007313 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007314
Eric Laurente8726fe2015-06-26 09:39:24 -07007315 if (mInDevice != mPrevInDevice) {
7316 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7317 mPrevInDevice = mInDevice;
7318 }
Eric Laurent296fb132015-05-01 11:38:42 -07007319
Eric Laurent1c333e22014-05-20 10:48:17 -07007320 return status;
7321}
7322
7323status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7324{
7325 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007326
7327 mInDevice = AUDIO_DEVICE_NONE;
7328
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007329 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007330 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7331 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007332 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007333 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007334 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007335 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007336 }
7337 return status;
7338}
7339
Eric Laurent83b88082014-06-20 18:31:16 -07007340void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7341{
7342 Mutex::Autolock _l(mLock);
7343 mTracks.add(record);
7344}
7345
7346void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7347{
7348 Mutex::Autolock _l(mLock);
7349 destroyTrack_l(record);
7350}
7351
7352void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7353{
7354 ThreadBase::getAudioPortConfig(config);
7355 config->role = AUDIO_PORT_ROLE_SINK;
7356 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7357 config->ext.mix.usecase.source = mAudioSource;
7358}
Eric Laurent1c333e22014-05-20 10:48:17 -07007359
Glenn Kasten63238ef2015-03-02 15:50:29 -08007360} // namespace android