blob: a57821bdb15bc1d0c7129448a6b979bb2f1442d6 [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
Mikhail Naganov83f04272017-02-07 10:45:09 -0800616void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700617{
618 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800619 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700620}
621
Eric Laurent81784c32012-11-19 14:55:58 -0800622// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800623void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
624 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800625{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800626 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700627 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800628}
629
Eric Laurent10351942014-05-08 18:49:52 -0700630// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
631status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800632{
Andy Hung2ddee192015-12-18 17:34:44 -0800633 sp<ConfigEvent> configEvent;
634 AudioParameter param(keyValuePair);
635 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700636 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800637 setMasterMono_l(value != 0);
638 if (param.size() == 1) {
639 return NO_ERROR; // should be a solo parameter - we don't pass down
640 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700641 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800642 configEvent = new SetParameterConfigEvent(param.toString());
643 } else {
644 configEvent = new SetParameterConfigEvent(keyValuePair);
645 }
Eric Laurent10351942014-05-08 18:49:52 -0700646 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700647}
648
Eric Laurent1c333e22014-05-20 10:48:17 -0700649status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
650 const struct audio_patch *patch,
651 audio_patch_handle_t *handle)
652{
653 Mutex::Autolock _l(mLock);
654 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
655 status_t status = sendConfigEvent_l(configEvent);
656 if (status == NO_ERROR) {
657 CreateAudioPatchConfigEventData *data =
658 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
659 *handle = data->mHandle;
660 }
661 return status;
662}
663
664status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
665 const audio_patch_handle_t handle)
666{
667 Mutex::Autolock _l(mLock);
668 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
669 return sendConfigEvent_l(configEvent);
670}
671
672
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700673// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700674void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700675{
Eric Laurent10351942014-05-08 18:49:52 -0700676 bool configChanged = false;
677
Eric Laurent81784c32012-11-19 14:55:58 -0800678 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700679 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700680 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800681 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700682 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700683 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700684 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
685 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800686 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700687 true /*asynchronous*/);
688 if (err != 0) {
689 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700690 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700691 }
692 } break;
693 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700694 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700695 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700696 } break;
697 case CFG_EVENT_SET_PARAMETER: {
698 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
699 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
700 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700701 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700702 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700703 case CFG_EVENT_CREATE_AUDIO_PATCH: {
704 CreateAudioPatchConfigEventData *data =
705 (CreateAudioPatchConfigEventData *)event->mData.get();
706 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
707 } break;
708 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
709 ReleaseAudioPatchConfigEventData *data =
710 (ReleaseAudioPatchConfigEventData *)event->mData.get();
711 event->mStatus = releaseAudioPatch_l(data->mHandle);
712 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700713 default:
Eric Laurent10351942014-05-08 18:49:52 -0700714 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700715 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800716 }
Eric Laurent10351942014-05-08 18:49:52 -0700717 {
718 Mutex::Autolock _l(event->mLock);
719 if (event->mWaitStatus) {
720 event->mWaitStatus = false;
721 event->mCond.signal();
722 }
723 }
724 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
725 }
726
727 if (configChanged) {
728 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800729 }
Eric Laurent81784c32012-11-19 14:55:58 -0800730}
731
Marco Nelissenb2208842014-02-07 14:00:50 -0800732String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
733 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700734 const audio_channel_representation_t representation =
735 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700736
737 switch (representation) {
738 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
739 if (output) {
740 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
741 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
742 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
743 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
744 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
745 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
746 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
747 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
748 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
749 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
750 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
751 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
753 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
754 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
755 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
756 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
757 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
758 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
759 } else {
760 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
761 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
762 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
763 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
764 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
765 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
766 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
767 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
768 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
769 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
770 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
771 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
772 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
773 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
774 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
775 }
776 const int len = s.length();
777 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700778 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700779 s.unlockBuffer(len - 2); // remove trailing ", "
780 }
781 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800782 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700783 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
784 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
785 return s;
786 default:
787 s.appendFormat("unknown mask, representation:%d bits:%#x",
788 representation, audio_channel_mask_get_bits(mask));
789 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800790 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800791}
792
Glenn Kasten0f11b512014-01-31 16:18:54 -0800793void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800794{
795 const size_t SIZE = 256;
796 char buffer[SIZE];
797 String8 result;
798
799 bool locked = AudioFlinger::dumpTryLock(mLock);
800 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700801 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800802 }
803
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800804 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700805 dprintf(fd, " I/O handle: %d\n", mId);
806 dprintf(fd, " TID: %d\n", getTid());
807 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700808 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700809 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700810 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700811 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700812 dprintf(fd, " Channel count: %u\n", mChannelCount);
813 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800814 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700815 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700816 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700817 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800818 size_t numConfig = mConfigEvents.size();
819 if (numConfig) {
820 for (size_t i = 0; i < numConfig; i++) {
821 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700822 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800823 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700824 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800825 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700826 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800827 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700828 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
829 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800830 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800831
832 if (locked) {
833 mLock.unlock();
834 }
835}
836
837void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
838{
839 const size_t SIZE = 256;
840 char buffer[SIZE];
841 String8 result;
842
Marco Nelissenb2208842014-02-07 14:00:50 -0800843 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000844 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800845 write(fd, buffer, strlen(buffer));
846
Marco Nelissenb2208842014-02-07 14:00:50 -0800847 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800848 sp<EffectChain> chain = mEffectChains[i];
849 if (chain != 0) {
850 chain->dump(fd, args);
851 }
852 }
853}
854
Andy Hungdae27702016-10-31 14:01:16 -0700855void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800856{
857 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700858 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800859}
860
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100861String16 AudioFlinger::ThreadBase::getWakeLockTag()
862{
863 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800864 case MIXER:
865 return String16("AudioMix");
866 case DIRECT:
867 return String16("AudioDirectOut");
868 case DUPLICATING:
869 return String16("AudioDup");
870 case RECORD:
871 return String16("AudioIn");
872 case OFFLOAD:
873 return String16("AudioOffload");
874 default:
875 ALOG_ASSERT(false);
876 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100877 }
878}
879
Andy Hungdae27702016-10-31 14:01:16 -0700880void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800881{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800882 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800883 if (mPowerManager != 0) {
884 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700885 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
886 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700887 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100888 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700889 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700890 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800891 if (status == NO_ERROR) {
892 mWakeLockToken = binder;
893 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800894 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800895 }
Wei Jia3f273d12015-11-24 09:06:49 -0800896
Andy Hung3f0c9022016-01-15 17:49:46 -0800897 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800898 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
899 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800900}
901
902void AudioFlinger::ThreadBase::releaseWakeLock()
903{
904 Mutex::Autolock _l(mLock);
905 releaseWakeLock_l();
906}
907
908void AudioFlinger::ThreadBase::releaseWakeLock_l()
909{
Andy Hung3f0c9022016-01-15 17:49:46 -0800910 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800911 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800912 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800913 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700914 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
915 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800916 }
917 mWakeLockToken.clear();
918 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800919}
920
921void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700922 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800923 // use checkService() to avoid blocking if power service is not up yet
924 sp<IBinder> binder =
925 defaultServiceManager()->checkService(String16("power"));
926 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800927 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800928 } else {
929 mPowerManager = interface_cast<IPowerManager>(binder);
930 binder->linkToDeath(mDeathRecipient);
931 }
932 }
933}
934
Andy Hungd01b0f12016-11-07 16:10:30 -0800935void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800936 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700937
938#if !LOG_NDEBUG
939 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800940 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700941 s << uid << " ";
942 }
943 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
944#endif
945
Andy Hung438e7572015-12-14 15:51:17 -0800946 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
947 if (mSystemReady) {
948 ALOGE("no wake lock to update, but system ready!");
949 } else {
950 ALOGW("no wake lock to update, system not ready yet");
951 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800952 return;
953 }
954 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800955 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
956 status_t status = mPowerManager->updateWakeLockUids(
957 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
958 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800959 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800960 }
961}
962
Eric Laurent81784c32012-11-19 14:55:58 -0800963void AudioFlinger::ThreadBase::clearPowerManager()
964{
965 Mutex::Autolock _l(mLock);
966 releaseWakeLock_l();
967 mPowerManager.clear();
968}
969
Glenn Kasten0f11b512014-01-31 16:18:54 -0800970void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800971{
972 sp<ThreadBase> thread = mThread.promote();
973 if (thread != 0) {
974 thread->clearPowerManager();
975 }
976 ALOGW("power manager service died !!!");
977}
978
979void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800980 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800981{
982 Mutex::Autolock _l(mLock);
983 setEffectSuspended_l(type, suspend, sessionId);
984}
985
986void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800987 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800988{
989 sp<EffectChain> chain = getEffectChain_l(sessionId);
990 if (chain != 0) {
991 if (type != NULL) {
992 chain->setEffectSuspended_l(type, suspend);
993 } else {
994 chain->setEffectSuspendedAll_l(suspend);
995 }
996 }
997
998 updateSuspendedSessions_l(type, suspend, sessionId);
999}
1000
1001void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1002{
1003 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1004 if (index < 0) {
1005 return;
1006 }
1007
1008 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1009 mSuspendedSessions.valueAt(index);
1010
1011 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001012 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001013 for (int j = 0; j < desc->mRefCount; j++) {
1014 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1015 chain->setEffectSuspendedAll_l(true);
1016 } else {
1017 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1018 desc->mType.timeLow);
1019 chain->setEffectSuspended_l(&desc->mType, true);
1020 }
1021 }
1022 }
1023}
1024
1025void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1026 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001027 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001028{
1029 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1030
1031 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1032
1033 if (suspend) {
1034 if (index >= 0) {
1035 sessionEffects = mSuspendedSessions.valueAt(index);
1036 } else {
1037 mSuspendedSessions.add(sessionId, sessionEffects);
1038 }
1039 } else {
1040 if (index < 0) {
1041 return;
1042 }
1043 sessionEffects = mSuspendedSessions.valueAt(index);
1044 }
1045
1046
1047 int key = EffectChain::kKeyForSuspendAll;
1048 if (type != NULL) {
1049 key = type->timeLow;
1050 }
1051 index = sessionEffects.indexOfKey(key);
1052
1053 sp<SuspendedSessionDesc> desc;
1054 if (suspend) {
1055 if (index >= 0) {
1056 desc = sessionEffects.valueAt(index);
1057 } else {
1058 desc = new SuspendedSessionDesc();
1059 if (type != NULL) {
1060 desc->mType = *type;
1061 }
1062 sessionEffects.add(key, desc);
1063 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1064 }
1065 desc->mRefCount++;
1066 } else {
1067 if (index < 0) {
1068 return;
1069 }
1070 desc = sessionEffects.valueAt(index);
1071 if (--desc->mRefCount == 0) {
1072 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1073 sessionEffects.removeItemsAt(index);
1074 if (sessionEffects.isEmpty()) {
1075 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1076 sessionId);
1077 mSuspendedSessions.removeItem(sessionId);
1078 }
1079 }
1080 }
1081 if (!sessionEffects.isEmpty()) {
1082 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1083 }
1084}
1085
1086void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1087 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001088 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001089{
1090 Mutex::Autolock _l(mLock);
1091 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1092}
1093
1094void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1095 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001096 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001097{
1098 if (mType != RECORD) {
1099 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1100 // another session. This gives the priority to well behaved effect control panels
1101 // and applications not using global effects.
1102 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1103 // global effects
1104 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1105 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1106 }
1107 }
1108
1109 sp<EffectChain> chain = getEffectChain_l(sessionId);
1110 if (chain != 0) {
1111 chain->checkSuspendOnEffectEnabled(effect, enabled);
1112 }
1113}
1114
Eric Laurent4c415062016-06-17 16:14:16 -07001115// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1116status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1117 const effect_descriptor_t *desc, audio_session_t sessionId)
1118{
1119 // No global effect sessions on record threads
1120 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1121 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1122 desc->name, mThreadName);
1123 return BAD_VALUE;
1124 }
1125 // only pre processing effects on record thread
1126 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1127 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1128 desc->name, mThreadName);
1129 return BAD_VALUE;
1130 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001131
1132 // always allow effects without processing load or latency
1133 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1134 return NO_ERROR;
1135 }
1136
Eric Laurent4c415062016-06-17 16:14:16 -07001137 audio_input_flags_t flags = mInput->flags;
1138 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1139 if (flags & AUDIO_INPUT_FLAG_RAW) {
1140 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1141 desc->name, mThreadName);
1142 return BAD_VALUE;
1143 }
1144 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1145 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1146 desc->name, mThreadName);
1147 return BAD_VALUE;
1148 }
1149 }
1150 return NO_ERROR;
1151}
1152
1153// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1154status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1155 const effect_descriptor_t *desc, audio_session_t sessionId)
1156{
1157 // no preprocessing on playback threads
1158 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1159 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1160 " thread %s", desc->name, mThreadName);
1161 return BAD_VALUE;
1162 }
1163
1164 switch (mType) {
1165 case MIXER: {
1166 // Reject any effect on mixer multichannel sinks.
1167 // TODO: fix both format and multichannel issues with effects.
1168 if (mChannelCount != FCC_2) {
1169 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1170 " thread %s", desc->name, mChannelCount, mThreadName);
1171 return BAD_VALUE;
1172 }
1173 audio_output_flags_t flags = mOutput->flags;
1174 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1175 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1176 // global effects are applied only to non fast tracks if they are SW
1177 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1178 break;
1179 }
1180 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1181 // only post processing on output stage session
1182 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1183 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1184 " on output stage session", desc->name);
1185 return BAD_VALUE;
1186 }
1187 } else {
1188 // no restriction on effects applied on non fast tracks
1189 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1190 break;
1191 }
1192 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001193
1194 // always allow effects without processing load or latency
1195 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1196 break;
1197 }
Eric Laurent4c415062016-06-17 16:14:16 -07001198 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1199 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1200 desc->name);
1201 return BAD_VALUE;
1202 }
1203 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1204 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1205 " in fast mode", desc->name);
1206 return BAD_VALUE;
1207 }
1208 }
1209 } break;
1210 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001211 // nothing actionable on offload threads, if the effect:
1212 // - is offloadable: the effect can be created
1213 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1214 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001215 break;
1216 case DIRECT:
1217 // Reject any effect on Direct output threads for now, since the format of
1218 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1219 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1220 desc->name, mThreadName);
1221 return BAD_VALUE;
1222 case DUPLICATING:
1223 // Reject any effect on mixer multichannel sinks.
1224 // TODO: fix both format and multichannel issues with effects.
1225 if (mChannelCount != FCC_2) {
1226 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1227 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1228 return BAD_VALUE;
1229 }
1230 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1231 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1232 " thread %s", desc->name, mThreadName);
1233 return BAD_VALUE;
1234 }
1235 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1236 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1237 " DUPLICATING thread %s", desc->name, mThreadName);
1238 return BAD_VALUE;
1239 }
1240 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1241 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1242 " DUPLICATING thread %s", desc->name, mThreadName);
1243 return BAD_VALUE;
1244 }
1245 break;
1246 default:
1247 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1248 }
1249
1250 return NO_ERROR;
1251}
1252
Eric Laurent81784c32012-11-19 14:55:58 -08001253// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1254sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1255 const sp<AudioFlinger::Client>& client,
1256 const sp<IEffectClient>& effectClient,
1257 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001258 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001259 effect_descriptor_t *desc,
1260 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001261 status_t *status,
1262 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001263{
1264 sp<EffectModule> effect;
1265 sp<EffectHandle> handle;
1266 status_t lStatus;
1267 sp<EffectChain> chain;
1268 bool chainCreated = false;
1269 bool effectCreated = false;
1270 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001271 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001272
1273 lStatus = initCheck();
1274 if (lStatus != NO_ERROR) {
1275 ALOGW("createEffect_l() Audio driver not initialized.");
1276 goto Exit;
1277 }
1278
Eric Laurent81784c32012-11-19 14:55:58 -08001279 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1280
1281 { // scope for mLock
1282 Mutex::Autolock _l(mLock);
1283
Eric Laurent4c415062016-06-17 16:14:16 -07001284 lStatus = checkEffectCompatibility_l(desc, sessionId);
1285 if (lStatus != NO_ERROR) {
1286 goto Exit;
1287 }
1288
Eric Laurent81784c32012-11-19 14:55:58 -08001289 // check for existing effect chain with the requested audio session
1290 chain = getEffectChain_l(sessionId);
1291 if (chain == 0) {
1292 // create a new chain for this session
1293 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1294 chain = new EffectChain(this, sessionId);
1295 addEffectChain_l(chain);
1296 chain->setStrategy(getStrategyForSession_l(sessionId));
1297 chainCreated = true;
1298 } else {
1299 effect = chain->getEffectFromDesc_l(desc);
1300 }
1301
1302 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1303
1304 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001305 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001306 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001307 lStatus = AudioSystem::registerEffect(
1308 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001309 if (lStatus != NO_ERROR) {
1310 goto Exit;
1311 }
1312 effectRegistered = true;
1313 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001314 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001315 if (lStatus != NO_ERROR) {
1316 goto Exit;
1317 }
1318 effectCreated = true;
1319
1320 effect->setDevice(mOutDevice);
1321 effect->setDevice(mInDevice);
1322 effect->setMode(mAudioFlinger->getMode());
1323 effect->setAudioSource(mAudioSource);
1324 }
1325 // create effect handle and connect it to effect module
1326 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001327 lStatus = handle->initCheck();
1328 if (lStatus == OK) {
1329 lStatus = effect->addHandle(handle.get());
1330 }
Eric Laurent81784c32012-11-19 14:55:58 -08001331 if (enabled != NULL) {
1332 *enabled = (int)effect->isEnabled();
1333 }
1334 }
1335
1336Exit:
1337 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1338 Mutex::Autolock _l(mLock);
1339 if (effectCreated) {
1340 chain->removeEffect_l(effect);
1341 }
1342 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001343 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001344 }
1345 if (chainCreated) {
1346 removeEffectChain_l(chain);
1347 }
1348 handle.clear();
1349 }
1350
Glenn Kasten9156ef32013-08-06 15:39:08 -07001351 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001352 return handle;
1353}
1354
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001355void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1356 bool unpinIfLast)
1357{
1358 bool remove = false;
1359 sp<EffectModule> effect;
1360 {
1361 Mutex::Autolock _l(mLock);
1362
1363 effect = handle->effect().promote();
1364 if (effect == 0) {
1365 return;
1366 }
1367 // restore suspended effects if the disconnected handle was enabled and the last one.
1368 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1369 if (remove) {
1370 removeEffect_l(effect, true);
1371 }
1372 }
1373 if (remove) {
1374 mAudioFlinger->updateOrphanEffectChains(effect);
1375 AudioSystem::unregisterEffect(effect->id());
1376 if (handle->enabled()) {
1377 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1378 }
1379 }
1380}
1381
Glenn Kastend848eb42016-03-08 13:42:11 -08001382sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1383 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001384{
1385 Mutex::Autolock _l(mLock);
1386 return getEffect_l(sessionId, effectId);
1387}
1388
Glenn Kastend848eb42016-03-08 13:42:11 -08001389sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1390 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001391{
1392 sp<EffectChain> chain = getEffectChain_l(sessionId);
1393 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1394}
1395
1396// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1397// PlaybackThread::mLock held
1398status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1399{
1400 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001401 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001402 sp<EffectChain> chain = getEffectChain_l(sessionId);
1403 bool chainCreated = false;
1404
Eric Laurent5baf2af2013-09-12 17:37:00 -07001405 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1406 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1407 this, effect->desc().name, effect->desc().flags);
1408
Eric Laurent81784c32012-11-19 14:55:58 -08001409 if (chain == 0) {
1410 // create a new chain for this session
1411 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1412 chain = new EffectChain(this, sessionId);
1413 addEffectChain_l(chain);
1414 chain->setStrategy(getStrategyForSession_l(sessionId));
1415 chainCreated = true;
1416 }
1417 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1418
1419 if (chain->getEffectFromId_l(effect->id()) != 0) {
1420 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1421 this, effect->desc().name, chain.get());
1422 return BAD_VALUE;
1423 }
1424
Eric Laurent5baf2af2013-09-12 17:37:00 -07001425 effect->setOffloaded(mType == OFFLOAD, mId);
1426
Eric Laurent81784c32012-11-19 14:55:58 -08001427 status_t status = chain->addEffect_l(effect);
1428 if (status != NO_ERROR) {
1429 if (chainCreated) {
1430 removeEffectChain_l(chain);
1431 }
1432 return status;
1433 }
1434
1435 effect->setDevice(mOutDevice);
1436 effect->setDevice(mInDevice);
1437 effect->setMode(mAudioFlinger->getMode());
1438 effect->setAudioSource(mAudioSource);
1439 return NO_ERROR;
1440}
1441
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001442void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001443
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001444 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001445 effect_descriptor_t desc = effect->desc();
1446 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1447 detachAuxEffect_l(effect->id());
1448 }
1449
1450 sp<EffectChain> chain = effect->chain().promote();
1451 if (chain != 0) {
1452 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001453 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001454 removeEffectChain_l(chain);
1455 }
1456 } else {
1457 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1458 }
1459}
1460
1461void AudioFlinger::ThreadBase::lockEffectChains_l(
1462 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1463{
1464 effectChains = mEffectChains;
1465 for (size_t i = 0; i < mEffectChains.size(); i++) {
1466 mEffectChains[i]->lock();
1467 }
1468}
1469
1470void AudioFlinger::ThreadBase::unlockEffectChains(
1471 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1472{
1473 for (size_t i = 0; i < effectChains.size(); i++) {
1474 effectChains[i]->unlock();
1475 }
1476}
1477
Glenn Kastend848eb42016-03-08 13:42:11 -08001478sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001479{
1480 Mutex::Autolock _l(mLock);
1481 return getEffectChain_l(sessionId);
1482}
1483
Glenn Kastend848eb42016-03-08 13:42:11 -08001484sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1485 const
Eric Laurent81784c32012-11-19 14:55:58 -08001486{
1487 size_t size = mEffectChains.size();
1488 for (size_t i = 0; i < size; i++) {
1489 if (mEffectChains[i]->sessionId() == sessionId) {
1490 return mEffectChains[i];
1491 }
1492 }
1493 return 0;
1494}
1495
1496void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1497{
1498 Mutex::Autolock _l(mLock);
1499 size_t size = mEffectChains.size();
1500 for (size_t i = 0; i < size; i++) {
1501 mEffectChains[i]->setMode_l(mode);
1502 }
1503}
1504
Eric Laurent83b88082014-06-20 18:31:16 -07001505void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1506{
1507 config->type = AUDIO_PORT_TYPE_MIX;
1508 config->ext.mix.handle = mId;
1509 config->sample_rate = mSampleRate;
1510 config->format = mFormat;
1511 config->channel_mask = mChannelMask;
1512 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1513 AUDIO_PORT_CONFIG_FORMAT;
1514}
1515
Eric Laurent72e3f392015-05-20 14:43:50 -07001516void AudioFlinger::ThreadBase::systemReady()
1517{
1518 Mutex::Autolock _l(mLock);
1519 if (mSystemReady) {
1520 return;
1521 }
1522 mSystemReady = true;
1523
1524 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1525 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1526 }
1527 mPendingConfigEvents.clear();
1528}
1529
Andy Hungdae27702016-10-31 14:01:16 -07001530template <typename T>
1531ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1532 ssize_t index = mActiveTracks.indexOf(track);
1533 if (index >= 0) {
1534 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1535 return index;
1536 }
1537 mActiveTracksGeneration++;
1538 mLatestActiveTrack = track;
1539 ++mBatteryCounter[track->uid()].second;
1540 return mActiveTracks.add(track);
1541}
1542
1543template <typename T>
1544ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1545 ssize_t index = mActiveTracks.remove(track);
1546 if (index < 0) {
1547 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1548 return index;
1549 }
1550 mActiveTracksGeneration++;
1551 --mBatteryCounter[track->uid()].second;
1552 // mLatestActiveTrack is not cleared even if is the same as track.
1553 return index;
1554}
1555
1556template <typename T>
1557void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1558 for (const sp<T> &track : mActiveTracks) {
1559 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1560 }
1561 mLastActiveTracksGeneration = mActiveTracksGeneration;
1562 mActiveTracks.clear();
1563 mLatestActiveTrack.clear();
1564 mBatteryCounter.clear();
1565}
1566
1567template <typename T>
1568void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1569 sp<ThreadBase> thread, bool force) {
1570 // Updates ActiveTracks client uids to the thread wakelock.
1571 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1572 thread->updateWakeLockUids_l(getWakeLockUids());
1573 mLastActiveTracksGeneration = mActiveTracksGeneration;
1574 }
1575
1576 // Updates BatteryNotifier uids
1577 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1578 const uid_t uid = it->first;
1579 ssize_t &previous = it->second.first;
1580 ssize_t &current = it->second.second;
1581 if (current > 0) {
1582 if (previous == 0) {
1583 BatteryNotifier::getInstance().noteStartAudio(uid);
1584 }
1585 previous = current;
1586 ++it;
1587 } else if (current == 0) {
1588 if (previous > 0) {
1589 BatteryNotifier::getInstance().noteStopAudio(uid);
1590 }
1591 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1592 } else /* (current < 0) */ {
1593 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1594 }
1595 }
1596}
Eric Laurent83b88082014-06-20 18:31:16 -07001597
Eric Laurent81784c32012-11-19 14:55:58 -08001598// ----------------------------------------------------------------------------
1599// Playback
1600// ----------------------------------------------------------------------------
1601
1602AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1603 AudioStreamOut* output,
1604 audio_io_handle_t id,
1605 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001606 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001607 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001608 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001609 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001610 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001611 mMixerBuffer(NULL),
1612 mMixerBufferSize(0),
1613 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1614 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001615 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001616 mEffectBuffer(NULL),
1617 mEffectBufferSize(0),
1618 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1619 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001620 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001621 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001622 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001623 // mStreamTypes[] initialized in constructor body
1624 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001625 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001626 mMixerStatus(MIXER_IDLE),
1627 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001628 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001629 mBytesRemaining(0),
1630 mCurrentWriteLength(0),
1631 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001632 mWriteAckSequence(0),
1633 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001634 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001635 mScreenState(AudioFlinger::mScreenState),
1636 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001637 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001638 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001639{
Glenn Kastend7dca052015-03-05 16:05:54 -08001640 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1641 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001642
1643 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1644 // it would be safer to explicitly pass initial masterVolume/masterMute as
1645 // parameter.
1646 //
1647 // If the HAL we are using has support for master volume or master mute,
1648 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1649 // and the mute set to false).
1650 mMasterVolume = audioFlinger->masterVolume_l();
1651 mMasterMute = audioFlinger->masterMute_l();
1652 if (mOutput && mOutput->audioHwDev) {
1653 if (mOutput->audioHwDev->canSetMasterVolume()) {
1654 mMasterVolume = 1.0;
1655 }
1656
1657 if (mOutput->audioHwDev->canSetMasterMute()) {
1658 mMasterMute = false;
1659 }
1660 }
1661
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001662 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001663
Eric Laurent223fd5c2014-11-11 13:43:36 -08001664 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001665 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001666 stream = (audio_stream_type_t) (stream + 1)) {
1667 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1668 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1669 }
Eric Laurent81784c32012-11-19 14:55:58 -08001670}
1671
1672AudioFlinger::PlaybackThread::~PlaybackThread()
1673{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001674 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001675 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001676 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001677 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001678}
1679
1680void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1681{
1682 dumpInternals(fd, args);
1683 dumpTracks(fd, args);
1684 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001685 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001686}
1687
Glenn Kasten0f11b512014-01-31 16:18:54 -08001688void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001689{
1690 const size_t SIZE = 256;
1691 char buffer[SIZE];
1692 String8 result;
1693
Marco Nelissenb2208842014-02-07 14:00:50 -08001694 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001695 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1696 const stream_type_t *st = &mStreamTypes[i];
1697 if (i > 0) {
1698 result.appendFormat(", ");
1699 }
1700 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1701 if (st->mute) {
1702 result.append("M");
1703 }
1704 }
1705 result.append("\n");
1706 write(fd, result.string(), result.length());
1707 result.clear();
1708
Eric Laurent81784c32012-11-19 14:55:58 -08001709 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1710 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001711 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001712 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001713
1714 size_t numtracks = mTracks.size();
1715 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001716 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001717 size_t numactiveseen = 0;
1718 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001719 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001720 Track::appendDumpHeader(result);
1721 for (size_t i = 0; i < numtracks; ++i) {
1722 sp<Track> track = mTracks[i];
1723 if (track != 0) {
1724 bool active = mActiveTracks.indexOf(track) >= 0;
1725 if (active) {
1726 numactiveseen++;
1727 }
1728 track->dump(buffer, SIZE, active);
1729 result.append(buffer);
1730 }
1731 }
1732 } else {
1733 result.append("\n");
1734 }
1735 if (numactiveseen != numactive) {
1736 // some tracks in the active list were not in the tracks list
1737 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1738 " not in the track list\n");
1739 result.append(buffer);
1740 Track::appendDumpHeader(result);
1741 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001742 sp<Track> track = mActiveTracks[i];
1743 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001744 track->dump(buffer, SIZE, true);
1745 result.append(buffer);
1746 }
1747 }
1748 }
1749
1750 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001751}
1752
1753void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1754{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001755 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001756
1757 dumpBase(fd, args);
1758
Elliott Hughes87cebad2014-05-22 10:14:43 -07001759 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001760 dprintf(fd, " Last write occurred (msecs): %llu\n",
1761 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001762 dprintf(fd, " Total writes: %d\n", mNumWrites);
1763 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1764 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1765 dprintf(fd, " Suspend count: %d\n", mSuspended);
1766 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1767 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1768 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1769 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001770 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001771 AudioStreamOut *output = mOutput;
1772 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001773 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1774 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001775 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1776 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1777 if (mPipeSink.get() != nullptr) {
1778 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1779 }
1780 if (output != nullptr) {
1781 dprintf(fd, " Hal stream dump:\n");
1782 (void)output->stream->dump(fd);
1783 }
Eric Laurent81784c32012-11-19 14:55:58 -08001784}
1785
1786// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001787
1788void AudioFlinger::PlaybackThread::onFirstRef()
1789{
Glenn Kastend7dca052015-03-05 16:05:54 -08001790 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001791}
1792
1793// ThreadBase virtuals
1794void AudioFlinger::PlaybackThread::preExit()
1795{
1796 ALOGV(" preExit()");
1797 // FIXME this is using hard-coded strings but in the future, this functionality will be
1798 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001799 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1800 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001801}
1802
1803// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1804sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1805 const sp<AudioFlinger::Client>& client,
1806 audio_stream_type_t streamType,
1807 uint32_t sampleRate,
1808 audio_format_t format,
1809 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001810 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001811 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001812 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001813 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001814 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001815 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001816 status_t *status,
1817 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001818{
Glenn Kasten74935e42013-12-19 08:56:45 -08001819 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001820 sp<Track> track;
1821 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001822 audio_output_flags_t outputFlags = mOutput->flags;
1823
1824 // special case for FAST flag considered OK if fast mixer is present
1825 if (hasFastMixer()) {
1826 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1827 }
1828
1829 // Check if requested flags are compatible with output stream flags
1830 if ((*flags & outputFlags) != *flags) {
1831 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1832 *flags, outputFlags);
1833 *flags = (audio_output_flags_t)(*flags & outputFlags);
1834 }
Eric Laurent81784c32012-11-19 14:55:58 -08001835
Eric Laurent81784c32012-11-19 14:55:58 -08001836 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001837 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001838 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001839 // PCM data
1840 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001841 // TODO: extract as a data library function that checks that a computationally
1842 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001843 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001844 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1845 (channelMask == AUDIO_CHANNEL_OUT_MONO
1846 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001847 // hardware sample rate
1848 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001849 // normal mixer has an associated fast mixer
1850 hasFastMixer() &&
1851 // there are sufficient fast track slots available
1852 (mFastTrackAvailMask != 0)
1853 // FIXME test that MixerThread for this fast track has a capable output HAL
1854 // FIXME add a permission test also?
1855 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001856 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1857 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001858 // read the fast track multiplier property the first time it is needed
1859 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1860 if (ok != 0) {
1861 ALOGE("%s pthread_once failed: %d", __func__, ok);
1862 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001863 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001864 }
Eric Laurent4c415062016-06-17 16:14:16 -07001865
1866 // check compatibility with audio effects.
1867 { // scope for mLock
1868 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001869 for (audio_session_t session : {
1870 AUDIO_SESSION_OUTPUT_STAGE,
1871 AUDIO_SESSION_OUTPUT_MIX,
1872 sessionId,
1873 }) {
1874 sp<EffectChain> chain = getEffectChain_l(session);
1875 if (chain.get() != nullptr) {
1876 audio_output_flags_t old = *flags;
1877 chain->checkOutputFlagCompatibility(flags);
1878 if (old != *flags) {
1879 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1880 (int)session, (int)old, (int)*flags);
1881 }
Eric Laurent4c415062016-06-17 16:14:16 -07001882 }
1883 }
1884 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001885 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001886 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1887 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001888 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001889 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1890 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001891 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001892 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001893 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001894 audio_is_linear_pcm(format),
1895 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001896 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001897 }
1898 }
1899 // For normal PCM streaming tracks, update minimum frame count.
1900 // For compatibility with AudioTrack calculation, buffer depth is forced
1901 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1902 // This is probably too conservative, but legacy application code may depend on it.
1903 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001904 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001905 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001906 // this must match AudioTrack.cpp calculateMinFrameCount().
1907 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001908 uint32_t latencyMs = 0;
1909 lStatus = mOutput->stream->getLatency(&latencyMs);
1910 if (lStatus != OK) {
1911 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1912 goto Exit;
1913 }
Eric Laurent81784c32012-11-19 14:55:58 -08001914 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1915 if (minBufCount < 2) {
1916 minBufCount = 2;
1917 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001918 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1919 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001920 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001921 minBufCount * sourceFramesNeededWithTimestretch(
1922 sampleRate, mNormalFrameCount,
1923 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001924 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001925 frameCount = minFrameCount;
1926 }
Eric Laurent81784c32012-11-19 14:55:58 -08001927 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001928 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001929
Glenn Kastenc3df8382014-03-13 15:05:25 -07001930 switch (mType) {
1931
1932 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001933 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001934 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001935 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1936 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001937 sampleRate, format, channelMask, mOutput, mFormat);
1938 lStatus = BAD_VALUE;
1939 goto Exit;
1940 }
1941 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001942 break;
1943
1944 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001945 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001946 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1947 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001948 sampleRate, format, channelMask, mOutput, mFormat);
1949 lStatus = BAD_VALUE;
1950 goto Exit;
1951 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001952 break;
1953
1954 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001955 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001956 ALOGE("createTrack_l() Bad parameter: format %#x \""
1957 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958 format, mOutput, mFormat);
1959 lStatus = BAD_VALUE;
1960 goto Exit;
1961 }
Andy Hungcd044842014-08-07 11:04:34 -07001962 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001963 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1964 lStatus = BAD_VALUE;
1965 goto Exit;
1966 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001967 break;
1968
Eric Laurent81784c32012-11-19 14:55:58 -08001969 }
1970
1971 lStatus = initCheck();
1972 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001973 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001974 goto Exit;
1975 }
1976
1977 { // scope for mLock
1978 Mutex::Autolock _l(mLock);
1979
1980 // all tracks in same audio session must share the same routing strategy otherwise
1981 // conflicts will happen when tracks are moved from one output to another by audio policy
1982 // manager
1983 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1984 for (size_t i = 0; i < mTracks.size(); ++i) {
1985 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001986 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001987 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1988 if (sessionId == t->sessionId() && strategy != actual) {
1989 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1990 strategy, actual);
1991 lStatus = BAD_VALUE;
1992 goto Exit;
1993 }
1994 }
1995 }
1996
Glenn Kastend79072e2016-01-06 08:41:20 -08001997 track = new Track(this, client, streamType, sampleRate, format,
1998 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001999 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002000
Glenn Kasten03003332013-08-06 15:40:54 -07002001 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2002 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002003 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002004 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002005 goto Exit;
2006 }
2007 mTracks.add(track);
2008
2009 sp<EffectChain> chain = getEffectChain_l(sessionId);
2010 if (chain != 0) {
2011 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2012 track->setMainBuffer(chain->inBuffer());
2013 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2014 chain->incTrackCnt();
2015 }
2016
Eric Laurent05067782016-06-01 18:27:28 -07002017 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002018 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2019 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2020 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08002021 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*isForApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002022 }
2023 }
2024
2025 lStatus = NO_ERROR;
2026
2027Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002028 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002029 return track;
2030}
2031
2032uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2033{
2034 return latency;
2035}
2036
2037uint32_t AudioFlinger::PlaybackThread::latency() const
2038{
2039 Mutex::Autolock _l(mLock);
2040 return latency_l();
2041}
2042uint32_t AudioFlinger::PlaybackThread::latency_l() const
2043{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002044 uint32_t latency;
2045 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2046 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002047 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002048 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002049}
2050
2051void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2052{
2053 Mutex::Autolock _l(mLock);
2054 // Don't apply master volume in SW if our HAL can do it for us.
2055 if (mOutput && mOutput->audioHwDev &&
2056 mOutput->audioHwDev->canSetMasterVolume()) {
2057 mMasterVolume = 1.0;
2058 } else {
2059 mMasterVolume = value;
2060 }
2061}
2062
2063void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2064{
2065 Mutex::Autolock _l(mLock);
2066 // Don't apply master mute in SW if our HAL can do it for us.
2067 if (mOutput && mOutput->audioHwDev &&
2068 mOutput->audioHwDev->canSetMasterMute()) {
2069 mMasterMute = false;
2070 } else {
2071 mMasterMute = muted;
2072 }
2073}
2074
2075void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2076{
2077 Mutex::Autolock _l(mLock);
2078 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002079 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002080}
2081
2082void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2083{
2084 Mutex::Autolock _l(mLock);
2085 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002086 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002087}
2088
2089float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2090{
2091 Mutex::Autolock _l(mLock);
2092 return mStreamTypes[stream].volume;
2093}
2094
2095// addTrack_l() must be called with ThreadBase::mLock held
2096status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2097{
2098 status_t status = ALREADY_EXISTS;
2099
Eric Laurent81784c32012-11-19 14:55:58 -08002100 if (mActiveTracks.indexOf(track) < 0) {
2101 // the track is newly added, make sure it fills up all its
2102 // buffers before playing. This is to ensure the client will
2103 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002104 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002105 TrackBase::track_state state = track->mState;
2106 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002107 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002108 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002109 mLock.lock();
2110 // abort track was stopped/paused while we released the lock
2111 if (state != track->mState) {
2112 if (status == NO_ERROR) {
2113 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002114 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002115 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002116 mLock.lock();
2117 }
2118 return INVALID_OPERATION;
2119 }
2120 // abort if start is rejected by audio policy manager
2121 if (status != NO_ERROR) {
2122 return PERMISSION_DENIED;
2123 }
2124#ifdef ADD_BATTERY_DATA
2125 // to track the speaker usage
2126 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2127#endif
2128 }
2129
Eric Laurent51716182016-02-29 18:00:56 -08002130 // set retry count for buffer fill
2131 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002132 if (track->isStopping_1()) {
2133 track->mRetryCount = kMaxTrackStopRetriesOffload;
2134 } else {
2135 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2136 }
2137 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002138 } else {
2139 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002140 track->mFillingUpStatus =
2141 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002142 }
2143
Eric Laurent81784c32012-11-19 14:55:58 -08002144 track->mResetDone = false;
2145 track->mPresentationCompleteFrames = 0;
2146 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002147 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2148 if (chain != 0) {
2149 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2150 track->sessionId());
2151 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002152 }
2153
Andy Hung2148bf02016-11-28 19:01:02 -08002154 char buffer[256];
2155 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2156 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2157
Eric Laurent81784c32012-11-19 14:55:58 -08002158 status = NO_ERROR;
2159 }
2160
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002161 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002162 return status;
2163}
2164
Eric Laurentbfb1b832013-01-07 09:53:42 -08002165bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002166{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002167 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002168 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2170 track->mState = TrackBase::STOPPED;
2171 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002172 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002173 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002174 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002175 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002176
2177 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002178}
2179
2180void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2181{
2182 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002183
2184 char buffer[256];
2185 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2186 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2187
Eric Laurent81784c32012-11-19 14:55:58 -08002188 mTracks.remove(track);
2189 deleteTrackName_l(track->name());
2190 // redundant as track is about to be destroyed, for dumpsys only
2191 track->mName = -1;
2192 if (track->isFastTrack()) {
2193 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002194 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002195 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2196 mFastTrackAvailMask |= 1 << index;
2197 // redundant as track is about to be destroyed, for dumpsys only
2198 track->mFastIndex = -1;
2199 }
2200 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2201 if (chain != 0) {
2202 chain->decTrackCnt();
2203 }
2204}
2205
Eric Laurentede6c3b2013-09-19 14:37:46 -07002206void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002207{
2208 // Thread could be blocked waiting for async
2209 // so signal it to handle state changes immediately
2210 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2211 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2212 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002213 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002214}
2215
Eric Laurent81784c32012-11-19 14:55:58 -08002216String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2217{
Eric Laurent81784c32012-11-19 14:55:58 -08002218 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002219 String8 out_s8;
2220 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2221 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002222 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002223 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002224}
2225
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002226void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002227 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2228 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002229
Eric Laurent73e26b62015-04-27 16:55:58 -07002230 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002231
2232 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002233 case AUDIO_OUTPUT_OPENED:
2234 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002235 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002236 desc->mChannelMask = mChannelMask;
2237 desc->mSamplingRate = mSampleRate;
2238 desc->mFormat = mFormat;
2239 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002240 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002241 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002242 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002243 break;
2244
Eric Laurent73e26b62015-04-27 16:55:58 -07002245 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002246 default:
2247 break;
2248 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002249 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002250}
2251
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002252void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002253{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002254 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002255}
2256
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002257void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002258{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002259 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002260}
2261
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002262void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002263{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002264 mCallbackThread->setAsyncError();
2265}
2266
Eric Laurent3b4529e2013-09-05 18:09:19 -07002267void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002268{
2269 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002270 // reject out of sequence requests
2271 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2272 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273 mWaitWorkCV.signal();
2274 }
2275}
2276
Eric Laurent3b4529e2013-09-05 18:09:19 -07002277void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278{
2279 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002280 // reject out of sequence requests
2281 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2282 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002283 mWaitWorkCV.signal();
2284 }
2285}
2286
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002287void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002288{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002289 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002290 mSampleRate = mOutput->getSampleRate();
2291 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002292 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002293 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002294 }
Andy Hung9a592762014-07-21 21:56:01 -07002295 if ((mType == MIXER || mType == DUPLICATING)
2296 && !isValidPcmSinkChannelMask(mChannelMask)) {
2297 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2298 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002299 }
Andy Hunge5412692014-05-16 11:25:07 -07002300 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002301
2302 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002303 status_t result = mOutput->stream->getFormat(&mHALFormat);
2304 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002305 // Get format from the shim, which will be different than the HAL format
2306 // if playing compressed audio over HDMI passthrough.
2307 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002308 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002309 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002310 }
Andy Hung6146c082014-03-18 11:56:15 -07002311 if ((mType == MIXER || mType == DUPLICATING)
2312 && !isValidPcmSinkFormat(mFormat)) {
2313 LOG_FATAL("HAL format %#x not supported for mixed output",
2314 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002315 }
Phil Burk062e67a2015-02-11 13:40:50 -08002316 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002317 result = mOutput->stream->getBufferSize(&mBufferSize);
2318 LOG_ALWAYS_FATAL_IF(result != OK,
2319 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002320 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002321 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002322 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002323 mFrameCount);
2324 }
2325
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002326 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2327 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002328 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002329 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330 }
2331 }
2332
Eric Laurentd1f69b02014-12-15 14:33:13 -08002333 mHwSupportsPause = false;
2334 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002335 bool supportsPause = false, supportsResume = false;
2336 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2337 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002338 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002339 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002340 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002341 } else if (supportsResume) {
2342 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002343 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002344 }
2345 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002346 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2347 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2348 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002349
Andy Hungfbfc3952015-01-15 13:33:51 -08002350 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2351 // For best precision, we use float instead of the associated output
2352 // device format (typically PCM 16 bit).
2353
2354 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2355 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2356 mBufferSize = mFrameSize * mFrameCount;
2357
2358 // TODO: We currently use the associated output device channel mask and sample rate.
2359 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2360 // (if a valid mask) to avoid premature downmix.
2361 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2362 // instead of the output device sample rate to avoid loss of high frequency information.
2363 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2364 }
2365
Andy Hung09a50072014-02-27 14:30:47 -08002366 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002367 double multiplier = 1.0;
2368 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2369 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002370 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2371 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002372
Eric Laurent81784c32012-11-19 14:55:58 -08002373 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2374 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2375 maxNormalFrameCount = maxNormalFrameCount & ~15;
2376 if (maxNormalFrameCount < minNormalFrameCount) {
2377 maxNormalFrameCount = minNormalFrameCount;
2378 }
2379 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2380 if (multiplier <= 1.0) {
2381 multiplier = 1.0;
2382 } else if (multiplier <= 2.0) {
2383 if (2 * mFrameCount <= maxNormalFrameCount) {
2384 multiplier = 2.0;
2385 } else {
2386 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2387 }
2388 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002389 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002390 }
2391 }
2392 mNormalFrameCount = multiplier * mFrameCount;
2393 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002394 if (mType == MIXER || mType == DUPLICATING) {
2395 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2396 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002397 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002398 mNormalFrameCount);
2399
Andy Hung08fb1742015-05-31 23:22:10 -07002400 // Check if we want to throttle the processing to no more than 2x normal rate
2401 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002402 mThreadThrottleTimeMs = 0;
2403 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002404 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2405
Andy Hung010a1a12014-03-13 13:57:33 -07002406 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2407 // Originally this was int16_t[] array, need to remove legacy implications.
2408 free(mSinkBuffer);
2409 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002410 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2411 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2412 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002413 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002414
Andy Hung69aed5f2014-02-25 17:24:40 -08002415 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2416 // drives the output.
2417 free(mMixerBuffer);
2418 mMixerBuffer = NULL;
2419 if (mMixerBufferEnabled) {
2420 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2421 mMixerBufferSize = mNormalFrameCount * mChannelCount
2422 * audio_bytes_per_sample(mMixerBufferFormat);
2423 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2424 }
Andy Hung98ef9782014-03-04 14:46:50 -08002425 free(mEffectBuffer);
2426 mEffectBuffer = NULL;
2427 if (mEffectBufferEnabled) {
2428 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2429 mEffectBufferSize = mNormalFrameCount * mChannelCount
2430 * audio_bytes_per_sample(mEffectBufferFormat);
2431 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2432 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002433
Eric Laurent81784c32012-11-19 14:55:58 -08002434 // force reconfiguration of effect chains and engines to take new buffer size and audio
2435 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002436 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002437 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2438 // matter.
2439 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2440 Vector< sp<EffectChain> > effectChains = mEffectChains;
2441 for (size_t i = 0; i < effectChains.size(); i ++) {
2442 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2443 }
2444}
2445
2446
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002447status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002448{
2449 if (halFrames == NULL || dspFrames == NULL) {
2450 return BAD_VALUE;
2451 }
2452 Mutex::Autolock _l(mLock);
2453 if (initCheck() != NO_ERROR) {
2454 return INVALID_OPERATION;
2455 }
Andy Hung818e7a32016-02-16 18:08:07 -08002456 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002457 *halFrames = framesWritten;
2458
2459 if (isSuspended()) {
2460 // return an estimation of rendered frames when the output is suspended
2461 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002462 *dspFrames = (uint32_t)
2463 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002464 return NO_ERROR;
2465 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002466 status_t status;
2467 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002468 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002469 *dspFrames = (size_t)frames;
2470 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002471 }
2472}
2473
Eric Laurent4c415062016-06-17 16:14:16 -07002474// hasAudioSession_l() must be called with ThreadBase::mLock held
2475uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002476{
Eric Laurent81784c32012-11-19 14:55:58 -08002477 uint32_t result = 0;
2478 if (getEffectChain_l(sessionId) != 0) {
2479 result = EFFECT_SESSION;
2480 }
2481
2482 for (size_t i = 0; i < mTracks.size(); ++i) {
2483 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002484 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002485 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002486 if (track->isFastTrack()) {
2487 result |= FAST_SESSION;
2488 }
Eric Laurent81784c32012-11-19 14:55:58 -08002489 break;
2490 }
2491 }
2492
2493 return result;
2494}
2495
Glenn Kastend848eb42016-03-08 13:42:11 -08002496uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002497{
2498 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2499 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2500 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2501 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2502 }
2503 for (size_t i = 0; i < mTracks.size(); i++) {
2504 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002505 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002506 return AudioSystem::getStrategyForStream(track->streamType());
2507 }
2508 }
2509 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2510}
2511
2512
Phil Burk062e67a2015-02-11 13:40:50 -08002513AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002514{
2515 Mutex::Autolock _l(mLock);
2516 return mOutput;
2517}
2518
Phil Burk062e67a2015-02-11 13:40:50 -08002519AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002520{
2521 Mutex::Autolock _l(mLock);
2522 AudioStreamOut *output = mOutput;
2523 mOutput = NULL;
2524 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2525 // must push a NULL and wait for ack
2526 mOutputSink.clear();
2527 mPipeSink.clear();
2528 mNormalSink.clear();
2529 return output;
2530}
2531
2532// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002533sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002534{
2535 if (mOutput == NULL) {
2536 return NULL;
2537 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002538 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002539}
2540
2541uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2542{
2543 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2544}
2545
2546status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2547{
2548 if (!isValidSyncEvent(event)) {
2549 return BAD_VALUE;
2550 }
2551
2552 Mutex::Autolock _l(mLock);
2553
2554 for (size_t i = 0; i < mTracks.size(); ++i) {
2555 sp<Track> track = mTracks[i];
2556 if (event->triggerSession() == track->sessionId()) {
2557 (void) track->setSyncEvent(event);
2558 return NO_ERROR;
2559 }
2560 }
2561
2562 return NAME_NOT_FOUND;
2563}
2564
2565bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2566{
2567 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2568}
2569
2570void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2571 const Vector< sp<Track> >& tracksToRemove)
2572{
2573 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002574 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002575 for (size_t i = 0 ; i < count ; i++) {
2576 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002577 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002578 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002579 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002580#ifdef ADD_BATTERY_DATA
2581 // to track the speaker usage
2582 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2583#endif
2584 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002585 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002586 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002587 }
Eric Laurent81784c32012-11-19 14:55:58 -08002588 }
2589 }
2590 }
Eric Laurent81784c32012-11-19 14:55:58 -08002591}
2592
2593void AudioFlinger::PlaybackThread::checkSilentMode_l()
2594{
2595 if (!mMasterMute) {
2596 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002597 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2598 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2599 return;
2600 }
Eric Laurent81784c32012-11-19 14:55:58 -08002601 if (property_get("ro.audio.silent", value, "0") > 0) {
2602 char *endptr;
2603 unsigned long ul = strtoul(value, &endptr, 0);
2604 if (*endptr == '\0' && ul != 0) {
2605 ALOGD("Silence is golden");
2606 // The setprop command will not allow a property to be changed after
2607 // the first time it is set, so we don't have to worry about un-muting.
2608 setMasterMute_l(true);
2609 }
2610 }
2611 }
2612}
2613
2614// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002615ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002616{
Eric Laurent81784c32012-11-19 14:55:58 -08002617 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002618 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002619 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002620
2621 // If an NBAIO sink is present, use it to write the normal mixer's submix
2622 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002623
Andy Hung010a1a12014-03-13 13:57:33 -07002624 const size_t count = mBytesRemaining / mFrameSize;
2625
Simon Wilson2d590962012-11-29 15:18:50 -08002626 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002627 // update the setpoint when AudioFlinger::mScreenState changes
2628 uint32_t screenState = AudioFlinger::mScreenState;
2629 if (screenState != mScreenState) {
2630 mScreenState = screenState;
2631 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2632 if (pipe != NULL) {
2633 pipe->setAvgFrames((mScreenState & 1) ?
2634 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2635 }
2636 }
Andy Hung010a1a12014-03-13 13:57:33 -07002637 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002638 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002639 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002640 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002641 } else {
2642 bytesWritten = framesWritten;
2643 }
2644 // otherwise use the HAL / AudioStreamOut directly
2645 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002647
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002649 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2650 mWriteAckSequence += 2;
2651 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002652 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002653 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002655 // FIXME We should have an implementation of timestamps for direct output threads.
2656 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002657 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002658
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 if (mUseAsyncWrite &&
2660 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2661 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002662 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002663 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002664 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002665 }
Eric Laurent81784c32012-11-19 14:55:58 -08002666 }
2667
Eric Laurent81784c32012-11-19 14:55:58 -08002668 mNumWrites++;
2669 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002670 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 return bytesWritten;
2672}
2673
2674void AudioFlinger::PlaybackThread::threadLoop_drain()
2675{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002676 bool supportsDrain = false;
2677 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002678 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2679 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002680 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2681 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002683 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002684 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002685 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002686 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687 }
2688}
2689
2690void AudioFlinger::PlaybackThread::threadLoop_exit()
2691{
Eric Laurent275e8e92014-11-30 15:14:47 -08002692 {
2693 Mutex::Autolock _l(mLock);
2694 for (size_t i = 0; i < mTracks.size(); i++) {
2695 sp<Track> track = mTracks[i];
2696 track->invalidate();
2697 }
Andy Hungdae27702016-10-31 14:01:16 -07002698 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2699 // After we exit there are no more track changes sent to BatteryNotifier
2700 // because that requires an active threadLoop.
2701 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2702 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002703 }
Eric Laurent81784c32012-11-19 14:55:58 -08002704}
2705
2706/*
2707The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002708 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002709 - mActiveSleepTimeUs from activeSleepTimeUs()
2710 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002711 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2712 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002713 - maxPeriod from frame count and sample rate (MIXER only)
2714
2715The parameters that affect these derived values are:
2716 - frame count
2717 - frame size
2718 - sample rate
2719 - device type: A2DP or not
2720 - device latency
2721 - format: PCM or not
2722 - active sleep time
2723 - idle sleep time
2724*/
2725
2726void AudioFlinger::PlaybackThread::cacheParameters_l()
2727{
Andy Hung25c2dac2014-02-27 14:56:00 -08002728 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002729 mActiveSleepTimeUs = activeSleepTimeUs();
2730 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002731
2732 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2733 // truncating audio when going to standby.
2734 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2735 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2736 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2737 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2738 }
2739 }
Eric Laurent81784c32012-11-19 14:55:58 -08002740}
2741
Eric Laurent13084622016-05-17 10:51:49 -07002742bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002743{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002744 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002745 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002746 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002747 size_t size = mTracks.size();
2748 for (size_t i = 0; i < size; i++) {
2749 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002750 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002751 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002752 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002753 }
2754 }
Eric Laurent13084622016-05-17 10:51:49 -07002755 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002756}
2757
Haynes Mathew George05317d22016-05-03 16:34:26 -07002758void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2759{
2760 Mutex::Autolock _l(mLock);
2761 invalidateTracks_l(streamType);
2762}
2763
Eric Laurent81784c32012-11-19 14:55:58 -08002764status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2765{
Glenn Kastend848eb42016-03-08 13:42:11 -08002766 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002767 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2768 status_t result = EffectBufferHalInterface::mirror(
2769 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2770 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2771 &halInBuffer);
2772 if (result != OK) return result;
2773 halOutBuffer = halInBuffer;
2774 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002775
2776 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002777 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002778 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002779 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002780 if (mType != DIRECT) {
2781 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002782 status_t result = EffectBufferHalInterface::allocate(
2783 numSamples * sizeof(int16_t),
2784 &halInBuffer);
2785 if (result != OK) return result;
2786 buffer = halInBuffer->audioBuffer()->s16;
2787 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2788 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002789 }
2790
2791 // Attach all tracks with same session ID to this chain.
2792 for (size_t i = 0; i < mTracks.size(); ++i) {
2793 sp<Track> track = mTracks[i];
2794 if (session == track->sessionId()) {
2795 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2796 buffer);
2797 track->setMainBuffer(buffer);
2798 chain->incTrackCnt();
2799 }
2800 }
2801
2802 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002803 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002804 if (session == track->sessionId()) {
2805 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2806 chain->incActiveTrackCnt();
2807 }
2808 }
2809 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002810 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002811 chain->setInBuffer(halInBuffer);
2812 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002813 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002814 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002815 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2816 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002817 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002818 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002819 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002820 // Effect chain for other sessions are inserted at beginning of effect
2821 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002822 // sessions is not important.
2823 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2824 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2825 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002826 size_t size = mEffectChains.size();
2827 size_t i = 0;
2828 for (i = 0; i < size; i++) {
2829 if (mEffectChains[i]->sessionId() < session) {
2830 break;
2831 }
2832 }
2833 mEffectChains.insertAt(chain, i);
2834 checkSuspendOnAddEffectChain_l(chain);
2835
2836 return NO_ERROR;
2837}
2838
2839size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2840{
Glenn Kastend848eb42016-03-08 13:42:11 -08002841 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002842
2843 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2844
2845 for (size_t i = 0; i < mEffectChains.size(); i++) {
2846 if (chain == mEffectChains[i]) {
2847 mEffectChains.removeAt(i);
2848 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002849 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002850 if (session == track->sessionId()) {
2851 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2852 chain.get(), session);
2853 chain->decActiveTrackCnt();
2854 }
2855 }
2856
2857 // detach all tracks with same session ID from this chain
2858 for (size_t i = 0; i < mTracks.size(); ++i) {
2859 sp<Track> track = mTracks[i];
2860 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002861 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002862 chain->decTrackCnt();
2863 }
2864 }
2865 break;
2866 }
2867 }
2868 return mEffectChains.size();
2869}
2870
2871status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002872 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002873{
2874 Mutex::Autolock _l(mLock);
2875 return attachAuxEffect_l(track, EffectId);
2876}
2877
2878status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002879 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002880{
2881 status_t status = NO_ERROR;
2882
2883 if (EffectId == 0) {
2884 track->setAuxBuffer(0, NULL);
2885 } else {
2886 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2887 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2888 if (effect != 0) {
2889 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2890 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2891 } else {
2892 status = INVALID_OPERATION;
2893 }
2894 } else {
2895 status = BAD_VALUE;
2896 }
2897 }
2898 return status;
2899}
2900
2901void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2902{
2903 for (size_t i = 0; i < mTracks.size(); ++i) {
2904 sp<Track> track = mTracks[i];
2905 if (track->auxEffectId() == effectId) {
2906 attachAuxEffect_l(track, 0);
2907 }
2908 }
2909}
2910
2911bool AudioFlinger::PlaybackThread::threadLoop()
2912{
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002913 logWriterTLS = mNBLogWriter.get();
2914
Eric Laurent81784c32012-11-19 14:55:58 -08002915 Vector< sp<Track> > tracksToRemove;
2916
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002917 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002918 nsecs_t lastWriteFinished = -1; // time last server write completed
2919 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002920
2921 // MIXER
2922 nsecs_t lastWarning = 0;
2923
2924 // DUPLICATING
2925 // FIXME could this be made local to while loop?
2926 writeFrames = 0;
2927
2928 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002929 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002930
2931 if (mType == MIXER) {
2932 sleepTimeShift = 0;
2933 }
2934
2935 CpuStats cpuStats;
2936 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2937
2938 acquireWakeLock();
2939
Glenn Kasten9e58b552013-01-18 15:09:48 -08002940 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2941 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2942 // and then that string will be logged at the next convenient opportunity.
2943 const char *logString = NULL;
2944
Eric Laurent664539d2013-09-23 18:24:31 -07002945 checkSilentMode_l();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002946#if 0
2947 int z = 0; // used in logFormat example
2948#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002949 while (!exitPending())
2950 {
2951 cpuStats.sample(myName);
2952
2953 Vector< sp<EffectChain> > effectChains;
2954
Eric Laurent81784c32012-11-19 14:55:58 -08002955 { // scope for mLock
2956
2957 Mutex::Autolock _l(mLock);
2958
Eric Laurent021cf962014-05-13 10:18:14 -07002959 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002960
Glenn Kasten9e58b552013-01-18 15:09:48 -08002961 if (logString != NULL) {
2962 mNBLogWriter->logTimestamp();
2963 mNBLogWriter->log(logString);
2964 logString = NULL;
2965 }
2966
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002967 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002968 // and associate with the sink frames written out. We need
2969 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002970 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002971 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002972 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002973 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002974 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002975 ExtendedTimestamp timestamp; // use private copy to fetch
2976 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002977
2978 // We keep track of the last valid kernel position in case we are in underrun
2979 // and the normal mixer period is the same as the fast mixer period, or there
2980 // is some error from the HAL.
2981 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2982 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2983 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2984 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2985 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2986
2987 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2988 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2989 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2990 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002991 }
2992
2993 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2994 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002995 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002996 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002997 }
2998
Andy Hung818e7a32016-02-16 18:08:07 -08002999 // copy over kernel info
3000 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003001 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3002 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003003 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3004 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003005 }
3006 // mFramesWritten for non-offloaded tracks are contiguous
3007 // even after standby() is called. This is useful for the track frame
3008 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003009 bool serverLocationUpdate = false;
3010 if (mFramesWritten != lastFramesWritten) {
3011 serverLocationUpdate = true;
3012 lastFramesWritten = mFramesWritten;
3013 }
3014 // Only update timestamps if there is a meaningful change.
3015 // Either the kernel timestamp must be valid or we have written something.
3016 if (kernelLocationUpdate || serverLocationUpdate) {
3017 if (serverLocationUpdate) {
3018 // use the time before we called the HAL write - it is a bit more accurate
3019 // to when the server last read data than the current time here.
3020 //
3021 // If we haven't written anything, mLastWriteTime will be -1
3022 // and we use systemTime().
3023 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3024 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3025 ? systemTime() : mLastWriteTime;
3026 }
Andy Hungdae27702016-10-31 14:01:16 -07003027
3028 for (const sp<Track> &t : mActiveTracks) {
3029 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003030 t->updateTrackFrameInfo(
3031 t->mAudioTrackServerProxy->framesReleased(),
3032 mFramesWritten,
3033 mTimestamp);
3034 }
Andy Hunge10393e2015-06-12 13:59:33 -07003035 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003036 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003037#if 0
3038 // logFormat example
3039 if (!(z % 100)) {
3040 timespec ts;
3041 clock_gettime(CLOCK_MONOTONIC, &ts);
3042 LOGF("This is an integer %d, this is a float %f, this is my "
3043 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
3044 LOGF("A deceptive null-terminated string %\0");
3045 }
3046 ++z;
3047#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003048 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003049 if (mSignalPending) {
3050 // A signal was raised while we were unlocked
3051 mSignalPending = false;
3052 } else if (waitingAsyncCallback_l()) {
3053 if (exitPending()) {
3054 break;
3055 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003056 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003057 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003058 releaseWakeLock_l();
3059 released = true;
3060 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003061 ALOGV("wait async completion");
3062 mWaitWorkCV.wait(mLock);
3063 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003064 if (released) {
3065 acquireWakeLock_l();
3066 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003067 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3068 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003069
3070 continue;
3071 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003072 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003073 isSuspended()) {
3074 // put audio hardware into standby after short delay
3075 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003076
3077 threadLoop_standby();
3078
3079 mStandby = true;
3080 }
3081
3082 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3083 // we're about to wait, flush the binder command buffer
3084 IPCThreadState::self()->flushCommands();
3085
3086 clearOutputTracks();
3087
3088 if (exitPending()) {
3089 break;
3090 }
3091
3092 releaseWakeLock_l();
3093 // wait until we have something to do...
3094 ALOGV("%s going to sleep", myName.string());
3095 mWaitWorkCV.wait(mLock);
3096 ALOGV("%s waking up", myName.string());
3097 acquireWakeLock_l();
3098
3099 mMixerStatus = MIXER_IDLE;
3100 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3101 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003102 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003103 checkSilentMode_l();
3104
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003105 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3106 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003107 if (mType == MIXER) {
3108 sleepTimeShift = 0;
3109 }
3110
3111 continue;
3112 }
3113 }
Eric Laurent81784c32012-11-19 14:55:58 -08003114 // mMixerStatusIgnoringFastTracks is also updated internally
3115 mMixerStatus = prepareTracks_l(&tracksToRemove);
3116
Andy Hungdae27702016-10-31 14:01:16 -07003117 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003118
Eric Laurent81784c32012-11-19 14:55:58 -08003119 // prevent any changes in effect chain list and in each effect chain
3120 // during mixing and effect process as the audio buffers could be deleted
3121 // or modified if an effect is created or deleted
3122 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003123 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003124
Eric Laurentbfb1b832013-01-07 09:53:42 -08003125 if (mBytesRemaining == 0) {
3126 mCurrentWriteLength = 0;
3127 if (mMixerStatus == MIXER_TRACKS_READY) {
3128 // threadLoop_mix() sets mCurrentWriteLength
3129 threadLoop_mix();
3130 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3131 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003132 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003133 // must be written to HAL
3134 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003135 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003136 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003137 }
3138 }
Andy Hung98ef9782014-03-04 14:46:50 -08003139 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003140 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003141 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3142 // or mSinkBuffer (if there are no effects).
3143 //
3144 // This is done pre-effects computation; if effects change to
3145 // support higher precision, this needs to move.
3146 //
3147 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003148 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003149 if (mMixerBufferValid) {
3150 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3151 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3152
Andy Hung2ddee192015-12-18 17:34:44 -08003153 // mono blend occurs for mixer threads only (not direct or offloaded)
3154 // and is handled here if we're going directly to the sink.
3155 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003156 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3157 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003158 }
3159
Andy Hung98ef9782014-03-04 14:46:50 -08003160 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3161 mNormalFrameCount * mChannelCount);
3162 }
3163
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164 mBytesRemaining = mCurrentWriteLength;
3165 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003166 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3167 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3168 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3169 mBytesWritten += mBytesRemaining;
3170 mFramesWritten += framesRemaining;
3171 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003172 mBytesRemaining = 0;
3173 }
Eric Laurent81784c32012-11-19 14:55:58 -08003174
Eric Laurentbfb1b832013-01-07 09:53:42 -08003175 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003176 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003177 for (size_t i = 0; i < effectChains.size(); i ++) {
3178 effectChains[i]->process_l();
3179 }
Eric Laurent81784c32012-11-19 14:55:58 -08003180 }
3181 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003182 // Process effect chains for offloaded thread even if no audio
3183 // was read from audio track: process only updates effect state
3184 // and thus does have to be synchronized with audio writes but may have
3185 // to be called while waiting for async write callback
3186 if (mType == OFFLOAD) {
3187 for (size_t i = 0; i < effectChains.size(); i ++) {
3188 effectChains[i]->process_l();
3189 }
3190 }
Eric Laurent81784c32012-11-19 14:55:58 -08003191
Andy Hung98ef9782014-03-04 14:46:50 -08003192 // Only if the Effects buffer is enabled and there is data in the
3193 // Effects buffer (buffer valid), we need to
3194 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003195 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003196 if (mEffectBufferValid) {
3197 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003198
3199 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003200 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3201 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003202 }
3203
Andy Hung98ef9782014-03-04 14:46:50 -08003204 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3205 mNormalFrameCount * mChannelCount);
3206 }
3207
Eric Laurent81784c32012-11-19 14:55:58 -08003208 // enable changes in effect chain
3209 unlockEffectChains(effectChains);
3210
Eric Laurentbfb1b832013-01-07 09:53:42 -08003211 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003212 // mSleepTimeUs == 0 means we must write to audio hardware
3213 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003214 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003215 // We save lastWriteFinished here, as previousLastWriteFinished,
3216 // for throttling. On thread start, previousLastWriteFinished will be
3217 // set to -1, which properly results in no throttling after the first write.
3218 nsecs_t previousLastWriteFinished = lastWriteFinished;
3219 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003220 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003221 // FIXME rewrite to reduce number of system calls
3222 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003223 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003224 lastWriteFinished = systemTime();
3225 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003226 if (ret < 0) {
3227 mBytesRemaining = 0;
3228 } else {
3229 mBytesWritten += ret;
3230 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003231 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003232 }
3233 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3234 (mMixerStatus == MIXER_DRAIN_ALL)) {
3235 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003236 }
Andy Hung08fb1742015-05-31 23:22:10 -07003237 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003238 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003239 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003240 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003241 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003242 ATRACE_NAME("underrun");
3243 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003244 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003245 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003246 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003247 }
Andy Hung08fb1742015-05-31 23:22:10 -07003248
3249 if (mThreadThrottle
3250 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3251 && ret > 0) { // we wrote something
3252 // Limit MixerThread data processing to no more than twice the
3253 // expected processing rate.
3254 //
3255 // This helps prevent underruns with NuPlayer and other applications
3256 // which may set up buffers that are close to the minimum size, or use
3257 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3258 //
3259 // The throttle smooths out sudden large data drains from the device,
3260 // e.g. when it comes out of standby, which often causes problems with
3261 // (1) mixer threads without a fast mixer (which has its own warm-up)
3262 // (2) minimum buffer sized tracks (even if the track is full,
3263 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003264 //
3265 // Total time spent in last processing cycle equals time spent in
3266 // 1. threadLoop_write, as well as time spent in
3267 // 2. threadLoop_mix (significant for heavy mixing, especially
3268 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003269
Andy Hung69488c42016-05-16 18:43:33 -07003270 // it's OK if deltaMs is an overestimate.
3271 const int32_t deltaMs =
3272 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003273 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3274 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3275 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003276 // notify of throttle start on verbose log
3277 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3278 "mixer(%p) throttle begin:"
3279 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003280 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003281 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003282 // Throttle must be attributed to the previous mixer loop's write time
3283 // to allow back-to-back throttling.
3284 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003285 } else {
3286 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3287 if (diff > 0) {
3288 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003289 // but prevent spamming for bluetooth
3290 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3291 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003292 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3293 }
Andy Hung08fb1742015-05-31 23:22:10 -07003294 }
3295 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003296 }
Eric Laurent81784c32012-11-19 14:55:58 -08003297
Eric Laurentbfb1b832013-01-07 09:53:42 -08003298 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003299 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003300 Mutex::Autolock _l(mLock);
3301 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3302 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003303 }
Glenn Kastene7754022014-10-31 12:11:26 -07003304 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003305 }
Eric Laurent81784c32012-11-19 14:55:58 -08003306 }
3307
3308 // Finally let go of removed track(s), without the lock held
3309 // since we can't guarantee the destructors won't acquire that
3310 // same lock. This will also mutate and push a new fast mixer state.
3311 threadLoop_removeTracks(tracksToRemove);
3312 tracksToRemove.clear();
3313
3314 // FIXME I don't understand the need for this here;
3315 // it was in the original code but maybe the
3316 // assignment in saveOutputTracks() makes this unnecessary?
3317 clearOutputTracks();
3318
3319 // Effect chains will be actually deleted here if they were removed from
3320 // mEffectChains list during mixing or effects processing
3321 effectChains.clear();
3322
3323 // FIXME Note that the above .clear() is no longer necessary since effectChains
3324 // is now local to this block, but will keep it for now (at least until merge done).
3325 }
3326
Eric Laurentbfb1b832013-01-07 09:53:42 -08003327 threadLoop_exit();
3328
Eric Laurentcf817a22014-08-04 20:36:31 -07003329 if (!mStandby) {
3330 threadLoop_standby();
3331 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003332 }
3333
3334 releaseWakeLock();
3335
3336 ALOGV("Thread %p type %d exiting", this, mType);
3337 return false;
3338}
3339
Eric Laurentbfb1b832013-01-07 09:53:42 -08003340// removeTracks_l() must be called with ThreadBase::mLock held
3341void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3342{
3343 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003344 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003345 for (size_t i=0 ; i<count ; i++) {
3346 const sp<Track>& track = tracksToRemove.itemAt(i);
3347 mActiveTracks.remove(track);
3348 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3349 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3350 if (chain != 0) {
3351 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3352 track->sessionId());
3353 chain->decActiveTrackCnt();
3354 }
3355 if (track->isTerminated()) {
3356 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003357 } else { // inactive but not terminated
3358 char buffer[256];
3359 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3360 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003361 }
3362 }
3363 }
3364
3365}
Eric Laurent81784c32012-11-19 14:55:58 -08003366
Eric Laurentaccc1472013-09-20 09:36:34 -07003367status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3368{
3369 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003370 ExtendedTimestamp ets;
3371 status_t status = mNormalSink->getTimestamp(ets);
3372 if (status == NO_ERROR) {
3373 status = ets.getBestTimestamp(&timestamp);
3374 }
3375 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003376 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003377 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003378 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003379 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003380 timestamp.mPosition = (uint32_t)position64;
3381 return NO_ERROR;
3382 }
3383 }
3384 return INVALID_OPERATION;
3385}
Eric Laurent1c333e22014-05-20 10:48:17 -07003386
Eric Laurent054d9d32015-04-24 08:48:48 -07003387status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3388 audio_patch_handle_t *handle)
3389{
Andy Hungf60abce2016-08-26 11:37:54 -07003390 status_t status;
3391 if (property_get_bool("af.patch_park", false /* default_value */)) {
3392 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3393 // or if HAL does not properly lock against access.
3394 AutoPark<FastMixer> park(mFastMixer);
3395 status = PlaybackThread::createAudioPatch_l(patch, handle);
3396 } else {
3397 status = PlaybackThread::createAudioPatch_l(patch, handle);
3398 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003399 return status;
3400}
3401
Eric Laurent1c333e22014-05-20 10:48:17 -07003402status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3403 audio_patch_handle_t *handle)
3404{
3405 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003406
3407 // store new device and send to effects
3408 audio_devices_t type = AUDIO_DEVICE_NONE;
3409 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3410 type |= patch->sinks[i].ext.device.type;
3411 }
3412
3413#ifdef ADD_BATTERY_DATA
3414 // when changing the audio output device, call addBatteryData to notify
3415 // the change
3416 if (mOutDevice != type) {
3417 uint32_t params = 0;
3418 // check whether speaker is on
3419 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3420 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003421 }
3422
Eric Laurent054d9d32015-04-24 08:48:48 -07003423 audio_devices_t deviceWithoutSpeaker
3424 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3425 // check if any other device (except speaker) is on
3426 if (type & deviceWithoutSpeaker) {
3427 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3428 }
3429
3430 if (params != 0) {
3431 addBatteryData(params);
3432 }
3433 }
3434#endif
3435
3436 for (size_t i = 0; i < mEffectChains.size(); i++) {
3437 mEffectChains[i]->setDevice_l(type);
3438 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003439
3440 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3441 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3442 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003443 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003444 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003445
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003446 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003447 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3448 status = hwDevice->createAudioPatch(patch->num_sources,
3449 patch->sources,
3450 patch->num_sinks,
3451 patch->sinks,
3452 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003453 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003454 char *address;
3455 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3456 //FIXME: we only support address on first sink with HAL version < 3.0
3457 address = audio_device_address_to_parameter(
3458 patch->sinks[0].ext.device.type,
3459 patch->sinks[0].ext.device.address);
3460 } else {
3461 address = (char *)calloc(1, 1);
3462 }
3463 AudioParameter param = AudioParameter(String8(address));
3464 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003465 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003466 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003467 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003468 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003469 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003470 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003471 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3472 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003473 return status;
3474}
3475
Eric Laurent054d9d32015-04-24 08:48:48 -07003476status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3477{
Andy Hungf60abce2016-08-26 11:37:54 -07003478 status_t status;
3479 if (property_get_bool("af.patch_park", false /* default_value */)) {
3480 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3481 // or if HAL does not properly lock against access.
3482 AutoPark<FastMixer> park(mFastMixer);
3483 status = PlaybackThread::releaseAudioPatch_l(handle);
3484 } else {
3485 status = PlaybackThread::releaseAudioPatch_l(handle);
3486 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003487 return status;
3488}
3489
Eric Laurent1c333e22014-05-20 10:48:17 -07003490status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3491{
3492 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003493
3494 mOutDevice = AUDIO_DEVICE_NONE;
3495
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003496 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003497 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3498 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003499 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003500 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003501 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003502 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003503 }
3504 return status;
3505}
3506
Eric Laurent83b88082014-06-20 18:31:16 -07003507void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3508{
3509 Mutex::Autolock _l(mLock);
3510 mTracks.add(track);
3511}
3512
3513void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3514{
3515 Mutex::Autolock _l(mLock);
3516 destroyTrack_l(track);
3517}
3518
3519void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3520{
3521 ThreadBase::getAudioPortConfig(config);
3522 config->role = AUDIO_PORT_ROLE_SOURCE;
3523 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3524 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3525}
3526
Eric Laurent81784c32012-11-19 14:55:58 -08003527// ----------------------------------------------------------------------------
3528
3529AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003530 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3531 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003532 // mAudioMixer below
3533 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003534 mFastMixerFutex(0),
3535 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003536 // mOutputSink below
3537 // mPipeSink below
3538 // mNormalSink below
3539{
3540 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003541 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3542 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003543 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3544 mNormalFrameCount);
3545 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3546
Andy Hungfbfc3952015-01-15 13:33:51 -08003547 if (type == DUPLICATING) {
3548 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3549 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3550 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3551 return;
3552 }
Eric Laurent81784c32012-11-19 14:55:58 -08003553 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003554 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003555 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003556 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003557#if !LOG_NDEBUG
3558 ssize_t index =
3559#else
3560 (void)
3561#endif
3562 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003563 ALOG_ASSERT(index == 0);
3564
3565 // initialize fast mixer depending on configuration
3566 bool initFastMixer;
3567 switch (kUseFastMixer) {
3568 case FastMixer_Never:
3569 initFastMixer = false;
3570 break;
3571 case FastMixer_Always:
3572 initFastMixer = true;
3573 break;
3574 case FastMixer_Static:
3575 case FastMixer_Dynamic:
3576 initFastMixer = mFrameCount < mNormalFrameCount;
3577 break;
3578 }
3579 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003580 audio_format_t fastMixerFormat;
3581 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3582 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3583 } else {
3584 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3585 }
3586 if (mFormat != fastMixerFormat) {
3587 // change our Sink format to accept our intermediate precision
3588 mFormat = fastMixerFormat;
3589 free(mSinkBuffer);
3590 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3591 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3592 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3593 }
Eric Laurent81784c32012-11-19 14:55:58 -08003594
3595 // create a MonoPipe to connect our submix to FastMixer
3596 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003597#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003598 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003599#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003600 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003601 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003602 format.mFormat = fastMixerFormat;
3603 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3604
Eric Laurent81784c32012-11-19 14:55:58 -08003605 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3606 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3607 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3608 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3609 const NBAIO_Format offers[1] = {format};
3610 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003611#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003612 ssize_t index =
3613#else
3614 (void)
3615#endif
3616 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003617 ALOG_ASSERT(index == 0);
3618 monoPipe->setAvgFrames((mScreenState & 1) ?
3619 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3620 mPipeSink = monoPipe;
3621
Glenn Kasten46909e72013-02-26 09:20:22 -08003622#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003623 if (mTeeSinkOutputEnabled) {
3624 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003625 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3626 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003627 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003628 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003629 ALOG_ASSERT(index == 0);
3630 mTeeSink = teeSink;
3631 PipeReader *teeSource = new PipeReader(*teeSink);
3632 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003633 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003634 ALOG_ASSERT(index == 0);
3635 mTeeSource = teeSource;
3636 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003637#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003638
3639 // create fast mixer and configure it initially with just one fast track for our submix
3640 mFastMixer = new FastMixer();
3641 FastMixerStateQueue *sq = mFastMixer->sq();
3642#ifdef STATE_QUEUE_DUMP
3643 sq->setObserverDump(&mStateQueueObserverDump);
3644 sq->setMutatorDump(&mStateQueueMutatorDump);
3645#endif
3646 FastMixerState *state = sq->begin();
3647 FastTrack *fastTrack = &state->mFastTracks[0];
3648 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3649 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3650 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003651 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3652 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003653 fastTrack->mGeneration++;
3654 state->mFastTracksGen++;
3655 state->mTrackMask = 1;
3656 // fast mixer will use the HAL output sink
3657 state->mOutputSink = mOutputSink.get();
3658 state->mOutputSinkGen++;
3659 state->mFrameCount = mFrameCount;
3660 state->mCommand = FastMixerState::COLD_IDLE;
3661 // already done in constructor initialization list
3662 //mFastMixerFutex = 0;
3663 state->mColdFutexAddr = &mFastMixerFutex;
3664 state->mColdGen++;
3665 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003666#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003667 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003668#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003669 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3670 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003671 sq->end();
3672 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3673
3674 // start the fast mixer
3675 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3676 pid_t tid = mFastMixer->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08003677 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003678 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003679
3680#ifdef AUDIO_WATCHDOG
3681 // create and start the watchdog
3682 mAudioWatchdog = new AudioWatchdog();
3683 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3684 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3685 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003686 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003687#endif
3688
Eric Laurent81784c32012-11-19 14:55:58 -08003689 }
3690
3691 switch (kUseFastMixer) {
3692 case FastMixer_Never:
3693 case FastMixer_Dynamic:
3694 mNormalSink = mOutputSink;
3695 break;
3696 case FastMixer_Always:
3697 mNormalSink = mPipeSink;
3698 break;
3699 case FastMixer_Static:
3700 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3701 break;
3702 }
3703}
3704
3705AudioFlinger::MixerThread::~MixerThread()
3706{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003707 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003708 FastMixerStateQueue *sq = mFastMixer->sq();
3709 FastMixerState *state = sq->begin();
3710 if (state->mCommand == FastMixerState::COLD_IDLE) {
3711 int32_t old = android_atomic_inc(&mFastMixerFutex);
3712 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003713 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003714 }
3715 }
3716 state->mCommand = FastMixerState::EXIT;
3717 sq->end();
3718 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3719 mFastMixer->join();
3720 // Though the fast mixer thread has exited, it's state queue is still valid.
3721 // We'll use that extract the final state which contains one remaining fast track
3722 // corresponding to our sub-mix.
3723 state = sq->begin();
3724 ALOG_ASSERT(state->mTrackMask == 1);
3725 FastTrack *fastTrack = &state->mFastTracks[0];
3726 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3727 delete fastTrack->mBufferProvider;
3728 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003729 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003730#ifdef AUDIO_WATCHDOG
3731 if (mAudioWatchdog != 0) {
3732 mAudioWatchdog->requestExit();
3733 mAudioWatchdog->requestExitAndWait();
3734 mAudioWatchdog.clear();
3735 }
3736#endif
3737 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003738 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003739 delete mAudioMixer;
3740}
3741
3742
3743uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3744{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003745 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003746 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3747 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3748 }
3749 return latency;
3750}
3751
3752
3753void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3754{
3755 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3756}
3757
Eric Laurentbfb1b832013-01-07 09:53:42 -08003758ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003759{
3760 // FIXME we should only do one push per cycle; confirm this is true
3761 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003762 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003763 FastMixerStateQueue *sq = mFastMixer->sq();
3764 FastMixerState *state = sq->begin();
3765 if (state->mCommand != FastMixerState::MIX_WRITE &&
3766 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3767 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003768
3769 // FIXME workaround for first HAL write being CPU bound on some devices
3770 ATRACE_BEGIN("write");
3771 mOutput->write((char *)mSinkBuffer, 0);
3772 ATRACE_END();
3773
Eric Laurent81784c32012-11-19 14:55:58 -08003774 int32_t old = android_atomic_inc(&mFastMixerFutex);
3775 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003776 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003777 }
3778#ifdef AUDIO_WATCHDOG
3779 if (mAudioWatchdog != 0) {
3780 mAudioWatchdog->resume();
3781 }
3782#endif
3783 }
3784 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003785#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003786 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003787 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003788#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003789 sq->end();
3790 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3791 if (kUseFastMixer == FastMixer_Dynamic) {
3792 mNormalSink = mPipeSink;
3793 }
3794 } else {
3795 sq->end(false /*didModify*/);
3796 }
3797 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003798 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003799}
3800
3801void AudioFlinger::MixerThread::threadLoop_standby()
3802{
3803 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003804 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003805 FastMixerStateQueue *sq = mFastMixer->sq();
3806 FastMixerState *state = sq->begin();
3807 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003808 // Report any frames trapped in the Monopipe
3809 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3810 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3811 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3812 "monoPipeWritten:%lld monoPipeLeft:%lld",
3813 (long long)mFramesWritten, (long long)mSuspendedFrames,
3814 (long long)mPipeSink->framesWritten(), pipeFrames);
3815 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3816
Eric Laurent81784c32012-11-19 14:55:58 -08003817 state->mCommand = FastMixerState::COLD_IDLE;
3818 state->mColdFutexAddr = &mFastMixerFutex;
3819 state->mColdGen++;
3820 mFastMixerFutex = 0;
3821 sq->end();
3822 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3823 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3824 if (kUseFastMixer == FastMixer_Dynamic) {
3825 mNormalSink = mOutputSink;
3826 }
3827#ifdef AUDIO_WATCHDOG
3828 if (mAudioWatchdog != 0) {
3829 mAudioWatchdog->pause();
3830 }
3831#endif
3832 } else {
3833 sq->end(false /*didModify*/);
3834 }
3835 }
3836 PlaybackThread::threadLoop_standby();
3837}
3838
Eric Laurentbfb1b832013-01-07 09:53:42 -08003839bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3840{
3841 return false;
3842}
3843
3844bool AudioFlinger::PlaybackThread::shouldStandby_l()
3845{
3846 return !mStandby;
3847}
3848
3849bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3850{
3851 Mutex::Autolock _l(mLock);
3852 return waitingAsyncCallback_l();
3853}
3854
Eric Laurent81784c32012-11-19 14:55:58 -08003855// shared by MIXER and DIRECT, overridden by DUPLICATING
3856void AudioFlinger::PlaybackThread::threadLoop_standby()
3857{
3858 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003859 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003860 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003861 // discard any pending drain or write ack by incrementing sequence
3862 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3863 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003864 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003865 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3866 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003867 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003868 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003869}
3870
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003871void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3872{
3873 ALOGV("signal playback thread");
3874 broadcast_l();
3875}
3876
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003877void AudioFlinger::PlaybackThread::onAsyncError()
3878{
3879 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3880 invalidateTracks((audio_stream_type_t)i);
3881 }
3882}
3883
Eric Laurent81784c32012-11-19 14:55:58 -08003884void AudioFlinger::MixerThread::threadLoop_mix()
3885{
Eric Laurent81784c32012-11-19 14:55:58 -08003886 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003887 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003888 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003889 // increase sleep time progressively when application underrun condition clears.
3890 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3891 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3892 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003893 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003894 sleepTimeShift--;
3895 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003896 mSleepTimeUs = 0;
3897 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003898 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003899
Eric Laurent81784c32012-11-19 14:55:58 -08003900}
3901
3902void AudioFlinger::MixerThread::threadLoop_sleepTime()
3903{
3904 // If no tracks are ready, sleep once for the duration of an output
3905 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003906 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003907 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003908 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3909 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3910 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003911 }
3912 // reduce sleep time in case of consecutive application underruns to avoid
3913 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3914 // duration we would end up writing less data than needed by the audio HAL if
3915 // the condition persists.
3916 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3917 sleepTimeShift++;
3918 }
3919 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003920 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003921 }
3922 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003923 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3924 // before effects processing or output.
3925 if (mMixerBufferValid) {
3926 memset(mMixerBuffer, 0, mMixerBufferSize);
3927 } else {
3928 memset(mSinkBuffer, 0, mSinkBufferSize);
3929 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003930 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003931 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3932 "anticipated start");
3933 }
3934 // TODO add standby time extension fct of effect tail
3935}
3936
3937// prepareTracks_l() must be called with ThreadBase::mLock held
3938AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3939 Vector< sp<Track> > *tracksToRemove)
3940{
3941
3942 mixer_state mixerStatus = MIXER_IDLE;
3943 // find out which tracks need to be processed
3944 size_t count = mActiveTracks.size();
3945 size_t mixedTracks = 0;
3946 size_t tracksWithEffect = 0;
3947 // counts only _active_ fast tracks
3948 size_t fastTracks = 0;
3949 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3950
3951 float masterVolume = mMasterVolume;
3952 bool masterMute = mMasterMute;
3953
3954 if (masterMute) {
3955 masterVolume = 0;
3956 }
3957 // Delegate master volume control to effect in output mix effect chain if needed
3958 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3959 if (chain != 0) {
3960 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3961 chain->setVolume_l(&v, &v);
3962 masterVolume = (float)((v + (1 << 23)) >> 24);
3963 chain.clear();
3964 }
3965
3966 // prepare a new state to push
3967 FastMixerStateQueue *sq = NULL;
3968 FastMixerState *state = NULL;
3969 bool didModify = false;
3970 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003971 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003972 sq = mFastMixer->sq();
3973 state = sq->begin();
3974 }
3975
Andy Hung69aed5f2014-02-25 17:24:40 -08003976 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003977 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003978
Eric Laurent81784c32012-11-19 14:55:58 -08003979 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07003980 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003981
3982 // this const just means the local variable doesn't change
3983 Track* const track = t.get();
3984
3985 // process fast tracks
3986 if (track->isFastTrack()) {
3987
3988 // It's theoretically possible (though unlikely) for a fast track to be created
3989 // and then removed within the same normal mix cycle. This is not a problem, as
3990 // the track never becomes active so it's fast mixer slot is never touched.
3991 // The converse, of removing an (active) track and then creating a new track
3992 // at the identical fast mixer slot within the same normal mix cycle,
3993 // is impossible because the slot isn't marked available until the end of each cycle.
3994 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003995 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003996 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3997 FastTrack *fastTrack = &state->mFastTracks[j];
3998
3999 // Determine whether the track is currently in underrun condition,
4000 // and whether it had a recent underrun.
4001 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4002 FastTrackUnderruns underruns = ftDump->mUnderruns;
4003 uint32_t recentFull = (underruns.mBitFields.mFull -
4004 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4005 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4006 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4007 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4008 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4009 uint32_t recentUnderruns = recentPartial + recentEmpty;
4010 track->mObservedUnderruns = underruns;
4011 // don't count underruns that occur while stopping or pausing
4012 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004013 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4014 recentUnderruns > 0) {
4015 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4016 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004017 } else {
4018 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004019 }
4020
4021 // This is similar to the state machine for normal tracks,
4022 // with a few modifications for fast tracks.
4023 bool isActive = true;
4024 switch (track->mState) {
4025 case TrackBase::STOPPING_1:
4026 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004027 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004028 track->mState = TrackBase::STOPPING_2;
4029 }
4030 break;
4031 case TrackBase::PAUSING:
4032 // ramp down is not yet implemented
4033 track->setPaused();
4034 break;
4035 case TrackBase::RESUMING:
4036 // ramp up is not yet implemented
4037 track->mState = TrackBase::ACTIVE;
4038 break;
4039 case TrackBase::ACTIVE:
4040 if (recentFull > 0 || recentPartial > 0) {
4041 // track has provided at least some frames recently: reset retry count
4042 track->mRetryCount = kMaxTrackRetries;
4043 }
4044 if (recentUnderruns == 0) {
4045 // no recent underruns: stay active
4046 break;
4047 }
4048 // there has recently been an underrun of some kind
4049 if (track->sharedBuffer() == 0) {
4050 // were any of the recent underruns "empty" (no frames available)?
4051 if (recentEmpty == 0) {
4052 // no, then ignore the partial underruns as they are allowed indefinitely
4053 break;
4054 }
4055 // there has recently been an "empty" underrun: decrement the retry counter
4056 if (--(track->mRetryCount) > 0) {
4057 break;
4058 }
4059 // indicate to client process that the track was disabled because of underrun;
4060 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004061 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004062 // remove from active list, but state remains ACTIVE [confusing but true]
4063 isActive = false;
4064 break;
4065 }
4066 // fall through
4067 case TrackBase::STOPPING_2:
4068 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004069 case TrackBase::STOPPED:
4070 case TrackBase::FLUSHED: // flush() while active
4071 // Check for presentation complete if track is inactive
4072 // We have consumed all the buffers of this track.
4073 // This would be incomplete if we auto-paused on underrun
4074 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004075 uint32_t latency = 0;
4076 status_t result = mOutput->stream->getLatency(&latency);
4077 ALOGE_IF(result != OK,
4078 "Error when retrieving output stream latency: %d", result);
4079 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004080 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004081 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4082 // track stays in active list until presentation is complete
4083 break;
4084 }
4085 }
4086 if (track->isStopping_2()) {
4087 track->mState = TrackBase::STOPPED;
4088 }
4089 if (track->isStopped()) {
4090 // Can't reset directly, as fast mixer is still polling this track
4091 // track->reset();
4092 // So instead mark this track as needing to be reset after push with ack
4093 resetMask |= 1 << i;
4094 }
4095 isActive = false;
4096 break;
4097 case TrackBase::IDLE:
4098 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004099 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004100 }
4101
4102 if (isActive) {
4103 // was it previously inactive?
4104 if (!(state->mTrackMask & (1 << j))) {
4105 ExtendedAudioBufferProvider *eabp = track;
4106 VolumeProvider *vp = track;
4107 fastTrack->mBufferProvider = eabp;
4108 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004109 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004110 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004111 fastTrack->mGeneration++;
4112 state->mTrackMask |= 1 << j;
4113 didModify = true;
4114 // no acknowledgement required for newly active tracks
4115 }
4116 // cache the combined master volume and stream type volume for fast mixer; this
4117 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004118 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004119 ++fastTracks;
4120 } else {
4121 // was it previously active?
4122 if (state->mTrackMask & (1 << j)) {
4123 fastTrack->mBufferProvider = NULL;
4124 fastTrack->mGeneration++;
4125 state->mTrackMask &= ~(1 << j);
4126 didModify = true;
4127 // If any fast tracks were removed, we must wait for acknowledgement
4128 // because we're about to decrement the last sp<> on those tracks.
4129 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4130 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004131 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4132 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4133 j, track->mState, state->mTrackMask, recentUnderruns,
4134 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004135 }
4136 tracksToRemove->add(track);
4137 // Avoids a misleading display in dumpsys
4138 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4139 }
4140 continue;
4141 }
4142
4143 { // local variable scope to avoid goto warning
4144
4145 audio_track_cblk_t* cblk = track->cblk();
4146
4147 // The first time a track is added we wait
4148 // for all its buffers to be filled before processing it
4149 int name = track->name();
4150 // make sure that we have enough frames to mix one full buffer.
4151 // enforce this condition only once to enable draining the buffer in case the client
4152 // app does not call stop() and relies on underrun to stop:
4153 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4154 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004155 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004156 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004157 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004158
4159 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004160 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004161 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4162 // add frames already consumed but not yet released by the resampler
4163 // because mAudioTrackServerProxy->framesReady() will include these frames
4164 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4165
Eric Laurent81784c32012-11-19 14:55:58 -08004166 uint32_t minFrames = 1;
4167 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4168 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004169 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004170 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004171
4172 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004173 if (ATRACE_ENABLED()) {
4174 // I wish we had formatted trace names
4175 char traceName[16];
4176 strcpy(traceName, "nRdy");
4177 int name = track->name();
4178 if (AudioMixer::TRACK0 <= name &&
4179 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4180 name -= AudioMixer::TRACK0;
4181 traceName[4] = (name / 10) + '0';
4182 traceName[5] = (name % 10) + '0';
4183 } else {
4184 traceName[4] = '?';
4185 traceName[5] = '?';
4186 }
4187 traceName[6] = '\0';
4188 ATRACE_INT(traceName, framesReady);
4189 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004190 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004191 !track->isPaused() && !track->isTerminated())
4192 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004193 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004194
4195 mixedTracks++;
4196
Andy Hung69aed5f2014-02-25 17:24:40 -08004197 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4198 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004199 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004200 if (track->mainBuffer() != mSinkBuffer &&
4201 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004202 if (mEffectBufferEnabled) {
4203 mEffectBufferValid = true; // Later can set directly.
4204 }
Eric Laurent81784c32012-11-19 14:55:58 -08004205 chain = getEffectChain_l(track->sessionId());
4206 // Delegate volume control to effect in track effect chain if needed
4207 if (chain != 0) {
4208 tracksWithEffect++;
4209 } else {
4210 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4211 "session %d",
4212 name, track->sessionId());
4213 }
4214 }
4215
4216
4217 int param = AudioMixer::VOLUME;
4218 if (track->mFillingUpStatus == Track::FS_FILLED) {
4219 // no ramp for the first volume setting
4220 track->mFillingUpStatus = Track::FS_ACTIVE;
4221 if (track->mState == TrackBase::RESUMING) {
4222 track->mState = TrackBase::ACTIVE;
4223 param = AudioMixer::RAMP_VOLUME;
4224 }
4225 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004226 // FIXME should not make a decision based on mServer
4227 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004228 // If the track is stopped before the first frame was mixed,
4229 // do not apply ramp
4230 param = AudioMixer::RAMP_VOLUME;
4231 }
4232
4233 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004234 uint32_t vl, vr; // in U8.24 integer format
4235 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004236 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004237 vl = vr = 0;
4238 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004239 if (track->isPausing()) {
4240 track->setPaused();
4241 }
4242 } else {
4243
4244 // read original volumes with volume control
4245 float typeVolume = mStreamTypes[track->streamType()].volume;
4246 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004247 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004248 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004249 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4250 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004251 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004252 if (vlf > GAIN_FLOAT_UNITY) {
4253 ALOGV("Track left volume out of range: %.3g", vlf);
4254 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004255 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004256 if (vrf > GAIN_FLOAT_UNITY) {
4257 ALOGV("Track right volume out of range: %.3g", vrf);
4258 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004259 }
4260 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004261 vlf *= v;
4262 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004263 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004264 // then derive vl and vr as U8.24 versions for the effect chain
4265 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4266 vl = (uint32_t) (scaleto8_24 * vlf);
4267 vr = (uint32_t) (scaleto8_24 * vrf);
4268 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004269 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004270 // send level comes from shared memory and so may be corrupt
4271 if (sendLevel > MAX_GAIN_INT) {
4272 ALOGV("Track send level out of range: %04X", sendLevel);
4273 sendLevel = MAX_GAIN_INT;
4274 }
Andy Hung6be49402014-05-30 10:42:03 -07004275 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4276 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004277 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004278
Eric Laurent81784c32012-11-19 14:55:58 -08004279 // Delegate volume control to effect in track effect chain if needed
4280 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4281 // Do not ramp volume if volume is controlled by effect
4282 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004283 // Update remaining floating point volume levels
4284 vlf = (float)vl / (1 << 24);
4285 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004286 track->mHasVolumeController = true;
4287 } else {
4288 // force no volume ramp when volume controller was just disabled or removed
4289 // from effect chain to avoid volume spike
4290 if (track->mHasVolumeController) {
4291 param = AudioMixer::VOLUME;
4292 }
4293 track->mHasVolumeController = false;
4294 }
4295
Eric Laurent81784c32012-11-19 14:55:58 -08004296 // XXX: these things DON'T need to be done each time
4297 mAudioMixer->setBufferProvider(name, track);
4298 mAudioMixer->enable(name);
4299
Andy Hung6be49402014-05-30 10:42:03 -07004300 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4301 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4302 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004303 mAudioMixer->setParameter(
4304 name,
4305 AudioMixer::TRACK,
4306 AudioMixer::FORMAT, (void *)track->format());
4307 mAudioMixer->setParameter(
4308 name,
4309 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004310 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004311 mAudioMixer->setParameter(
4312 name,
4313 AudioMixer::TRACK,
4314 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004315 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004316 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004317 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004318 if (reqSampleRate == 0) {
4319 reqSampleRate = mSampleRate;
4320 } else if (reqSampleRate > maxSampleRate) {
4321 reqSampleRate = maxSampleRate;
4322 }
Eric Laurent81784c32012-11-19 14:55:58 -08004323 mAudioMixer->setParameter(
4324 name,
4325 AudioMixer::RESAMPLE,
4326 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004327 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004328
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004329 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004330 mAudioMixer->setParameter(
4331 name,
4332 AudioMixer::TIMESTRETCH,
4333 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004334 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004335
Andy Hung69aed5f2014-02-25 17:24:40 -08004336 /*
4337 * Select the appropriate output buffer for the track.
4338 *
Andy Hung98ef9782014-03-04 14:46:50 -08004339 * Tracks with effects go into their own effects chain buffer
4340 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004341 *
4342 * Other tracks can use mMixerBuffer for higher precision
4343 * channel accumulation. If this buffer is enabled
4344 * (mMixerBufferEnabled true), then selected tracks will accumulate
4345 * into it.
4346 *
4347 */
4348 if (mMixerBufferEnabled
4349 && (track->mainBuffer() == mSinkBuffer
4350 || track->mainBuffer() == mMixerBuffer)) {
4351 mAudioMixer->setParameter(
4352 name,
4353 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004354 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004355 mAudioMixer->setParameter(
4356 name,
4357 AudioMixer::TRACK,
4358 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4359 // TODO: override track->mainBuffer()?
4360 mMixerBufferValid = true;
4361 } else {
4362 mAudioMixer->setParameter(
4363 name,
4364 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004365 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004366 mAudioMixer->setParameter(
4367 name,
4368 AudioMixer::TRACK,
4369 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4370 }
Eric Laurent81784c32012-11-19 14:55:58 -08004371 mAudioMixer->setParameter(
4372 name,
4373 AudioMixer::TRACK,
4374 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4375
4376 // reset retry count
4377 track->mRetryCount = kMaxTrackRetries;
4378
4379 // If one track is ready, set the mixer ready if:
4380 // - the mixer was not ready during previous round OR
4381 // - no other track is not ready
4382 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4383 mixerStatus != MIXER_TRACKS_ENABLED) {
4384 mixerStatus = MIXER_TRACKS_READY;
4385 }
4386 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004387 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004388 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4389 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004390 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004391 } else {
4392 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004393 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004394
Eric Laurent81784c32012-11-19 14:55:58 -08004395 // clear effect chain input buffer if an active track underruns to avoid sending
4396 // previous audio buffer again to effects
4397 chain = getEffectChain_l(track->sessionId());
4398 if (chain != 0) {
4399 chain->clearInputBuffer();
4400 }
4401
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004402 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004403 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4404 track->isStopped() || track->isPaused()) {
4405 // We have consumed all the buffers of this track.
4406 // Remove it from the list of active tracks.
4407 // TODO: use actual buffer filling status instead of latency when available from
4408 // audio HAL
4409 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004410 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004411 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4412 if (track->isStopped()) {
4413 track->reset();
4414 }
4415 tracksToRemove->add(track);
4416 }
4417 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004418 // No buffers for this track. Give it a few chances to
4419 // fill a buffer, then remove it from active list.
4420 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004421 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004422 tracksToRemove->add(track);
4423 // indicate to client process that the track was disabled because of underrun;
4424 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004425 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004426 // If one track is not ready, mark the mixer also not ready if:
4427 // - the mixer was ready during previous round OR
4428 // - no other track is ready
4429 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4430 mixerStatus != MIXER_TRACKS_READY) {
4431 mixerStatus = MIXER_TRACKS_ENABLED;
4432 }
4433 }
4434 mAudioMixer->disable(name);
4435 }
4436
4437 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004438
4439 }
4440
4441 // Push the new FastMixer state if necessary
4442 bool pauseAudioWatchdog = false;
4443 if (didModify) {
4444 state->mFastTracksGen++;
4445 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4446 if (kUseFastMixer == FastMixer_Dynamic &&
4447 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4448 state->mCommand = FastMixerState::COLD_IDLE;
4449 state->mColdFutexAddr = &mFastMixerFutex;
4450 state->mColdGen++;
4451 mFastMixerFutex = 0;
4452 if (kUseFastMixer == FastMixer_Dynamic) {
4453 mNormalSink = mOutputSink;
4454 }
4455 // If we go into cold idle, need to wait for acknowledgement
4456 // so that fast mixer stops doing I/O.
4457 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4458 pauseAudioWatchdog = true;
4459 }
Eric Laurent81784c32012-11-19 14:55:58 -08004460 }
4461 if (sq != NULL) {
4462 sq->end(didModify);
4463 sq->push(block);
4464 }
4465#ifdef AUDIO_WATCHDOG
4466 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4467 mAudioWatchdog->pause();
4468 }
4469#endif
4470
4471 // Now perform the deferred reset on fast tracks that have stopped
4472 while (resetMask != 0) {
4473 size_t i = __builtin_ctz(resetMask);
4474 ALOG_ASSERT(i < count);
4475 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004476 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004477 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4478 track->reset();
4479 }
4480
4481 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004482 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004483
Eric Laurent97d547d2014-09-02 14:45:53 -07004484 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4485 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004486 }
4487
4488 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004489 // as long as there are effects we should clear the effects buffer, to avoid
4490 // passing a non-clean buffer to the effect chain
4491 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004492 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004493 // sink or mix buffer must be cleared if all tracks are connected to an
4494 // effect chain as in this case the mixer will not write to the sink or mix buffer
4495 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004496 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4497 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004498 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004499 if (mMixerBufferValid) {
4500 memset(mMixerBuffer, 0, mMixerBufferSize);
4501 // TODO: In testing, mSinkBuffer below need not be cleared because
4502 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4503 // after mixing.
4504 //
4505 // To enforce this guarantee:
4506 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4507 // (mixedTracks == 0 && fastTracks > 0))
4508 // must imply MIXER_TRACKS_READY.
4509 // Later, we may clear buffers regardless, and skip much of this logic.
4510 }
Andy Hung98ef9782014-03-04 14:46:50 -08004511 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004512 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004513 }
4514
4515 // if any fast tracks, then status is ready
4516 mMixerStatusIgnoringFastTracks = mixerStatus;
4517 if (fastTracks > 0) {
4518 mixerStatus = MIXER_TRACKS_READY;
4519 }
4520 return mixerStatus;
4521}
4522
Eric Laurentad7dd962016-09-22 12:38:37 -07004523// trackCountForUid_l() must be called with ThreadBase::mLock held
4524uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4525{
4526 uint32_t trackCount = 0;
4527 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004528 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004529 trackCount++;
4530 }
4531 }
4532 return trackCount;
4533}
4534
Eric Laurent81784c32012-11-19 14:55:58 -08004535// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004536int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004537 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004538{
Eric Laurentad7dd962016-09-22 12:38:37 -07004539 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4540 return -1;
4541 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004542 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004543}
4544
4545// deleteTrackName_l() must be called with ThreadBase::mLock held
4546void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4547{
4548 ALOGV("remove track (%d) and delete from mixer", name);
4549 mAudioMixer->deleteTrackName(name);
4550}
4551
Eric Laurent10351942014-05-08 18:49:52 -07004552// checkForNewParameter_l() must be called with ThreadBase::mLock held
4553bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4554 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004555{
Eric Laurent81784c32012-11-19 14:55:58 -08004556 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004557 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004558
Eric Laurent10351942014-05-08 18:49:52 -07004559 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004560
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004561 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004562
Eric Laurent10351942014-05-08 18:49:52 -07004563 AudioParameter param = AudioParameter(keyValuePair);
4564 int value;
4565 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4566 reconfig = true;
4567 }
4568 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004569 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004570 status = BAD_VALUE;
4571 } else {
4572 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004573 reconfig = true;
4574 }
Eric Laurent10351942014-05-08 18:49:52 -07004575 }
4576 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004577 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004578 status = BAD_VALUE;
4579 } else {
4580 // no need to save value, since it's constant
4581 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004582 }
Eric Laurent10351942014-05-08 18:49:52 -07004583 }
4584 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4585 // do not accept frame count changes if tracks are open as the track buffer
4586 // size depends on frame count and correct behavior would not be guaranteed
4587 // if frame count is changed after track creation
4588 if (!mTracks.isEmpty()) {
4589 status = INVALID_OPERATION;
4590 } else {
4591 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004592 }
Eric Laurent10351942014-05-08 18:49:52 -07004593 }
4594 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004595#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004596 // when changing the audio output device, call addBatteryData to notify
4597 // the change
4598 if (mOutDevice != value) {
4599 uint32_t params = 0;
4600 // check whether speaker is on
4601 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4602 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004603 }
Eric Laurent10351942014-05-08 18:49:52 -07004604
4605 audio_devices_t deviceWithoutSpeaker
4606 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4607 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004608 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004609 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4610 }
4611
4612 if (params != 0) {
4613 addBatteryData(params);
4614 }
4615 }
Eric Laurent81784c32012-11-19 14:55:58 -08004616#endif
4617
Eric Laurent10351942014-05-08 18:49:52 -07004618 // forward device change to effects that have requested to be
4619 // aware of attached audio device.
4620 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004621 a2dpDeviceChanged =
4622 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004623 mOutDevice = value;
4624 for (size_t i = 0; i < mEffectChains.size(); i++) {
4625 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004626 }
4627 }
Eric Laurent10351942014-05-08 18:49:52 -07004628 }
Eric Laurent81784c32012-11-19 14:55:58 -08004629
Eric Laurent10351942014-05-08 18:49:52 -07004630 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004631 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004632 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004633 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004634 mStandby = true;
4635 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004636 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004637 }
Eric Laurent10351942014-05-08 18:49:52 -07004638 if (status == NO_ERROR && reconfig) {
4639 readOutputParameters_l();
4640 delete mAudioMixer;
4641 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4642 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004643 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004644 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004645 if (name < 0) {
4646 break;
4647 }
4648 mTracks[i]->mName = name;
4649 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004650 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004651 }
Eric Laurent81784c32012-11-19 14:55:58 -08004652 }
4653
Eric Laurent42537be2016-01-08 17:16:42 -08004654 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004655}
4656
4657
4658void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4659{
Eric Laurent81784c32012-11-19 14:55:58 -08004660 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004661 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004662 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004663 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004664
4665 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004666 // while we are dumping it. It may be inconsistent, but it won't mutate!
4667 // This is a large object so we place it on the heap.
4668 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4669 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4670 copy->dump(fd);
4671 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004672
4673#ifdef STATE_QUEUE_DUMP
4674 // Similar for state queue
4675 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4676 observerCopy.dump(fd);
4677 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4678 mutatorCopy.dump(fd);
4679#endif
4680
Glenn Kasten46909e72013-02-26 09:20:22 -08004681#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004682 // Write the tee output to a .wav file
4683 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004684#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004685
4686#ifdef AUDIO_WATCHDOG
4687 if (mAudioWatchdog != 0) {
4688 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4689 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4690 wdCopy.dump(fd);
4691 }
4692#endif
4693}
4694
4695uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4696{
4697 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4698}
4699
4700uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4701{
4702 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4703}
4704
4705void AudioFlinger::MixerThread::cacheParameters_l()
4706{
4707 PlaybackThread::cacheParameters_l();
4708
4709 // FIXME: Relaxed timing because of a certain device that can't meet latency
4710 // Should be reduced to 2x after the vendor fixes the driver issue
4711 // increase threshold again due to low power audio mode. The way this warning
4712 // threshold is calculated and its usefulness should be reconsidered anyway.
4713 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4714}
4715
4716// ----------------------------------------------------------------------------
4717
4718AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004719 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4720 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004721 // mLeftVolFloat, mRightVolFloat
4722{
4723}
4724
Eric Laurentbfb1b832013-01-07 09:53:42 -08004725AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4726 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004727 ThreadBase::type_t type, bool systemReady)
4728 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004729 // mLeftVolFloat, mRightVolFloat
4730{
4731}
4732
Eric Laurent81784c32012-11-19 14:55:58 -08004733AudioFlinger::DirectOutputThread::~DirectOutputThread()
4734{
4735}
4736
Eric Laurent5850c4c2016-11-10 13:04:31 -08004737void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004738{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004739 float left, right;
4740
4741 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4742 left = right = 0;
4743 } else {
4744 float typeVolume = mStreamTypes[track->streamType()].volume;
4745 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004746 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004747 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4748 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4749 if (left > GAIN_FLOAT_UNITY) {
4750 left = GAIN_FLOAT_UNITY;
4751 }
4752 left *= v;
4753 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4754 if (right > GAIN_FLOAT_UNITY) {
4755 right = GAIN_FLOAT_UNITY;
4756 }
4757 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004758 }
4759
4760 if (lastTrack) {
4761 if (left != mLeftVolFloat || right != mRightVolFloat) {
4762 mLeftVolFloat = left;
4763 mRightVolFloat = right;
4764
4765 // Convert volumes from float to 8.24
4766 uint32_t vl = (uint32_t)(left * (1 << 24));
4767 uint32_t vr = (uint32_t)(right * (1 << 24));
4768
4769 // Delegate volume control to effect in track effect chain if needed
4770 // only one effect chain can be present on DirectOutputThread, so if
4771 // there is one, the track is connected to it
4772 if (!mEffectChains.isEmpty()) {
4773 mEffectChains[0]->setVolume_l(&vl, &vr);
4774 left = (float)vl / (1 << 24);
4775 right = (float)vr / (1 << 24);
4776 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004777 status_t result = mOutput->stream->setVolume(left, right);
4778 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004779 }
4780 }
4781}
4782
Phil Burk43b4dcc2015-06-09 16:53:44 -07004783void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4784{
4785 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004786 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004787
Eric Laurent0f0631e2015-07-06 18:01:25 -07004788 if (previousTrack != 0 && latestTrack != 0) {
4789 if (mType == DIRECT) {
4790 if (previousTrack.get() != latestTrack.get()) {
4791 mFlushPending = true;
4792 }
4793 } else /* mType == OFFLOAD */ {
4794 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4795 mFlushPending = true;
4796 }
4797 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004798 }
4799 PlaybackThread::onAddNewTrack_l();
4800}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004801
Eric Laurent81784c32012-11-19 14:55:58 -08004802AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4803 Vector< sp<Track> > *tracksToRemove
4804)
4805{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004806 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004807 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004808 bool doHwPause = false;
4809 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004810
4811 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004812 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004813 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004814 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004815 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004816 continue;
4817 }
4818
Eric Laurent5850c4c2016-11-10 13:04:31 -08004819 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004820#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004821 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004822#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004823 // Only consider last track started for volume and mixer state control.
4824 // In theory an older track could underrun and restart after the new one starts
4825 // but as we only care about the transition phase between two tracks on a
4826 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004827 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004828 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004829
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004830 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004831 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004832 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004833 doHwPause = true;
4834 mHwPaused = true;
4835 }
4836 tracksToRemove->add(track);
4837 } else if (track->isFlushPending()) {
4838 track->flushAck();
4839 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004840 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004841 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004842 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004843 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004844 if (last) {
4845 mLeftVolFloat = mRightVolFloat = -1.0;
4846 if (mHwPaused) {
4847 doHwResume = true;
4848 mHwPaused = false;
4849 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004850 }
4851 }
4852
Eric Laurent81784c32012-11-19 14:55:58 -08004853 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004854 // for all its buffers to be filled before processing it.
4855 // Allow draining the buffer in case the client
4856 // app does not call stop() and relies on underrun to stop:
4857 // hence the test on (track->mRetryCount > 1).
4858 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004859 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004860 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004861 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004862 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004863 minFrames = mNormalFrameCount;
4864 } else {
4865 minFrames = 1;
4866 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004867
Eric Laurentab5cdba2014-06-09 17:22:27 -07004868 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4869 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004870 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004871 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004872
4873 if (track->mFillingUpStatus == Track::FS_FILLED) {
4874 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004875 if (last) {
4876 // make sure processVolume_l() will apply new volume even if 0
4877 mLeftVolFloat = mRightVolFloat = -1.0;
4878 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004879 if (!mHwSupportsPause) {
4880 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004881 }
4882 }
4883
4884 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004885 processVolume_l(track, last);
4886 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004887 sp<Track> previousTrack = mPreviousTrack.promote();
4888 if (previousTrack != 0) {
4889 if (track != previousTrack.get()) {
4890 // Flush any data still being written from last track
4891 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004892 // Invalidate previous track to force a seek when resuming.
4893 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004894 }
4895 }
4896 mPreviousTrack = track;
4897
Eric Laurentd595b7c2013-04-03 17:27:56 -07004898 // reset retry count
4899 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004900 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004901 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004902 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004903 doHwResume = true;
4904 mHwPaused = false;
4905 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004906 }
Eric Laurent81784c32012-11-19 14:55:58 -08004907 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004908 // clear effect chain input buffer if the last active track started underruns
4909 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004910 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004911 mEffectChains[0]->clearInputBuffer();
4912 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004913 if (track->isStopping_1()) {
4914 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004915 if (last && mHwPaused) {
4916 doHwResume = true;
4917 mHwPaused = false;
4918 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004919 }
4920 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4921 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004922 // We have consumed all the buffers of this track.
4923 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004924 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004925 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004926 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4927 } else {
4928 audioHALFrames = 0;
4929 }
4930
Andy Hung818e7a32016-02-16 18:08:07 -08004931 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004932 if (mStandby || !last ||
4933 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004934 if (track->isStopping_2()) {
4935 track->mState = TrackBase::STOPPED;
4936 }
Eric Laurent81784c32012-11-19 14:55:58 -08004937 if (track->isStopped()) {
4938 track->reset();
4939 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004940 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004941 }
4942 } else {
4943 // No buffers for this track. Give it a few chances to
4944 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004945 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004946 if (--(track->mRetryCount) <= 0) {
4947 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004948 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004949 // indicate to client process that the track was disabled because of underrun;
4950 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004951 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004952 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004953 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4954 "minFrames = %u, mFormat = %#x",
4955 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004956 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004957 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004958 doHwPause = true;
4959 mHwPaused = true;
4960 }
Eric Laurent81784c32012-11-19 14:55:58 -08004961 }
4962 }
4963 }
4964 }
4965
Eric Laurentd1f69b02014-12-15 14:33:13 -08004966 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004967 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004968 for (size_t i = 0; i < mTracks.size(); i++) {
4969 if (mTracks[i]->isFlushPending()) {
4970 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004971 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004972 }
4973 }
4974 }
4975
4976 // make sure the pause/flush/resume sequence is executed in the right order.
4977 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4978 // before flush and then resume HW. This can happen in case of pause/flush/resume
4979 // if resume is received before pause is executed.
4980 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004981 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004982 status_t result = mOutput->stream->pause();
4983 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004984 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004985 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004986 flushHw_l();
4987 }
4988 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004989 status_t result = mOutput->stream->resume();
4990 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004991 }
Eric Laurent81784c32012-11-19 14:55:58 -08004992 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004993 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004994
4995 return mixerStatus;
4996}
4997
4998void AudioFlinger::DirectOutputThread::threadLoop_mix()
4999{
Eric Laurent81784c32012-11-19 14:55:58 -08005000 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005001 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005002 // output audio to hardware
5003 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005004 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005005 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005006 status_t status = mActiveTrack->getNextBuffer(&buffer);
5007 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005008 // no need to pad with 0 for compressed audio
5009 if (audio_has_proportional_frames(mFormat)) {
5010 memset(curBuf, 0, frameCount * mFrameSize);
5011 }
Eric Laurent81784c32012-11-19 14:55:58 -08005012 break;
5013 }
5014 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5015 frameCount -= buffer.frameCount;
5016 curBuf += buffer.frameCount * mFrameSize;
5017 mActiveTrack->releaseBuffer(&buffer);
5018 }
Andy Hung2098f272014-02-27 14:00:06 -08005019 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005020 mSleepTimeUs = 0;
5021 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005022 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005023}
5024
5025void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5026{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005027 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005028 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005029 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005030 return;
5031 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005032 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005033 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005034 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005035 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005036 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005037 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005038 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005039 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005040 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005041 }
5042}
5043
Eric Laurentd1f69b02014-12-15 14:33:13 -08005044void AudioFlinger::DirectOutputThread::threadLoop_exit()
5045{
5046 {
5047 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005048 for (size_t i = 0; i < mTracks.size(); i++) {
5049 if (mTracks[i]->isFlushPending()) {
5050 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005051 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005052 }
5053 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005054 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005055 flushHw_l();
5056 }
5057 }
5058 PlaybackThread::threadLoop_exit();
5059}
5060
5061// must be called with thread mutex locked
5062bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5063{
5064 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005065 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005066
vivek mehta9cd7ad12016-03-17 00:18:29 -07005067 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5068 return !mStandby;
5069 }
5070
Eric Laurentd1f69b02014-12-15 14:33:13 -08005071 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5072 // after a timeout and we will enter standby then.
5073 if (mTracks.size() > 0) {
5074 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005075 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5076 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005077 }
5078
Eric Laurent5cff4032015-05-26 13:49:58 -07005079 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005080}
5081
Eric Laurent81784c32012-11-19 14:55:58 -08005082// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005083int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005084 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005085{
Eric Laurentad7dd962016-09-22 12:38:37 -07005086 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5087 return -1;
5088 }
Eric Laurent81784c32012-11-19 14:55:58 -08005089 return 0;
5090}
5091
5092// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005093void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005094{
5095}
5096
Eric Laurent10351942014-05-08 18:49:52 -07005097// checkForNewParameter_l() must be called with ThreadBase::mLock held
5098bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5099 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005100{
5101 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005102 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005103
Eric Laurent10351942014-05-08 18:49:52 -07005104 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005105
Eric Laurent10351942014-05-08 18:49:52 -07005106 AudioParameter param = AudioParameter(keyValuePair);
5107 int value;
5108 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5109 // forward device change to effects that have requested to be
5110 // aware of attached audio device.
5111 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005112 a2dpDeviceChanged =
5113 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005114 mOutDevice = value;
5115 for (size_t i = 0; i < mEffectChains.size(); i++) {
5116 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005117 }
5118 }
Eric Laurent81784c32012-11-19 14:55:58 -08005119 }
Eric Laurent10351942014-05-08 18:49:52 -07005120 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5121 // do not accept frame count changes if tracks are open as the track buffer
5122 // size depends on frame count and correct behavior would not be garantied
5123 // if frame count is changed after track creation
5124 if (!mTracks.isEmpty()) {
5125 status = INVALID_OPERATION;
5126 } else {
5127 reconfig = true;
5128 }
5129 }
5130 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005131 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005132 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005133 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005134 mStandby = true;
5135 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005136 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005137 }
5138 if (status == NO_ERROR && reconfig) {
5139 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005140 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005141 }
5142 }
5143
Eric Laurent42537be2016-01-08 17:16:42 -08005144 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005145}
5146
5147uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5148{
5149 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005150 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005151 time = PlaybackThread::activeSleepTimeUs();
5152 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005153 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005154 }
5155 return time;
5156}
5157
5158uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5159{
5160 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005161 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005162 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5163 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005164 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005165 }
5166 return time;
5167}
5168
5169uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5170{
5171 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005172 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005173 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5174 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005175 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005176 }
5177 return time;
5178}
5179
5180void AudioFlinger::DirectOutputThread::cacheParameters_l()
5181{
5182 PlaybackThread::cacheParameters_l();
5183
5184 // use shorter standby delay as on normal output to release
5185 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005186 // no delay on outputs with HW A/V sync
5187 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005188 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005189 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005190 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005191 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005192 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005193 }
Eric Laurent81784c32012-11-19 14:55:58 -08005194}
5195
Eric Laurente659ef42014-09-29 13:06:46 -07005196void AudioFlinger::DirectOutputThread::flushHw_l()
5197{
Phil Burk062e67a2015-02-11 13:40:50 -08005198 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005199 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005200 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005201}
5202
Eric Laurent81784c32012-11-19 14:55:58 -08005203// ----------------------------------------------------------------------------
5204
Eric Laurentbfb1b832013-01-07 09:53:42 -08005205AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005206 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005207 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005208 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005209 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005210 mDrainSequence(0),
5211 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005212{
5213}
5214
5215AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5216{
5217}
5218
5219void AudioFlinger::AsyncCallbackThread::onFirstRef()
5220{
5221 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5222}
5223
5224bool AudioFlinger::AsyncCallbackThread::threadLoop()
5225{
5226 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005227 uint32_t writeAckSequence;
5228 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005229 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005230
5231 {
5232 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005233 while (!((mWriteAckSequence & 1) ||
5234 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005235 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005236 exitPending())) {
5237 mWaitWorkCV.wait(mLock);
5238 }
5239
Eric Laurentbfb1b832013-01-07 09:53:42 -08005240 if (exitPending()) {
5241 break;
5242 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005243 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5244 mWriteAckSequence, mDrainSequence);
5245 writeAckSequence = mWriteAckSequence;
5246 mWriteAckSequence &= ~1;
5247 drainSequence = mDrainSequence;
5248 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005249 asyncError = mAsyncError;
5250 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005251 }
5252 {
Eric Laurent4de95592013-09-26 15:28:21 -07005253 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5254 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005255 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005256 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005257 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005258 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005259 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005260 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005261 if (asyncError) {
5262 playbackThread->onAsyncError();
5263 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005264 }
5265 }
5266 }
5267 return false;
5268}
5269
5270void AudioFlinger::AsyncCallbackThread::exit()
5271{
5272 ALOGV("AsyncCallbackThread::exit");
5273 Mutex::Autolock _l(mLock);
5274 requestExit();
5275 mWaitWorkCV.broadcast();
5276}
5277
Eric Laurent3b4529e2013-09-05 18:09:19 -07005278void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005279{
5280 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005281 // bit 0 is cleared
5282 mWriteAckSequence = sequence << 1;
5283}
5284
5285void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5286{
5287 Mutex::Autolock _l(mLock);
5288 // ignore unexpected callbacks
5289 if (mWriteAckSequence & 2) {
5290 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005291 mWaitWorkCV.signal();
5292 }
5293}
5294
Eric Laurent3b4529e2013-09-05 18:09:19 -07005295void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005296{
5297 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005298 // bit 0 is cleared
5299 mDrainSequence = sequence << 1;
5300}
5301
5302void AudioFlinger::AsyncCallbackThread::resetDraining()
5303{
5304 Mutex::Autolock _l(mLock);
5305 // ignore unexpected callbacks
5306 if (mDrainSequence & 2) {
5307 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308 mWaitWorkCV.signal();
5309 }
5310}
5311
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005312void AudioFlinger::AsyncCallbackThread::setAsyncError()
5313{
5314 Mutex::Autolock _l(mLock);
5315 mAsyncError = true;
5316 mWaitWorkCV.signal();
5317}
5318
Eric Laurentbfb1b832013-01-07 09:53:42 -08005319
5320// ----------------------------------------------------------------------------
5321AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005322 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5323 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005324 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5325 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005326{
Eric Laurentfd477972013-10-25 18:10:40 -07005327 //FIXME: mStandby should be set to true by ThreadBase constructor
5328 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005329 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005330}
5331
Eric Laurentbfb1b832013-01-07 09:53:42 -08005332void AudioFlinger::OffloadThread::threadLoop_exit()
5333{
5334 if (mFlushPending || mHwPaused) {
5335 // If a flush is pending or track was paused, just discard buffered data
5336 flushHw_l();
5337 } else {
5338 mMixerStatus = MIXER_DRAIN_ALL;
5339 threadLoop_drain();
5340 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005341 if (mUseAsyncWrite) {
5342 ALOG_ASSERT(mCallbackThread != 0);
5343 mCallbackThread->exit();
5344 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005345 PlaybackThread::threadLoop_exit();
5346}
5347
5348AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5349 Vector< sp<Track> > *tracksToRemove
5350)
5351{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005352 size_t count = mActiveTracks.size();
5353
5354 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005355 bool doHwPause = false;
5356 bool doHwResume = false;
5357
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005358 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005359
Eric Laurentbfb1b832013-01-07 09:53:42 -08005360 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005361 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005362 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005363#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005364 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005365#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005366 // Only consider last track started for volume and mixer state control.
5367 // In theory an older track could underrun and restart after the new one starts
5368 // but as we only care about the transition phase between two tracks on a
5369 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005370 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005371 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005372
Haynes Mathew George7844f672014-01-15 12:32:55 -08005373 if (track->isInvalid()) {
5374 ALOGW("An invalidated track shouldn't be in active list");
5375 tracksToRemove->add(track);
5376 continue;
5377 }
5378
5379 if (track->mState == TrackBase::IDLE) {
5380 ALOGW("An idle track shouldn't be in active list");
5381 continue;
5382 }
5383
Eric Laurentbfb1b832013-01-07 09:53:42 -08005384 if (track->isPausing()) {
5385 track->setPaused();
5386 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005387 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005388 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005389 mHwPaused = true;
5390 }
5391 // If we were part way through writing the mixbuffer to
5392 // the HAL we must save this until we resume
5393 // BUG - this will be wrong if a different track is made active,
5394 // in that case we want to discard the pending data in the
5395 // mixbuffer and tell the client to present it again when the
5396 // track is resumed
5397 mPausedWriteLength = mCurrentWriteLength;
5398 mPausedBytesRemaining = mBytesRemaining;
5399 mBytesRemaining = 0; // stop writing
5400 }
5401 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005402 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005403 if (track->isStopping_1()) {
5404 track->mRetryCount = kMaxTrackStopRetriesOffload;
5405 } else {
5406 track->mRetryCount = kMaxTrackRetriesOffload;
5407 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005408 track->flushAck();
5409 if (last) {
5410 mFlushPending = true;
5411 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005412 } else if (track->isResumePending()){
5413 track->resumeAck();
5414 if (last) {
5415 if (mPausedBytesRemaining) {
5416 // Need to continue write that was interrupted
5417 mCurrentWriteLength = mPausedWriteLength;
5418 mBytesRemaining = mPausedBytesRemaining;
5419 mPausedBytesRemaining = 0;
5420 }
5421 if (mHwPaused) {
5422 doHwResume = true;
5423 mHwPaused = false;
5424 // threadLoop_mix() will handle the case that we need to
5425 // resume an interrupted write
5426 }
5427 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005428 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005429
Eric Laurent3df841a2016-07-15 15:15:40 -07005430 mLeftVolFloat = mRightVolFloat = -1.0;
5431
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005432 // Do not handle new data in this iteration even if track->framesReady()
5433 mixerStatus = MIXER_TRACKS_ENABLED;
5434 }
5435 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005436 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005437 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005438 if (track->mFillingUpStatus == Track::FS_FILLED) {
5439 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005440 if (last) {
5441 // make sure processVolume_l() will apply new volume even if 0
5442 mLeftVolFloat = mRightVolFloat = -1.0;
5443 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005444 }
5445
5446 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005447 sp<Track> previousTrack = mPreviousTrack.promote();
5448 if (previousTrack != 0) {
5449 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005450 // Flush any data still being written from last track
5451 mBytesRemaining = 0;
5452 if (mPausedBytesRemaining) {
5453 // Last track was paused so we also need to flush saved
5454 // mixbuffer state and invalidate track so that it will
5455 // re-submit that unwritten data when it is next resumed
5456 mPausedBytesRemaining = 0;
5457 // Invalidate is a bit drastic - would be more efficient
5458 // to have a flag to tell client that some of the
5459 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005460 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005461 }
5462 // flush data already sent to the DSP if changing audio session as audio
5463 // comes from a different source. Also invalidate previous track to force a
5464 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005465 if (previousTrack->sessionId() != track->sessionId()) {
5466 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005467 }
5468 }
5469 }
5470 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005471 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005472 if (track->isStopping_1()) {
5473 track->mRetryCount = kMaxTrackStopRetriesOffload;
5474 } else {
5475 track->mRetryCount = kMaxTrackRetriesOffload;
5476 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005477 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005478 mixerStatus = MIXER_TRACKS_READY;
5479 }
5480 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005481 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005483 if (--(track->mRetryCount) <= 0) {
5484 // Hardware buffer can hold a large amount of audio so we must
5485 // wait for all current track's data to drain before we say
5486 // that the track is stopped.
5487 if (mBytesRemaining == 0) {
5488 // Only start draining when all data in mixbuffer
5489 // has been written
5490 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5491 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5492 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5493 if (last && !mStandby) {
5494 // do not modify drain sequence if we are already draining. This happens
5495 // when resuming from pause after drain.
5496 if ((mDrainSequence & 1) == 0) {
5497 mSleepTimeUs = 0;
5498 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5499 mixerStatus = MIXER_DRAIN_TRACK;
5500 mDrainSequence += 2;
5501 }
5502 if (mHwPaused) {
5503 // It is possible to move from PAUSED to STOPPING_1 without
5504 // a resume so we must ensure hardware is running
5505 doHwResume = true;
5506 mHwPaused = false;
5507 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005508 }
5509 }
Eric Laurente93cc032016-05-05 10:15:10 -07005510 } else if (last) {
5511 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5512 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005513 }
5514 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005515 // Drain has completed or we are in standby, signal presentation complete
5516 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005517 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005518 uint32_t latency = 0;
5519 status_t result = mOutput->stream->getLatency(&latency);
5520 ALOGE_IF(result != OK,
5521 "Error when retrieving output stream latency: %d", result);
5522 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005523 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005524 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005525 track->presentationComplete(framesWritten, audioHALFrames);
5526 track->reset();
5527 tracksToRemove->add(track);
5528 }
5529 } else {
5530 // No buffers for this track. Give it a few chances to
5531 // fill a buffer, then remove it from active list.
5532 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005533 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005534 uint64_t position = 0;
5535 struct timespec unused;
5536 // The running check restarts the retry counter at least once.
5537 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5538 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5539 running = true;
5540 mOffloadUnderrunPosition = position;
5541 }
5542 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005543 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5544 (long long)position, (long long)mOffloadUnderrunPosition);
5545 }
5546 if (running) { // still running, give us more time.
5547 track->mRetryCount = kMaxTrackRetriesOffload;
5548 } else {
5549 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5550 track->name());
5551 tracksToRemove->add(track);
5552 // indicate to client process that the track was disabled because of underrun;
5553 // it will then automatically call start() when data is available
5554 track->disable();
5555 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005556 } else if (last){
5557 mixerStatus = MIXER_TRACKS_ENABLED;
5558 }
5559 }
5560 }
5561 // compute volume for this track
5562 processVolume_l(track, last);
5563 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005564
Eric Laurentea0fade2013-10-04 16:23:48 -07005565 // make sure the pause/flush/resume sequence is executed in the right order.
5566 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5567 // before flush and then resume HW. This can happen in case of pause/flush/resume
5568 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005569 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005570 status_t result = mOutput->stream->pause();
5571 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005572 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005573 if (mFlushPending) {
5574 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005575 }
Eric Laurentfd477972013-10-25 18:10:40 -07005576 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005577 status_t result = mOutput->stream->resume();
5578 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005579 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005580
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581 // remove all the tracks that need to be...
5582 removeTracks_l(*tracksToRemove);
5583
5584 return mixerStatus;
5585}
5586
Eric Laurentbfb1b832013-01-07 09:53:42 -08005587// must be called with thread mutex locked
5588bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5589{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005590 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5591 mWriteAckSequence, mDrainSequence);
5592 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005593 return true;
5594 }
5595 return false;
5596}
5597
Eric Laurentbfb1b832013-01-07 09:53:42 -08005598bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5599{
5600 Mutex::Autolock _l(mLock);
5601 return waitingAsyncCallback_l();
5602}
5603
5604void AudioFlinger::OffloadThread::flushHw_l()
5605{
Eric Laurente659ef42014-09-29 13:06:46 -07005606 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005607 // Flush anything still waiting in the mixbuffer
5608 mCurrentWriteLength = 0;
5609 mBytesRemaining = 0;
5610 mPausedWriteLength = 0;
5611 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005612 // reset bytes written count to reflect that DSP buffers are empty after flush.
5613 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005614 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005615
Eric Laurentbfb1b832013-01-07 09:53:42 -08005616 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005617 // discard any pending drain or write ack by incrementing sequence
5618 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5619 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005620 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005621 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5622 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005623 }
5624}
5625
Haynes Mathew George05317d22016-05-03 16:34:26 -07005626void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5627{
5628 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005629 if (PlaybackThread::invalidateTracks_l(streamType)) {
5630 mFlushPending = true;
5631 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005632}
5633
Eric Laurentbfb1b832013-01-07 09:53:42 -08005634// ----------------------------------------------------------------------------
5635
Eric Laurent81784c32012-11-19 14:55:58 -08005636AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005637 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005638 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005639 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005640 mWaitTimeMs(UINT_MAX)
5641{
5642 addOutputTrack(mainThread);
5643}
5644
5645AudioFlinger::DuplicatingThread::~DuplicatingThread()
5646{
5647 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5648 mOutputTracks[i]->destroy();
5649 }
5650}
5651
5652void AudioFlinger::DuplicatingThread::threadLoop_mix()
5653{
5654 // mix buffers...
5655 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005656 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005657 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005658 if (mMixerBufferValid) {
5659 memset(mMixerBuffer, 0, mMixerBufferSize);
5660 } else {
5661 memset(mSinkBuffer, 0, mSinkBufferSize);
5662 }
Eric Laurent81784c32012-11-19 14:55:58 -08005663 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005664 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005665 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005666 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005667 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005668}
5669
5670void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5671{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005672 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005673 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005674 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005675 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005676 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005677 }
5678 } else if (mBytesWritten != 0) {
5679 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5680 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005681 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005682 } else {
5683 // flush remaining overflow buffers in output tracks
5684 writeFrames = 0;
5685 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005686 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005687 }
5688}
5689
Eric Laurentbfb1b832013-01-07 09:53:42 -08005690ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005691{
5692 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005693 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005694 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005695 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005696 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005697}
5698
5699void AudioFlinger::DuplicatingThread::threadLoop_standby()
5700{
5701 // DuplicatingThread implements standby by stopping all tracks
5702 for (size_t i = 0; i < outputTracks.size(); i++) {
5703 outputTracks[i]->stop();
5704 }
5705}
5706
5707void AudioFlinger::DuplicatingThread::saveOutputTracks()
5708{
5709 outputTracks = mOutputTracks;
5710}
5711
5712void AudioFlinger::DuplicatingThread::clearOutputTracks()
5713{
5714 outputTracks.clear();
5715}
5716
5717void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5718{
5719 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005720 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5721 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5722 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5723 const size_t frameCount =
5724 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5725 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5726 // from different OutputTracks and their associated MixerThreads (e.g. one may
5727 // nearly empty and the other may be dropping data).
5728
5729 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005730 this,
5731 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005732 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005733 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005734 frameCount,
5735 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005736 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5737 if (status != NO_ERROR) {
5738 ALOGE("addOutputTrack() initCheck failed %d", status);
5739 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005740 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005741 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5742 mOutputTracks.add(outputTrack);
5743 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5744 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005745}
5746
5747void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5748{
5749 Mutex::Autolock _l(mLock);
5750 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5751 if (mOutputTracks[i]->thread() == thread) {
5752 mOutputTracks[i]->destroy();
5753 mOutputTracks.removeAt(i);
5754 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005755 if (thread->getOutput() == mOutput) {
5756 mOutput = NULL;
5757 }
Eric Laurent81784c32012-11-19 14:55:58 -08005758 return;
5759 }
5760 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005761 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005762}
5763
5764// caller must hold mLock
5765void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5766{
5767 mWaitTimeMs = UINT_MAX;
5768 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5769 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5770 if (strong != 0) {
5771 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5772 if (waitTimeMs < mWaitTimeMs) {
5773 mWaitTimeMs = waitTimeMs;
5774 }
5775 }
5776 }
5777}
5778
5779
5780bool AudioFlinger::DuplicatingThread::outputsReady(
5781 const SortedVector< sp<OutputTrack> > &outputTracks)
5782{
5783 for (size_t i = 0; i < outputTracks.size(); i++) {
5784 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5785 if (thread == 0) {
5786 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5787 outputTracks[i].get());
5788 return false;
5789 }
5790 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5791 // see note at standby() declaration
5792 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5793 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5794 thread.get());
5795 return false;
5796 }
5797 }
5798 return true;
5799}
5800
5801uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5802{
5803 return (mWaitTimeMs * 1000) / 2;
5804}
5805
5806void AudioFlinger::DuplicatingThread::cacheParameters_l()
5807{
5808 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5809 updateWaitTime_l();
5810
5811 MixerThread::cacheParameters_l();
5812}
5813
5814// ----------------------------------------------------------------------------
5815// Record
5816// ----------------------------------------------------------------------------
5817
5818AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5819 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005820 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005821 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005822 audio_devices_t inDevice,
5823 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005824#ifdef TEE_SINK
5825 , const sp<NBAIO_Sink>& teeSink
5826#endif
5827 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005828 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005829 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005830 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005831 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005832#ifdef TEE_SINK
5833 , mTeeSink(teeSink)
5834#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005835 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5836 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005837 // mFastCapture below
5838 , mFastCaptureFutex(0)
5839 // mInputSource
5840 // mPipeSink
5841 // mPipeSource
5842 , mPipeFramesP2(0)
5843 // mPipeMemory
5844 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005845 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005846{
Glenn Kastend7dca052015-03-05 16:05:54 -08005847 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5848 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005849
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005850 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005851
5852 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005853 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005854 size_t numCounterOffers = 0;
5855 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005856#if !LOG_NDEBUG
5857 ssize_t index =
5858#else
5859 (void)
5860#endif
5861 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005862 ALOG_ASSERT(index == 0);
5863
5864 // initialize fast capture depending on configuration
5865 bool initFastCapture;
5866 switch (kUseFastCapture) {
5867 case FastCapture_Never:
5868 initFastCapture = false;
5869 break;
5870 case FastCapture_Always:
5871 initFastCapture = true;
5872 break;
5873 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005874 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005875 break;
5876 // case FastCapture_Dynamic:
5877 }
5878
5879 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005880 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005881 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005882 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5883 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005884 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5885 void *pipeBuffer;
5886 const sp<MemoryDealer> roHeap(readOnlyHeap());
5887 sp<IMemory> pipeMemory;
5888 if ((roHeap == 0) ||
5889 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5890 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5891 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5892 goto failed;
5893 }
5894 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5895 memset(pipeBuffer, 0, pipeSize);
5896 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5897 const NBAIO_Format offers[1] = {format};
5898 size_t numCounterOffers = 0;
5899 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5900 ALOG_ASSERT(index == 0);
5901 mPipeSink = pipe;
5902 PipeReader *pipeReader = new PipeReader(*pipe);
5903 numCounterOffers = 0;
5904 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5905 ALOG_ASSERT(index == 0);
5906 mPipeSource = pipeReader;
5907 mPipeFramesP2 = pipeFramesP2;
5908 mPipeMemory = pipeMemory;
5909
5910 // create fast capture
5911 mFastCapture = new FastCapture();
5912 FastCaptureStateQueue *sq = mFastCapture->sq();
5913#ifdef STATE_QUEUE_DUMP
5914 // FIXME
5915#endif
5916 FastCaptureState *state = sq->begin();
5917 state->mCblk = NULL;
5918 state->mInputSource = mInputSource.get();
5919 state->mInputSourceGen++;
5920 state->mPipeSink = pipe;
5921 state->mPipeSinkGen++;
5922 state->mFrameCount = mFrameCount;
5923 state->mCommand = FastCaptureState::COLD_IDLE;
5924 // already done in constructor initialization list
5925 //mFastCaptureFutex = 0;
5926 state->mColdFutexAddr = &mFastCaptureFutex;
5927 state->mColdGen++;
5928 state->mDumpState = &mFastCaptureDumpState;
5929#ifdef TEE_SINK
5930 // FIXME
5931#endif
5932 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5933 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5934 sq->end();
5935 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5936
5937 // start the fast capture
5938 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5939 pid_t tid = mFastCapture->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08005940 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005941 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005942#ifdef AUDIO_WATCHDOG
5943 // FIXME
5944#endif
5945
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005946 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005947 }
5948failed: ;
5949
5950 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005951}
5952
Eric Laurent81784c32012-11-19 14:55:58 -08005953AudioFlinger::RecordThread::~RecordThread()
5954{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005955 if (mFastCapture != 0) {
5956 FastCaptureStateQueue *sq = mFastCapture->sq();
5957 FastCaptureState *state = sq->begin();
5958 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5959 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5960 if (old == -1) {
5961 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5962 }
5963 }
5964 state->mCommand = FastCaptureState::EXIT;
5965 sq->end();
5966 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5967 mFastCapture->join();
5968 mFastCapture.clear();
5969 }
5970 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005971 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005972 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005973}
5974
5975void AudioFlinger::RecordThread::onFirstRef()
5976{
Glenn Kastend7dca052015-03-05 16:05:54 -08005977 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005978}
5979
Eric Laurent81784c32012-11-19 14:55:58 -08005980bool AudioFlinger::RecordThread::threadLoop()
5981{
Eric Laurent81784c32012-11-19 14:55:58 -08005982 nsecs_t lastWarning = 0;
5983
5984 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005985
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005986reacquire_wakelock:
5987 sp<RecordTrack> activeTrack;
5988 {
5989 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07005990 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005991 }
5992
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005993 // used to request a deferred sleep, to be executed later while mutex is unlocked
5994 uint32_t sleepUs = 0;
5995
5996 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005997 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005998 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005999
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006000 // activeTracks accumulates a copy of a subset of mActiveTracks
6001 Vector< sp<RecordTrack> > activeTracks;
6002
Glenn Kasten735f45f2014-08-18 15:51:59 -07006003 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006004 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006005
Glenn Kasten735f45f2014-08-18 15:51:59 -07006006 // reference to a fast track which is about to be removed
6007 sp<RecordTrack> fastTrackToRemove;
6008
Eric Laurent81784c32012-11-19 14:55:58 -08006009 { // scope for mLock
6010 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006011
Eric Laurent021cf962014-05-13 10:18:14 -07006012 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006013
Eric Laurent000a4192014-01-29 15:17:32 -08006014 // check exitPending here because checkForNewParameters_l() and
6015 // checkForNewParameters_l() can temporarily release mLock
6016 if (exitPending()) {
6017 break;
6018 }
6019
Eric Laurent5c25d562016-07-13 17:17:45 -07006020 // sleep with mutex unlocked
6021 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006022 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006023 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6024 ATRACE_END();
6025 sleepUs = 0;
6026 continue;
6027 }
6028
Glenn Kasten2b806402013-11-20 16:37:38 -08006029 // if no active track(s), then standby and release wakelock
6030 size_t size = mActiveTracks.size();
6031 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006032 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006033 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006034 releaseWakeLock_l();
6035 ALOGV("RecordThread: loop stopping");
6036 // go to sleep
6037 mWaitWorkCV.wait(mLock);
6038 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006039 goto reacquire_wakelock;
6040 }
6041
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006042 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006043 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006044 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006045
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006046 activeTrack = mActiveTracks[i];
6047 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006048 if (activeTrack->isFastTrack()) {
6049 ALOG_ASSERT(fastTrackToRemove == 0);
6050 fastTrackToRemove = activeTrack;
6051 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006052 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006053 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006054 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006055 continue;
6056 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006057
6058 TrackBase::track_state activeTrackState = activeTrack->mState;
6059 switch (activeTrackState) {
6060
6061 case TrackBase::PAUSING:
6062 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006063 doBroadcast = true;
6064 size--;
6065 continue;
6066
6067 case TrackBase::STARTING_1:
6068 sleepUs = 10000;
6069 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006070 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006071 continue;
6072
6073 case TrackBase::STARTING_2:
6074 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006075 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006076 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006077 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006078 break;
6079
6080 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006081 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006082 break;
6083
6084 case TrackBase::IDLE:
6085 i++;
6086 continue;
6087
6088 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006089 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006090 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006091
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006092 activeTracks.add(activeTrack);
6093 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006094
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006095 if (activeTrack->isFastTrack()) {
6096 ALOG_ASSERT(!mFastTrackAvail);
6097 ALOG_ASSERT(fastTrack == 0);
6098 fastTrack = activeTrack;
6099 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006100 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006101
Andy Hungdae27702016-10-31 14:01:16 -07006102 mActiveTracks.updatePowerState(this);
6103
Eric Laurent5c25d562016-07-13 17:17:45 -07006104 if (allStopped) {
6105 standbyIfNotAlreadyInStandby();
6106 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006107 if (doBroadcast) {
6108 mStartStopCond.broadcast();
6109 }
6110
6111 // sleep if there are no active tracks to process
6112 if (activeTracks.size() == 0) {
6113 if (sleepUs == 0) {
6114 sleepUs = kRecordThreadSleepUs;
6115 }
6116 continue;
6117 }
6118 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006119
Eric Laurent81784c32012-11-19 14:55:58 -08006120 lockEffectChains_l(effectChains);
6121 }
6122
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006124
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006125 size_t size = effectChains.size();
6126 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006127 // thread mutex is not locked, but effect chain is locked
6128 effectChains[i]->process_l();
6129 }
6130
Glenn Kasten735f45f2014-08-18 15:51:59 -07006131 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006132 if (mFastCapture != 0) {
6133 FastCaptureStateQueue *sq = mFastCapture->sq();
6134 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006135 bool didModify = false;
6136 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006137 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6138 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6139 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6140 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6141 if (old == -1) {
6142 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6143 }
6144 }
6145 state->mCommand = FastCaptureState::READ_WRITE;
6146#if 0 // FIXME
6147 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006148 FastThreadDumpState::kSamplingNforLowRamDevice :
6149 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006150#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006151 didModify = true;
6152 }
6153 audio_track_cblk_t *cblkOld = state->mCblk;
6154 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6155 if (cblkNew != cblkOld) {
6156 state->mCblk = cblkNew;
6157 // block until acked if removing a fast track
6158 if (cblkOld != NULL) {
6159 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6160 }
6161 didModify = true;
6162 }
6163 sq->end(didModify);
6164 if (didModify) {
6165 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006166#if 0
6167 if (kUseFastCapture == FastCapture_Dynamic) {
6168 mNormalSource = mPipeSource;
6169 }
6170#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006171 }
6172 }
6173
Glenn Kasten735f45f2014-08-18 15:51:59 -07006174 // now run the fast track destructor with thread mutex unlocked
6175 fastTrackToRemove.clear();
6176
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006177 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6178 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6179 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6180 // If destination is non-contiguous, first read past the nominal end of buffer, then
6181 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006182
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006183 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006184 ssize_t framesRead;
6185
6186 // If an NBAIO source is present, use it to read the normal capture's data
6187 if (mPipeSource != 0) {
6188 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006189 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006190 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006191 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006192 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6193 // buffer size or at least for 20ms.
6194 size_t sleepFrames = max(
6195 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6196 if (framesRead <= (ssize_t) sleepFrames) {
6197 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6198 }
6199 if (framesRead < 0) {
6200 status_t status = (status_t) framesRead;
6201 switch (status) {
6202 case OVERRUN:
6203 ALOGW("overrun on read from pipe");
6204 framesRead = 0;
6205 break;
6206 case NEGOTIATE:
6207 ALOGE("re-negotiation is needed");
6208 framesRead = -1; // Will cause an attempt to recover.
6209 break;
6210 default:
6211 ALOGE("unknown error %d on read from pipe", status);
6212 break;
6213 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006214 }
6215 // otherwise use the HAL / AudioStreamIn directly
6216 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006217 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006218 size_t bytesRead;
6219 status_t result = mInput->stream->read(
6220 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006221 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006222 if (result < 0) {
6223 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006224 } else {
6225 framesRead = bytesRead / mFrameSize;
6226 }
6227 }
6228
Andy Hung3f0c9022016-01-15 17:49:46 -08006229 // Update server timestamp with server stats
6230 // systemTime() is optional if the hardware supports timestamps.
6231 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6232 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6233
6234 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006235 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006236 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006237 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006238 if (ret == NO_ERROR) {
6239 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6240 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6241 // Note: In general record buffers should tend to be empty in
6242 // a properly running pipeline.
6243 //
6244 // Also, it is not advantageous to call get_presentation_position during the read
6245 // as the read obtains a lock, preventing the timestamp call from executing.
6246 }
6247 }
6248 // Use this to track timestamp information
6249 // ALOGD("%s", mTimestamp.toString().c_str());
6250
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006251 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006252 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006253 // Force input into standby so that it tries to recover at next read attempt
6254 inputStandBy();
6255 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006256 }
6257 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006258 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006259 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006260 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006261
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006262 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006263 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006264 }
6265 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006266 {
6267 size_t part1 = mRsmpInFramesP2 - rear;
6268 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006269 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006270 (framesRead - part1) * mFrameSize);
6271 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006272 }
6273 rear = mRsmpInRear += framesRead;
6274
6275 size = activeTracks.size();
6276 // loop over each active track
6277 for (size_t i = 0; i < size; i++) {
6278 activeTrack = activeTracks[i];
6279
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006280 // skip fast tracks, as those are handled directly by FastCapture
6281 if (activeTrack->isFastTrack()) {
6282 continue;
6283 }
6284
Andy Hung73c02e42015-03-29 01:13:58 -07006285 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006286 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6287
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006288 enum {
6289 OVERRUN_UNKNOWN,
6290 OVERRUN_TRUE,
6291 OVERRUN_FALSE
6292 } overrun = OVERRUN_UNKNOWN;
6293
6294 // loop over getNextBuffer to handle circular sink
6295 for (;;) {
6296
6297 activeTrack->mSink.frameCount = ~0;
6298 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6299 size_t framesOut = activeTrack->mSink.frameCount;
6300 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6301
Andy Hung73c02e42015-03-29 01:13:58 -07006302 // check available frames and handle overrun conditions
6303 // if the record track isn't draining fast enough.
6304 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006305 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006306 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6307 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006308 overrun = OVERRUN_TRUE;
6309 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006310 if (framesOut == 0 || framesIn == 0) {
6311 break;
6312 }
6313
Andy Hung6770c6f2015-04-07 13:43:36 -07006314 // Don't allow framesOut to be larger than what is possible with resampling
6315 // from framesIn.
6316 // This isn't strictly necessary but helps limit buffer resizing in
6317 // RecordBufferConverter. TODO: remove when no longer needed.
6318 framesOut = min(framesOut,
6319 destinationFramesPossible(
6320 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006321 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6322 framesOut = activeTrack->mRecordBufferConverter->convert(
6323 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006324
6325 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6326 overrun = OVERRUN_FALSE;
6327 }
6328
6329 if (activeTrack->mFramesToDrop == 0) {
6330 if (framesOut > 0) {
6331 activeTrack->mSink.frameCount = framesOut;
6332 activeTrack->releaseBuffer(&activeTrack->mSink);
6333 }
6334 } else {
6335 // FIXME could do a partial drop of framesOut
6336 if (activeTrack->mFramesToDrop > 0) {
6337 activeTrack->mFramesToDrop -= framesOut;
6338 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006339 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006340 }
6341 } else {
6342 activeTrack->mFramesToDrop += framesOut;
6343 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6344 activeTrack->mSyncStartEvent->isCancelled()) {
6345 ALOGW("Synced record %s, session %d, trigger session %d",
6346 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6347 activeTrack->sessionId(),
6348 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006349 activeTrack->mSyncStartEvent->triggerSession() :
6350 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006351 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006352 }
6353 }
6354 }
6355
6356 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006357 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006358 }
6359 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006360
6361 switch (overrun) {
6362 case OVERRUN_TRUE:
6363 // client isn't retrieving buffers fast enough
6364 if (!activeTrack->setOverflow()) {
6365 nsecs_t now = systemTime();
6366 // FIXME should lastWarning per track?
6367 if ((now - lastWarning) > kWarningThrottleNs) {
6368 ALOGW("RecordThread: buffer overflow");
6369 lastWarning = now;
6370 }
6371 }
6372 break;
6373 case OVERRUN_FALSE:
6374 activeTrack->clearOverflow();
6375 break;
6376 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006377 break;
6378 }
6379
Andy Hung3f0c9022016-01-15 17:49:46 -08006380 // update frame information and push timestamp out
6381 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006382 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006383 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6384 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006385 }
6386
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006387unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006388 // enable changes in effect chain
6389 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006390 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006391 }
6392
Glenn Kasten93e471f2013-08-19 08:40:07 -07006393 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006394
6395 {
6396 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006397 for (size_t i = 0; i < mTracks.size(); i++) {
6398 sp<RecordTrack> track = mTracks[i];
6399 track->invalidate();
6400 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006401 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006402 mStartStopCond.broadcast();
6403 }
6404
6405 releaseWakeLock();
6406
6407 ALOGV("RecordThread %p exiting", this);
6408 return false;
6409}
6410
Glenn Kasten93e471f2013-08-19 08:40:07 -07006411void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006412{
6413 if (!mStandby) {
6414 inputStandBy();
6415 mStandby = true;
6416 }
6417}
6418
6419void AudioFlinger::RecordThread::inputStandBy()
6420{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006421 // Idle the fast capture if it's currently running
6422 if (mFastCapture != 0) {
6423 FastCaptureStateQueue *sq = mFastCapture->sq();
6424 FastCaptureState *state = sq->begin();
6425 if (!(state->mCommand & FastCaptureState::IDLE)) {
6426 state->mCommand = FastCaptureState::COLD_IDLE;
6427 state->mColdFutexAddr = &mFastCaptureFutex;
6428 state->mColdGen++;
6429 mFastCaptureFutex = 0;
6430 sq->end();
6431 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6432 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6433#if 0
6434 if (kUseFastCapture == FastCapture_Dynamic) {
6435 // FIXME
6436 }
6437#endif
6438#ifdef AUDIO_WATCHDOG
6439 // FIXME
6440#endif
6441 } else {
6442 sq->end(false /*didModify*/);
6443 }
6444 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006445 status_t result = mInput->stream->standby();
6446 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006447
6448 // If going into standby, flush the pipe source.
6449 if (mPipeSource.get() != nullptr) {
6450 const ssize_t flushed = mPipeSource->flush();
6451 if (flushed > 0) {
6452 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6453 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6454 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6455 }
6456 }
Eric Laurent81784c32012-11-19 14:55:58 -08006457}
6458
Glenn Kasten05997e22014-03-13 15:08:33 -07006459// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006460sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006461 const sp<AudioFlinger::Client>& client,
6462 uint32_t sampleRate,
6463 audio_format_t format,
6464 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006465 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006466 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006467 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006468 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006469 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006470 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006471 status_t *status,
6472 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006473{
Glenn Kasten74935e42013-12-19 08:56:45 -08006474 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006475 sp<RecordTrack> track;
6476 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006477 audio_input_flags_t inputFlags = mInput->flags;
6478
6479 // special case for FAST flag considered OK if fast capture is present
6480 if (hasFastCapture()) {
6481 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6482 }
6483
6484 // Check if requested flags are compatible with output stream flags
6485 if ((*flags & inputFlags) != *flags) {
6486 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6487 " input flags (%08x)",
6488 *flags, inputFlags);
6489 *flags = (audio_input_flags_t)(*flags & inputFlags);
6490 }
Eric Laurent81784c32012-11-19 14:55:58 -08006491
Glenn Kasten90e58b12013-07-31 16:16:02 -07006492 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006493 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006494 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006495 // we formerly checked for a callback handler (non-0 tid),
6496 // but that is no longer required for TRANSFER_OBTAIN mode
6497 //
Glenn Kasten74105912014-07-03 12:28:53 -07006498 // frame count is not specified, or is exactly the pipe depth
6499 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006500 // PCM data
6501 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006502 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006503 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006504 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006505 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006506 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006507 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006508 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006509 hasFastCapture() &&
6510 // there are sufficient fast track slots available
6511 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006512 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006513 // check compatibility with audio effects.
6514 Mutex::Autolock _l(mLock);
6515 // Do not accept FAST flag if the session has software effects
6516 sp<EffectChain> chain = getEffectChain_l(sessionId);
6517 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006518 audio_input_flags_t old = *flags;
6519 chain->checkInputFlagCompatibility(flags);
6520 if (old != *flags) {
6521 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6522 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006523 }
6524 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006525 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006526 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6527 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006528 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006529 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006530 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006531 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006532 frameCount, mFrameCount, mPipeFramesP2,
6533 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6534 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006535 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006536 }
6537 }
6538
6539 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006540 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006541 // fast track: frame count is exactly the pipe depth
6542 frameCount = mPipeFramesP2;
6543 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6544 *notificationFrames = mFrameCount;
6545 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006546 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6547 // or 20 ms if there is a fast capture
6548 // TODO This could be a roundupRatio inline, and const
6549 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6550 * sampleRate + mSampleRate - 1) / mSampleRate;
6551 // minimum number of notification periods is at least kMinNotifications,
6552 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6553 static const size_t kMinNotifications = 3;
6554 static const uint32_t kMinMs = 30;
6555 // TODO This could be a roundupRatio inline
6556 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6557 // TODO This could be a roundupRatio inline
6558 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6559 maxNotificationFrames;
6560 const size_t minFrameCount = maxNotificationFrames *
6561 max(kMinNotifications, minNotificationsByMs);
6562 frameCount = max(frameCount, minFrameCount);
6563 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6564 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006565 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006566 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006567 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006568
Glenn Kasten15e57982013-09-24 11:52:37 -07006569 lStatus = initCheck();
6570 if (lStatus != NO_ERROR) {
6571 ALOGE("createRecordTrack_l() audio driver not initialized");
6572 goto Exit;
6573 }
Eric Laurent81784c32012-11-19 14:55:58 -08006574
6575 { // scope for mLock
6576 Mutex::Autolock _l(mLock);
6577
6578 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006579 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006580 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006581
Glenn Kasten03003332013-08-06 15:40:54 -07006582 lStatus = track->initCheck();
6583 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006584 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006585 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006586 goto Exit;
6587 }
6588 mTracks.add(track);
6589
6590 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6591 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6592 mAudioFlinger->btNrecIsOff();
6593 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6594 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006595
Eric Laurent05067782016-06-01 18:27:28 -07006596 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006597 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6598 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6599 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08006600 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006601 }
Eric Laurent81784c32012-11-19 14:55:58 -08006602 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006603
Eric Laurent81784c32012-11-19 14:55:58 -08006604 lStatus = NO_ERROR;
6605
6606Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006607 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006608 return track;
6609}
6610
6611status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6612 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006613 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006614{
6615 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6616 sp<ThreadBase> strongMe = this;
6617 status_t status = NO_ERROR;
6618
6619 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006620 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006621 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006622 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006623 triggerSession,
6624 recordTrack->sessionId(),
6625 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006626 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006627 // Sync event can be cancelled by the trigger session if the track is not in a
6628 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006629 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006630 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006631 } else {
6632 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006633 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006634 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006635 }
6636 }
6637
6638 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006639 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006640 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006641 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6642 if (recordTrack->mState == TrackBase::PAUSING) {
6643 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006644 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006645 } else {
6646 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006647 }
6648 return status;
6649 }
6650
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006651 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6652 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6653 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006654 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006655 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006656 status_t status = NO_ERROR;
6657 if (recordTrack->isExternalTrack()) {
6658 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006659 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006660 mLock.lock();
6661 // FIXME should verify that recordTrack is still in mActiveTracks
6662 if (status != NO_ERROR) {
6663 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006664 recordTrack->clearSyncStartEvent();
6665 ALOGV("RecordThread::start error %d", status);
6666 return status;
6667 }
Eric Laurent81784c32012-11-19 14:55:58 -08006668 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006669 // Catch up with current buffer indices if thread is already running.
6670 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6671 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6672 // see previously buffered data before it called start(), but with greater risk of overrun.
6673
Andy Hung73c02e42015-03-29 01:13:58 -07006674 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006675 // clear any converter state as new data will be discontinuous
6676 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006677 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006678 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006679 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006680 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006681 ALOGV("Record failed to start");
6682 status = BAD_VALUE;
6683 goto startError;
6684 }
Eric Laurent81784c32012-11-19 14:55:58 -08006685 return status;
6686 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006687
Eric Laurent81784c32012-11-19 14:55:58 -08006688startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006689 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006690 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006691 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006692 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006693 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006694 return status;
6695}
6696
Eric Laurent81784c32012-11-19 14:55:58 -08006697void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6698{
6699 sp<SyncEvent> strongEvent = event.promote();
6700
6701 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006702 sp<RefBase> ptr = strongEvent->cookie().promote();
6703 if (ptr != 0) {
6704 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6705 recordTrack->handleSyncStartEvent(strongEvent);
6706 }
Eric Laurent81784c32012-11-19 14:55:58 -08006707 }
6708}
6709
Glenn Kastena8356f62013-07-25 14:37:52 -07006710bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006711 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006712 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006713 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006714 return false;
6715 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006716 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006717 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006718 // signal thread to stop
6719 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006720 // do not wait for mStartStopCond if exiting
6721 if (exitPending()) {
6722 return true;
6723 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006724 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006725 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006726 // if we have been restarted, recordTrack is in mActiveTracks here
6727 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006728 ALOGV("Record stopped OK");
6729 return true;
6730 }
6731 return false;
6732}
6733
Glenn Kasten0f11b512014-01-31 16:18:54 -08006734bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006735{
6736 return false;
6737}
6738
Glenn Kasten0f11b512014-01-31 16:18:54 -08006739status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006740{
6741#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6742 if (!isValidSyncEvent(event)) {
6743 return BAD_VALUE;
6744 }
6745
Glenn Kastend848eb42016-03-08 13:42:11 -08006746 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006747 status_t ret = NAME_NOT_FOUND;
6748
6749 Mutex::Autolock _l(mLock);
6750
6751 for (size_t i = 0; i < mTracks.size(); i++) {
6752 sp<RecordTrack> track = mTracks[i];
6753 if (eventSession == track->sessionId()) {
6754 (void) track->setSyncEvent(event);
6755 ret = NO_ERROR;
6756 }
6757 }
6758 return ret;
6759#else
6760 return BAD_VALUE;
6761#endif
6762}
6763
6764// destroyTrack_l() must be called with ThreadBase::mLock held
6765void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6766{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006767 track->terminate();
6768 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006769 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006770 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006771 removeTrack_l(track);
6772 }
6773}
6774
6775void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6776{
6777 mTracks.remove(track);
6778 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006779 if (track->isFastTrack()) {
6780 ALOG_ASSERT(!mFastTrackAvail);
6781 mFastTrackAvail = true;
6782 }
Eric Laurent81784c32012-11-19 14:55:58 -08006783}
6784
6785void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6786{
6787 dumpInternals(fd, args);
6788 dumpTracks(fd, args);
6789 dumpEffectChains(fd, args);
6790}
6791
6792void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6793{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006794 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006795
Glenn Kasten44182c22015-03-05 17:12:23 -08006796 dumpBase(fd, args);
6797
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006798 AudioStreamIn *input = mInput;
6799 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6800 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6801 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006802 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006803 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006804 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006805 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006806 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006807
Glenn Kasten2f90c512015-12-02 11:40:09 -08006808 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6809 // while we are dumping it. It may be inconsistent, but it won't mutate!
6810 // This is a large object so we place it on the heap.
6811 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6812 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6813 copy->dump(fd);
6814 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006815}
6816
Glenn Kasten0f11b512014-01-31 16:18:54 -08006817void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006818{
6819 const size_t SIZE = 256;
6820 char buffer[SIZE];
6821 String8 result;
6822
Marco Nelissenb2208842014-02-07 14:00:50 -08006823 size_t numtracks = mTracks.size();
6824 size_t numactive = mActiveTracks.size();
6825 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006826 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006827 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006828 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006829 RecordTrack::appendDumpHeader(result);
6830 for (size_t i = 0; i < numtracks ; ++i) {
6831 sp<RecordTrack> track = mTracks[i];
6832 if (track != 0) {
6833 bool active = mActiveTracks.indexOf(track) >= 0;
6834 if (active) {
6835 numactiveseen++;
6836 }
6837 track->dump(buffer, SIZE, active);
6838 result.append(buffer);
6839 }
Eric Laurent81784c32012-11-19 14:55:58 -08006840 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006841 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006842 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006843 }
6844
Marco Nelissenb2208842014-02-07 14:00:50 -08006845 if (numactiveseen != numactive) {
6846 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6847 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006848 result.append(buffer);
6849 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006850 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006851 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006852 if (mTracks.indexOf(track) < 0) {
6853 track->dump(buffer, SIZE, true);
6854 result.append(buffer);
6855 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006856 }
Eric Laurent81784c32012-11-19 14:55:58 -08006857
6858 }
6859 write(fd, result.string(), result.size());
6860}
6861
Andy Hung73c02e42015-03-29 01:13:58 -07006862
6863void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6864{
6865 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6866 RecordThread *recordThread = (RecordThread *) threadBase.get();
6867 mRsmpInFront = recordThread->mRsmpInRear;
6868 mRsmpInUnrel = 0;
6869}
6870
6871void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6872 size_t *framesAvailable, bool *hasOverrun)
6873{
6874 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6875 RecordThread *recordThread = (RecordThread *) threadBase.get();
6876 const int32_t rear = recordThread->mRsmpInRear;
6877 const int32_t front = mRsmpInFront;
6878 const ssize_t filled = rear - front;
6879
6880 size_t framesIn;
6881 bool overrun = false;
6882 if (filled < 0) {
6883 // should not happen, but treat like a massive overrun and re-sync
6884 framesIn = 0;
6885 mRsmpInFront = rear;
6886 overrun = true;
6887 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6888 framesIn = (size_t) filled;
6889 } else {
6890 // client is not keeping up with server, but give it latest data
6891 framesIn = recordThread->mRsmpInFrames;
6892 mRsmpInFront = /* front = */ rear - framesIn;
6893 overrun = true;
6894 }
6895 if (framesAvailable != NULL) {
6896 *framesAvailable = framesIn;
6897 }
6898 if (hasOverrun != NULL) {
6899 *hasOverrun = overrun;
6900 }
6901}
6902
Eric Laurent81784c32012-11-19 14:55:58 -08006903// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006904status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006905 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006906{
Andy Hung73c02e42015-03-29 01:13:58 -07006907 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006908 if (threadBase == 0) {
6909 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006910 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006911 return NOT_ENOUGH_DATA;
6912 }
6913 RecordThread *recordThread = (RecordThread *) threadBase.get();
6914 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006915 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006916 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006917 // FIXME should not be P2 (don't want to increase latency)
6918 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006919 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006920 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006921 front &= recordThread->mRsmpInFramesP2 - 1;
6922 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006923 if (part1 > (size_t) filled) {
6924 part1 = filled;
6925 }
6926 size_t ask = buffer->frameCount;
6927 ALOG_ASSERT(ask > 0);
6928 if (part1 > ask) {
6929 part1 = ask;
6930 }
6931 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006932 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006933 buffer->raw = NULL;
6934 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006935 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006936 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006937 }
6938
Andy Hung57446612015-04-19 23:56:46 -07006939 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006940 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006941 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006942 return NO_ERROR;
6943}
6944
6945// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006946void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6947 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006948{
Glenn Kasten85948432013-08-19 12:09:05 -07006949 size_t stepCount = buffer->frameCount;
6950 if (stepCount == 0) {
6951 return;
6952 }
Andy Hung73c02e42015-03-29 01:13:58 -07006953 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6954 mRsmpInUnrel -= stepCount;
6955 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006956 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006957 buffer->frameCount = 0;
6958}
6959
Andy Hung97a893e2015-03-29 01:03:07 -07006960
Eric Laurent10351942014-05-08 18:49:52 -07006961bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6962 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006963{
6964 bool reconfig = false;
6965
Eric Laurent10351942014-05-08 18:49:52 -07006966 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006967
Eric Laurent10351942014-05-08 18:49:52 -07006968 audio_format_t reqFormat = mFormat;
6969 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006970 // 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 -07006971 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6972
6973 AudioParameter param = AudioParameter(keyValuePair);
6974 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07006975
6976 // scope for AutoPark extends to end of method
6977 AutoPark<FastCapture> park(mFastCapture);
6978
Eric Laurent10351942014-05-08 18:49:52 -07006979 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6980 // channel count change can be requested. Do we mandate the first client defines the
6981 // HAL sampling rate and channel count or do we allow changes on the fly?
6982 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6983 samplingRate = value;
6984 reconfig = true;
6985 }
6986 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006987 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006988 status = BAD_VALUE;
6989 } else {
6990 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006991 reconfig = true;
6992 }
Eric Laurent10351942014-05-08 18:49:52 -07006993 }
6994 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6995 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006996 if (!audio_is_input_channel(mask) ||
6997 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006998 status = BAD_VALUE;
6999 } else {
7000 channelMask = mask;
7001 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007002 }
Eric Laurent10351942014-05-08 18:49:52 -07007003 }
7004 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7005 // do not accept frame count changes if tracks are open as the track buffer
7006 // size depends on frame count and correct behavior would not be guaranteed
7007 // if frame count is changed after track creation
7008 if (mActiveTracks.size() > 0) {
7009 status = INVALID_OPERATION;
7010 } else {
7011 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007012 }
Eric Laurent10351942014-05-08 18:49:52 -07007013 }
7014 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7015 // forward device change to effects that have requested to be
7016 // aware of attached audio device.
7017 for (size_t i = 0; i < mEffectChains.size(); i++) {
7018 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007019 }
Eric Laurent81784c32012-11-19 14:55:58 -08007020
Eric Laurent10351942014-05-08 18:49:52 -07007021 // store input device and output device but do not forward output device to audio HAL.
7022 // Note that status is ignored by the caller for output device
7023 // (see AudioFlinger::setParameters()
7024 if (audio_is_output_devices(value)) {
7025 mOutDevice = value;
7026 status = BAD_VALUE;
7027 } else {
7028 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007029 if (value != AUDIO_DEVICE_NONE) {
7030 mPrevInDevice = value;
7031 }
Eric Laurent10351942014-05-08 18:49:52 -07007032 // disable AEC and NS if the device is a BT SCO headset supporting those
7033 // pre processings
7034 if (mTracks.size() > 0) {
7035 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7036 mAudioFlinger->btNrecIsOff();
7037 for (size_t i = 0; i < mTracks.size(); i++) {
7038 sp<RecordTrack> track = mTracks[i];
7039 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7040 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007041 }
7042 }
7043 }
Eric Laurent10351942014-05-08 18:49:52 -07007044 }
7045 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7046 mAudioSource != (audio_source_t)value) {
7047 // forward device change to effects that have requested to be
7048 // aware of attached audio device.
7049 for (size_t i = 0; i < mEffectChains.size(); i++) {
7050 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007051 }
Eric Laurent10351942014-05-08 18:49:52 -07007052 mAudioSource = (audio_source_t)value;
7053 }
Glenn Kastene198c362013-08-13 09:13:36 -07007054
Eric Laurent10351942014-05-08 18:49:52 -07007055 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007056 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007057 if (status == INVALID_OPERATION) {
7058 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007059 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007060 }
7061 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007062 if (status == BAD_VALUE) {
7063 uint32_t sRate;
7064 audio_channel_mask_t channelMask;
7065 audio_format_t format;
7066 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7067 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7068 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7069 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7070 status = NO_ERROR;
7071 }
Eric Laurent81784c32012-11-19 14:55:58 -08007072 }
Eric Laurent10351942014-05-08 18:49:52 -07007073 if (status == NO_ERROR) {
7074 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007075 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007076 }
7077 }
Eric Laurent81784c32012-11-19 14:55:58 -08007078 }
Eric Laurent10351942014-05-08 18:49:52 -07007079
Eric Laurent81784c32012-11-19 14:55:58 -08007080 return reconfig;
7081}
7082
7083String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7084{
Eric Laurent81784c32012-11-19 14:55:58 -08007085 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007086 if (initCheck() == NO_ERROR) {
7087 String8 out_s8;
7088 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7089 return out_s8;
7090 }
Eric Laurent81784c32012-11-19 14:55:58 -08007091 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007092 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007093}
7094
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007095void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007096 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7097
7098 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007099
7100 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007101 case AUDIO_INPUT_OPENED:
7102 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007103 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007104 desc->mChannelMask = mChannelMask;
7105 desc->mSamplingRate = mSampleRate;
7106 desc->mFormat = mFormat;
7107 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007108 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007109 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007110 break;
7111
Eric Laurent73e26b62015-04-27 16:55:58 -07007112 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007113 default:
7114 break;
7115 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007116 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007117}
7118
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007119void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007120{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007121 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7122 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007123 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007124 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007125 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007126 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7127 result = mInput->stream->getFrameSize(&mFrameSize);
7128 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7129 result = mInput->stream->getBufferSize(&mBufferSize);
7130 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007131 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007132 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007133 // 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 -07007134 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007135 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007136 // A larger value should allow more old data to be read after a track calls start(),
7137 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007138 //
7139 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007140 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007141 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007142 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007143 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007144
7145 // TODO optimize audio capture buffer sizes ...
7146 // Here we calculate the size of the sliding buffer used as a source
7147 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7148 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7149 // be better to have it derived from the pipe depth in the long term.
7150 // The current value is higher than necessary. However it should not add to latency.
7151
Glenn Kasten85948432013-08-19 12:09:05 -07007152 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007153 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7154 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7155 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007156
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007157 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7158 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007159}
7160
Glenn Kasten5f972c02014-01-13 09:59:31 -08007161uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007162{
7163 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007164 uint32_t result;
7165 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7166 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007167 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007168 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007169}
7170
Eric Laurent4c415062016-06-17 16:14:16 -07007171// hasAudioSession_l() must be called with ThreadBase::mLock held
7172uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007173{
Eric Laurent81784c32012-11-19 14:55:58 -08007174 uint32_t result = 0;
7175 if (getEffectChain_l(sessionId) != 0) {
7176 result = EFFECT_SESSION;
7177 }
7178
7179 for (size_t i = 0; i < mTracks.size(); ++i) {
7180 if (sessionId == mTracks[i]->sessionId()) {
7181 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007182 if (mTracks[i]->isFastTrack()) {
7183 result |= FAST_SESSION;
7184 }
Eric Laurent81784c32012-11-19 14:55:58 -08007185 break;
7186 }
7187 }
7188
7189 return result;
7190}
7191
Glenn Kastend848eb42016-03-08 13:42:11 -08007192KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007193{
Glenn Kastend848eb42016-03-08 13:42:11 -08007194 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007195 Mutex::Autolock _l(mLock);
7196 for (size_t j = 0; j < mTracks.size(); ++j) {
7197 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007198 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007199 if (ids.indexOfKey(sessionId) < 0) {
7200 ids.add(sessionId, true);
7201 }
7202 }
7203 return ids;
7204}
7205
7206AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7207{
7208 Mutex::Autolock _l(mLock);
7209 AudioStreamIn *input = mInput;
7210 mInput = NULL;
7211 return input;
7212}
7213
7214// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007215sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007216{
7217 if (mInput == NULL) {
7218 return NULL;
7219 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007220 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007221}
7222
7223status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7224{
7225 // only one chain per input thread
7226 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007227 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007228 return INVALID_OPERATION;
7229 }
7230 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007231 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007232 chain->setInBuffer(NULL);
7233 chain->setOutBuffer(NULL);
7234
7235 checkSuspendOnAddEffectChain_l(chain);
7236
Eric Laurent1b928682014-10-02 19:41:47 -07007237 // make sure enabled pre processing effects state is communicated to the HAL as we
7238 // just moved them to a new input stream.
7239 chain->syncHalEffectsState();
7240
Eric Laurent81784c32012-11-19 14:55:58 -08007241 mEffectChains.add(chain);
7242
7243 return NO_ERROR;
7244}
7245
7246size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7247{
7248 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7249 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007250 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007251 chain.get(), mEffectChains.size(), this);
7252 if (mEffectChains.size() == 1) {
7253 mEffectChains.removeAt(0);
7254 }
7255 return 0;
7256}
7257
Eric Laurent1c333e22014-05-20 10:48:17 -07007258status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7259 audio_patch_handle_t *handle)
7260{
7261 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007262
7263 // store new device and send to effects
7264 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007265 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007266 for (size_t i = 0; i < mEffectChains.size(); i++) {
7267 mEffectChains[i]->setDevice_l(mInDevice);
7268 }
7269
7270 // disable AEC and NS if the device is a BT SCO headset supporting those
7271 // pre processings
7272 if (mTracks.size() > 0) {
7273 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7274 mAudioFlinger->btNrecIsOff();
7275 for (size_t i = 0; i < mTracks.size(); i++) {
7276 sp<RecordTrack> track = mTracks[i];
7277 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7278 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7279 }
7280 }
7281
7282 // store new source and send to effects
7283 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7284 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007285 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007286 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007287 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007288 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007289
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007290 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007291 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7292 status = hwDevice->createAudioPatch(patch->num_sources,
7293 patch->sources,
7294 patch->num_sinks,
7295 patch->sinks,
7296 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007297 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007298 char *address;
7299 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7300 address = audio_device_address_to_parameter(
7301 patch->sources[0].ext.device.type,
7302 patch->sources[0].ext.device.address);
7303 } else {
7304 address = (char *)calloc(1, 1);
7305 }
7306 AudioParameter param = AudioParameter(String8(address));
7307 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007308 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007309 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007310 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007311 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007312 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007313 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007314 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007315
Eric Laurente8726fe2015-06-26 09:39:24 -07007316 if (mInDevice != mPrevInDevice) {
7317 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7318 mPrevInDevice = mInDevice;
7319 }
Eric Laurent296fb132015-05-01 11:38:42 -07007320
Eric Laurent1c333e22014-05-20 10:48:17 -07007321 return status;
7322}
7323
7324status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7325{
7326 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007327
7328 mInDevice = AUDIO_DEVICE_NONE;
7329
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007330 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007331 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7332 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007333 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007334 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007335 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007336 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007337 }
7338 return status;
7339}
7340
Eric Laurent83b88082014-06-20 18:31:16 -07007341void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7342{
7343 Mutex::Autolock _l(mLock);
7344 mTracks.add(record);
7345}
7346
7347void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7348{
7349 Mutex::Autolock _l(mLock);
7350 destroyTrack_l(record);
7351}
7352
7353void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7354{
7355 ThreadBase::getAudioPortConfig(config);
7356 config->role = AUDIO_PORT_ROLE_SINK;
7357 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7358 config->ext.mix.usecase.source = mAudioSource;
7359}
Eric Laurent1c333e22014-05-20 10:48:17 -07007360
Glenn Kasten63238ef2015-03-02 15:50:29 -08007361} // namespace android