blob: 3ba78817bb128cab34c14a87c6433f4faa9960ef [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080032#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070033#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080035#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036
37#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070038#include <private/android_filesystem_config.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070043#include <system/audio_effects/effect_ns.h>
44#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046
47// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070048#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <media/nbaio/AudioStreamOutSink.h>
50#include <media/nbaio/MonoPipe.h>
51#include <media/nbaio/MonoPipeReader.h>
52#include <media/nbaio/Pipe.h>
53#include <media/nbaio/PipeReader.h>
54#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080055#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57#include <powermanager/PowerManager.h>
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
Glenn Kastenc05b8d72016-03-24 09:48:17 -070075#include "AutoPark.h"
76
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080077#include <pthread.h>
78#include "TypedLogger.h"
79
Eric Laurent81784c32012-11-19 14:55:58 -080080// ----------------------------------------------------------------------------
81
82// Note: the following macro is used for extremely verbose logging message. In
83// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
84// 0; but one side effect of this is to turn all LOGV's as well. Some messages
85// are so verbose that we want to suppress them even when we have ALOG_ASSERT
86// turned on. Do not uncomment the #def below unless you really know what you
87// are doing and want to see all of the extremely verbose messages.
88//#define VERY_VERY_VERBOSE_LOGGING
89#ifdef VERY_VERY_VERBOSE_LOGGING
90#define ALOGVV ALOGV
91#else
92#define ALOGVV(a...) do { } while(0)
93#endif
94
Andy Hung6770c6f2015-04-07 13:43:36 -070095// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070097template <typename T>
98static inline T min(const T& a, const T& b)
99{
100 return a < b ? a : b;
101}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700102
Andy Hungd330ee42015-04-20 13:23:41 -0700103#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700104#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700105#endif
106
Eric Laurent81784c32012-11-19 14:55:58 -0800107namespace android {
108
109// retry counts for buffer fill timeout
110// 50 * ~20msecs = 1 second
111static const int8_t kMaxTrackRetries = 50;
112static const int8_t kMaxTrackStartupRetries = 50;
113// allow less retry attempts on direct output thread.
114// direct outputs can be a scarce resource in audio hardware and should
115// be released as quickly as possible.
116static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700117
Eric Laurent51716182016-02-29 18:00:56 -0800118
Eric Laurent81784c32012-11-19 14:55:58 -0800119
120// don't warn about blocked writes or record buffer overflows more often than this
121static const nsecs_t kWarningThrottleNs = seconds(5);
122
123// RecordThread loop sleep time upon application overrun or audio HAL read error
124static const int kRecordThreadSleepUs = 5000;
125
Eric Laurent10351942014-05-08 18:49:52 -0700126// maximum time to wait in sendConfigEvent_l() for a status to be received
127static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800128
129// minimum sleep time for the mixer thread loop when tracks are active but in underrun
130static const uint32_t kMinThreadSleepTimeUs = 5000;
131// maximum divider applied to the active sleep time in the mixer thread loop
132static const uint32_t kMaxThreadSleepTimeShift = 2;
133
Andy Hung09a50072014-02-27 14:30:47 -0800134// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700135// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800136static const uint32_t kMinNormalSinkBufferSizeMs = 20;
137// maximum normal sink buffer size
138static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800139
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700140// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
141// FIXME This should be based on experimentally observed scheduling jitter
142static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
143
Eric Laurent972a1732013-09-04 09:42:59 -0700144// Offloaded output thread standby delay: allows track transition without going to standby
145static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
146
Eric Laurent51716182016-02-29 18:00:56 -0800147// Direct output thread minimum sleep time in idle or active(underrun) state
148static const nsecs_t kDirectMinSleepTimeUs = 10000;
149
Glenn Kasten1b291842016-07-18 14:55:21 -0700150// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
151// balance between power consumption and latency, and allows threads to be scheduled reliably
152// by the CFS scheduler.
153// FIXME Express other hardcoded references to 20ms with references to this constant and move
154// it appropriately.
155#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800156
Eric Laurent81784c32012-11-19 14:55:58 -0800157// Whether to use fast mixer
158static const enum {
159 FastMixer_Never, // never initialize or use: for debugging only
160 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
161 // normal mixer multiplier is 1
162 FastMixer_Static, // initialize if needed, then use all the time if initialized,
163 // multiplier is calculated based on min & max normal mixer buffer size
164 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
165 // multiplier is calculated based on min & max normal mixer buffer size
166 // FIXME for FastMixer_Dynamic:
167 // Supporting this option will require fixing HALs that can't handle large writes.
168 // For example, one HAL implementation returns an error from a large write,
169 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
170 // We could either fix the HAL implementations, or provide a wrapper that breaks
171 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
172} kUseFastMixer = FastMixer_Static;
173
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700174// Whether to use fast capture
175static const enum {
176 FastCapture_Never, // never initialize or use: for debugging only
177 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
178 FastCapture_Static, // initialize if needed, then use all the time if initialized
179} kUseFastCapture = FastCapture_Static;
180
Eric Laurent81784c32012-11-19 14:55:58 -0800181// Priorities for requestPriority
182static const int kPriorityAudioApp = 2;
183static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700184static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800185
Glenn Kastenea38ee72016-04-18 11:08:01 -0700186// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
187// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
188// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700189
190// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800191static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800192
Glenn Kasten03490092014-05-27 12:30:54 -0700193// The minimum and maximum allowed values
194static const int kFastTrackMultiplierMin = 1;
195static const int kFastTrackMultiplierMax = 2;
196
197// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
198static int sFastTrackMultiplier = kFastTrackMultiplier;
199
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700200// See Thread::readOnlyHeap().
201// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
202// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
203// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700204static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700205
Eric Laurent81784c32012-11-19 14:55:58 -0800206// ----------------------------------------------------------------------------
207
Glenn Kasten03490092014-05-27 12:30:54 -0700208static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
209
210static void sFastTrackMultiplierInit()
211{
212 char value[PROPERTY_VALUE_MAX];
213 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
214 char *endptr;
215 unsigned long ul = strtoul(value, &endptr, 0);
216 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
217 sFastTrackMultiplier = (int) ul;
218 }
219 }
220}
221
222// ----------------------------------------------------------------------------
223
Eric Laurent81784c32012-11-19 14:55:58 -0800224#ifdef ADD_BATTERY_DATA
225// To collect the amplifier usage
226static void addBatteryData(uint32_t params) {
227 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
228 if (service == NULL) {
229 // it already logged
230 return;
231 }
232
233 service->addBatteryData(params);
234}
235#endif
236
Andy Hung3f0c9022016-01-15 17:49:46 -0800237// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
238struct {
239 // call when you acquire a partial wakelock
240 void acquire(const sp<IBinder> &wakeLockToken) {
241 pthread_mutex_lock(&mLock);
242 if (wakeLockToken.get() == nullptr) {
243 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
244 } else {
245 if (mCount == 0) {
246 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
247 }
248 ++mCount;
249 }
250 pthread_mutex_unlock(&mLock);
251 }
252
253 // call when you release a partial wakelock.
254 void release(const sp<IBinder> &wakeLockToken) {
255 if (wakeLockToken.get() == nullptr) {
256 return;
257 }
258 pthread_mutex_lock(&mLock);
259 if (--mCount < 0) {
260 ALOGE("negative wakelock count");
261 mCount = 0;
262 }
263 pthread_mutex_unlock(&mLock);
264 }
265
266 // retrieves the boottime timebase offset from monotonic.
267 int64_t getBoottimeOffset() {
268 pthread_mutex_lock(&mLock);
269 int64_t boottimeOffset = mBoottimeOffset;
270 pthread_mutex_unlock(&mLock);
271 return boottimeOffset;
272 }
273
274 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
275 // and the selected timebase.
276 // Currently only TIMEBASE_BOOTTIME is allowed.
277 //
278 // This only needs to be called upon acquiring the first partial wakelock
279 // after all other partial wakelocks are released.
280 //
281 // We do an empirical measurement of the offset rather than parsing
282 // /proc/timer_list since the latter is not a formal kernel ABI.
283 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
284 int clockbase;
285 switch (timebase) {
286 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
287 clockbase = SYSTEM_TIME_BOOTTIME;
288 break;
289 default:
290 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
291 break;
292 }
293 // try three times to get the clock offset, choose the one
294 // with the minimum gap in measurements.
295 const int tries = 3;
296 nsecs_t bestGap, measured;
297 for (int i = 0; i < tries; ++i) {
298 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
299 const nsecs_t tbase = systemTime(clockbase);
300 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
301 const nsecs_t gap = tmono2 - tmono;
302 if (i == 0 || gap < bestGap) {
303 bestGap = gap;
304 measured = tbase - ((tmono + tmono2) >> 1);
305 }
306 }
307
308 // to avoid micro-adjusting, we don't change the timebase
309 // unless it is significantly different.
310 //
311 // Assumption: It probably takes more than toleranceNs to
312 // suspend and resume the device.
313 static int64_t toleranceNs = 10000; // 10 us
314 if (llabs(*offset - measured) > toleranceNs) {
315 ALOGV("Adjusting timebase offset old: %lld new: %lld",
316 (long long)*offset, (long long)measured);
317 *offset = measured;
318 }
319 }
320
321 pthread_mutex_t mLock;
322 int32_t mCount;
323 int64_t mBoottimeOffset;
324} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800325
326// ----------------------------------------------------------------------------
327// CPU Stats
328// ----------------------------------------------------------------------------
329
330class CpuStats {
331public:
332 CpuStats();
333 void sample(const String8 &title);
334#ifdef DEBUG_CPU_USAGE
335private:
336 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
337 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
338
339 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
340
341 int mCpuNum; // thread's current CPU number
342 int mCpukHz; // frequency of thread's current CPU in kHz
343#endif
344};
345
346CpuStats::CpuStats()
347#ifdef DEBUG_CPU_USAGE
348 : mCpuNum(-1), mCpukHz(-1)
349#endif
350{
351}
352
Glenn Kasten0f11b512014-01-31 16:18:54 -0800353void CpuStats::sample(const String8 &title
354#ifndef DEBUG_CPU_USAGE
355 __unused
356#endif
357 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800358#ifdef DEBUG_CPU_USAGE
359 // get current thread's delta CPU time in wall clock ns
360 double wcNs;
361 bool valid = mCpuUsage.sampleAndEnable(wcNs);
362
363 // record sample for wall clock statistics
364 if (valid) {
365 mWcStats.sample(wcNs);
366 }
367
368 // get the current CPU number
369 int cpuNum = sched_getcpu();
370
371 // get the current CPU frequency in kHz
372 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
373
374 // check if either CPU number or frequency changed
375 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
376 mCpuNum = cpuNum;
377 mCpukHz = cpukHz;
378 // ignore sample for purposes of cycles
379 valid = false;
380 }
381
382 // if no change in CPU number or frequency, then record sample for cycle statistics
383 if (valid && mCpukHz > 0) {
384 double cycles = wcNs * cpukHz * 0.000001;
385 mHzStats.sample(cycles);
386 }
387
388 unsigned n = mWcStats.n();
389 // mCpuUsage.elapsed() is expensive, so don't call it every loop
390 if ((n & 127) == 1) {
391 long long elapsed = mCpuUsage.elapsed();
392 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
393 double perLoop = elapsed / (double) n;
394 double perLoop100 = perLoop * 0.01;
395 double perLoop1k = perLoop * 0.001;
396 double mean = mWcStats.mean();
397 double stddev = mWcStats.stddev();
398 double minimum = mWcStats.minimum();
399 double maximum = mWcStats.maximum();
400 double meanCycles = mHzStats.mean();
401 double stddevCycles = mHzStats.stddev();
402 double minCycles = mHzStats.minimum();
403 double maxCycles = mHzStats.maximum();
404 mCpuUsage.resetElapsed();
405 mWcStats.reset();
406 mHzStats.reset();
407 ALOGD("CPU usage for %s over past %.1f secs\n"
408 " (%u mixer loops at %.1f mean ms per loop):\n"
409 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
410 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
411 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
412 title.string(),
413 elapsed * .000000001, n, perLoop * .000001,
414 mean * .001,
415 stddev * .001,
416 minimum * .001,
417 maximum * .001,
418 mean / perLoop100,
419 stddev / perLoop100,
420 minimum / perLoop100,
421 maximum / perLoop100,
422 meanCycles / perLoop1k,
423 stddevCycles / perLoop1k,
424 minCycles / perLoop1k,
425 maxCycles / perLoop1k);
426
427 }
428 }
429#endif
430};
431
432// ----------------------------------------------------------------------------
433// ThreadBase
434// ----------------------------------------------------------------------------
435
Glenn Kasten97b7b752014-09-28 13:04:24 -0700436// static
437const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
438{
439 switch (type) {
440 case MIXER:
441 return "MIXER";
442 case DIRECT:
443 return "DIRECT";
444 case DUPLICATING:
445 return "DUPLICATING";
446 case RECORD:
447 return "RECORD";
448 case OFFLOAD:
449 return "OFFLOAD";
450 default:
451 return "unknown";
452 }
453}
454
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700461 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800462 }
463 return result;
464}
465
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800467{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700468 std::string result;
469 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800470 return result;
471}
472
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700474{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700475 std::string result;
476 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477 return result;
478}
479
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800480const char *sourceToString(audio_source_t source)
481{
482 switch (source) {
483 case AUDIO_SOURCE_DEFAULT: return "default";
484 case AUDIO_SOURCE_MIC: return "mic";
485 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
486 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
487 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
488 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
489 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
490 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
491 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800492 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800493 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
494 case AUDIO_SOURCE_HOTWORD: return "hotword";
495 default: return "unknown";
496 }
497}
498
Eric Laurent81784c32012-11-19 14:55:58 -0800499AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700500 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800501 : Thread(false /*canCallJava*/),
502 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700503 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700504 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800505 // are set by PlaybackThread::readOutputParameters_l() or
506 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700507 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800508 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700509 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
510 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800511 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700512 mDeathRecipient(new PMDeathRecipient(this)),
Andy Hungdae27702016-10-31 14:01:16 -0700513 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800514{
Eric Laurent296fb132015-05-01 11:38:42 -0700515 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800516}
517
518AudioFlinger::ThreadBase::~ThreadBase()
519{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700521 mConfigEvents.clear();
522
Eric Laurent81784c32012-11-19 14:55:58 -0800523 // do not lock the mutex in destructor
524 releaseWakeLock_l();
525 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800526 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800527 binder->unlinkToDeath(mDeathRecipient);
528 }
529}
530
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700531status_t AudioFlinger::ThreadBase::readyToRun()
532{
533 status_t status = initCheck();
534 if (status == NO_ERROR) {
535 ALOGI("AudioFlinger's thread %p ready to run", this);
536 } else {
537 ALOGE("No working audio driver found.");
538 }
539 return status;
540}
541
Eric Laurent81784c32012-11-19 14:55:58 -0800542void AudioFlinger::ThreadBase::exit()
543{
544 ALOGV("ThreadBase::exit");
545 // do any cleanup required for exit to succeed
546 preExit();
547 {
548 // This lock prevents the following race in thread (uniprocessor for illustration):
549 // if (!exitPending()) {
550 // // context switch from here to exit()
551 // // exit() calls requestExit(), what exitPending() observes
552 // // exit() calls signal(), which is dropped since no waiters
553 // // context switch back from exit() to here
554 // mWaitWorkCV.wait(...);
555 // // now thread is hung
556 // }
557 AutoMutex lock(mLock);
558 requestExit();
559 mWaitWorkCV.broadcast();
560 }
561 // When Thread::requestExitAndWait is made virtual and this method is renamed to
562 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
563 requestExitAndWait();
564}
565
566status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
567{
Eric Laurent81784c32012-11-19 14:55:58 -0800568 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
569 Mutex::Autolock _l(mLock);
570
Eric Laurent10351942014-05-08 18:49:52 -0700571 return sendSetParameterConfigEvent_l(keyValuePairs);
572}
573
574// sendConfigEvent_l() must be called with ThreadBase::mLock held
575// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
576status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
577{
578 status_t status = NO_ERROR;
579
Eric Laurent72e3f392015-05-20 14:43:50 -0700580 if (event->mRequiresSystemReady && !mSystemReady) {
581 event->mWaitStatus = false;
582 mPendingConfigEvents.add(event);
583 return status;
584 }
Eric Laurent10351942014-05-08 18:49:52 -0700585 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700586 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800587 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700588 mLock.unlock();
589 {
590 Mutex::Autolock _l(event->mLock);
591 while (event->mWaitStatus) {
592 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
593 event->mStatus = TIMED_OUT;
594 event->mWaitStatus = false;
595 }
596 }
597 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800598 }
Eric Laurent10351942014-05-08 18:49:52 -0700599 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800600 return status;
601}
602
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700603void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800604{
605 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700606 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800607}
608
609// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700610void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800611{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700612 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700613 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800614}
615
Eric Laurent72e3f392015-05-20 14:43:50 -0700616void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
617{
618 Mutex::Autolock _l(mLock);
619 sendPrioConfigEvent_l(pid, tid, prio);
620}
621
Eric Laurent81784c32012-11-19 14:55:58 -0800622// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
623void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
624{
Eric Laurent10351942014-05-08 18:49:52 -0700625 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
626 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800627}
628
Eric Laurent10351942014-05-08 18:49:52 -0700629// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
630status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
Andy Hung2ddee192015-12-18 17:34:44 -0800632 sp<ConfigEvent> configEvent;
633 AudioParameter param(keyValuePair);
634 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700635 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800636 setMasterMono_l(value != 0);
637 if (param.size() == 1) {
638 return NO_ERROR; // should be a solo parameter - we don't pass down
639 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700640 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800641 configEvent = new SetParameterConfigEvent(param.toString());
642 } else {
643 configEvent = new SetParameterConfigEvent(keyValuePair);
644 }
Eric Laurent10351942014-05-08 18:49:52 -0700645 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700646}
647
Eric Laurent1c333e22014-05-20 10:48:17 -0700648status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
649 const struct audio_patch *patch,
650 audio_patch_handle_t *handle)
651{
652 Mutex::Autolock _l(mLock);
653 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
654 status_t status = sendConfigEvent_l(configEvent);
655 if (status == NO_ERROR) {
656 CreateAudioPatchConfigEventData *data =
657 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
658 *handle = data->mHandle;
659 }
660 return status;
661}
662
663status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
664 const audio_patch_handle_t handle)
665{
666 Mutex::Autolock _l(mLock);
667 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
668 return sendConfigEvent_l(configEvent);
669}
670
671
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700672// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700673void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700674{
Eric Laurent10351942014-05-08 18:49:52 -0700675 bool configChanged = false;
676
Eric Laurent81784c32012-11-19 14:55:58 -0800677 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700678 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700679 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800680 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700681 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700682 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700683 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
684 // FIXME Need to understand why this has to be done asynchronously
685 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700686 true /*asynchronous*/);
687 if (err != 0) {
688 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700689 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700690 }
691 } break;
692 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700693 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700694 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700695 } break;
696 case CFG_EVENT_SET_PARAMETER: {
697 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
698 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
699 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700700 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700701 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700702 case CFG_EVENT_CREATE_AUDIO_PATCH: {
703 CreateAudioPatchConfigEventData *data =
704 (CreateAudioPatchConfigEventData *)event->mData.get();
705 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
706 } break;
707 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
708 ReleaseAudioPatchConfigEventData *data =
709 (ReleaseAudioPatchConfigEventData *)event->mData.get();
710 event->mStatus = releaseAudioPatch_l(data->mHandle);
711 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700712 default:
Eric Laurent10351942014-05-08 18:49:52 -0700713 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700714 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800715 }
Eric Laurent10351942014-05-08 18:49:52 -0700716 {
717 Mutex::Autolock _l(event->mLock);
718 if (event->mWaitStatus) {
719 event->mWaitStatus = false;
720 event->mCond.signal();
721 }
722 }
723 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
724 }
725
726 if (configChanged) {
727 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800728 }
Eric Laurent81784c32012-11-19 14:55:58 -0800729}
730
Marco Nelissenb2208842014-02-07 14:00:50 -0800731String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
732 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700733 const audio_channel_representation_t representation =
734 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700735
736 switch (representation) {
737 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
738 if (output) {
739 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
740 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
741 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
742 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
743 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
744 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
745 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
746 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
747 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
748 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
749 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
750 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
751 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
753 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
754 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
755 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
756 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
757 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
758 } else {
759 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
760 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
761 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
762 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
763 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
764 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
765 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
766 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
767 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
768 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
769 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
770 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
771 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
772 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
773 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
774 }
775 const int len = s.length();
776 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700777 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700778 s.unlockBuffer(len - 2); // remove trailing ", "
779 }
780 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800781 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700782 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
783 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
784 return s;
785 default:
786 s.appendFormat("unknown mask, representation:%d bits:%#x",
787 representation, audio_channel_mask_get_bits(mask));
788 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800789 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800790}
791
Glenn Kasten0f11b512014-01-31 16:18:54 -0800792void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800793{
794 const size_t SIZE = 256;
795 char buffer[SIZE];
796 String8 result;
797
798 bool locked = AudioFlinger::dumpTryLock(mLock);
799 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700800 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800801 }
802
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800803 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700804 dprintf(fd, " I/O handle: %d\n", mId);
805 dprintf(fd, " TID: %d\n", getTid());
806 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700807 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700808 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700809 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700810 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700811 dprintf(fd, " Channel count: %u\n", mChannelCount);
812 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800813 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700814 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700815 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700816 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800817 size_t numConfig = mConfigEvents.size();
818 if (numConfig) {
819 for (size_t i = 0; i < numConfig; i++) {
820 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800822 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800824 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700825 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800826 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700827 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
828 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800829 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800830
831 if (locked) {
832 mLock.unlock();
833 }
834}
835
836void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
837{
838 const size_t SIZE = 256;
839 char buffer[SIZE];
840 String8 result;
841
Marco Nelissenb2208842014-02-07 14:00:50 -0800842 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000843 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800844 write(fd, buffer, strlen(buffer));
845
Marco Nelissenb2208842014-02-07 14:00:50 -0800846 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800847 sp<EffectChain> chain = mEffectChains[i];
848 if (chain != 0) {
849 chain->dump(fd, args);
850 }
851 }
852}
853
Andy Hungdae27702016-10-31 14:01:16 -0700854void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800855{
856 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700857 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800858}
859
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100860String16 AudioFlinger::ThreadBase::getWakeLockTag()
861{
862 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800863 case MIXER:
864 return String16("AudioMix");
865 case DIRECT:
866 return String16("AudioDirectOut");
867 case DUPLICATING:
868 return String16("AudioDup");
869 case RECORD:
870 return String16("AudioIn");
871 case OFFLOAD:
872 return String16("AudioOffload");
873 default:
874 ALOG_ASSERT(false);
875 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100876 }
877}
878
Andy Hungdae27702016-10-31 14:01:16 -0700879void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800880{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800881 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800882 if (mPowerManager != 0) {
883 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700884 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
885 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700886 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100887 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700888 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700889 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800890 if (status == NO_ERROR) {
891 mWakeLockToken = binder;
892 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800893 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800894 }
Wei Jia3f273d12015-11-24 09:06:49 -0800895
Andy Hung3f0c9022016-01-15 17:49:46 -0800896 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800897 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
898 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800899}
900
901void AudioFlinger::ThreadBase::releaseWakeLock()
902{
903 Mutex::Autolock _l(mLock);
904 releaseWakeLock_l();
905}
906
907void AudioFlinger::ThreadBase::releaseWakeLock_l()
908{
Andy Hung3f0c9022016-01-15 17:49:46 -0800909 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800911 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800912 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700913 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
914 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800915 }
916 mWakeLockToken.clear();
917 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800918}
919
920void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700921 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800922 // use checkService() to avoid blocking if power service is not up yet
923 sp<IBinder> binder =
924 defaultServiceManager()->checkService(String16("power"));
925 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800926 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800927 } else {
928 mPowerManager = interface_cast<IPowerManager>(binder);
929 binder->linkToDeath(mDeathRecipient);
930 }
931 }
932}
933
Andy Hungd01b0f12016-11-07 16:10:30 -0800934void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800935 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700936
937#if !LOG_NDEBUG
938 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800939 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700940 s << uid << " ";
941 }
942 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
943#endif
944
Andy Hung438e7572015-12-14 15:51:17 -0800945 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
946 if (mSystemReady) {
947 ALOGE("no wake lock to update, but system ready!");
948 } else {
949 ALOGW("no wake lock to update, system not ready yet");
950 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 return;
952 }
953 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800954 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
955 status_t status = mPowerManager->updateWakeLockUids(
956 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
957 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800958 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800959 }
960}
961
Eric Laurent81784c32012-11-19 14:55:58 -0800962void AudioFlinger::ThreadBase::clearPowerManager()
963{
964 Mutex::Autolock _l(mLock);
965 releaseWakeLock_l();
966 mPowerManager.clear();
967}
968
Glenn Kasten0f11b512014-01-31 16:18:54 -0800969void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800970{
971 sp<ThreadBase> thread = mThread.promote();
972 if (thread != 0) {
973 thread->clearPowerManager();
974 }
975 ALOGW("power manager service died !!!");
976}
977
978void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800979 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800980{
981 Mutex::Autolock _l(mLock);
982 setEffectSuspended_l(type, suspend, sessionId);
983}
984
985void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800986 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800987{
988 sp<EffectChain> chain = getEffectChain_l(sessionId);
989 if (chain != 0) {
990 if (type != NULL) {
991 chain->setEffectSuspended_l(type, suspend);
992 } else {
993 chain->setEffectSuspendedAll_l(suspend);
994 }
995 }
996
997 updateSuspendedSessions_l(type, suspend, sessionId);
998}
999
1000void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1001{
1002 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1003 if (index < 0) {
1004 return;
1005 }
1006
1007 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1008 mSuspendedSessions.valueAt(index);
1009
1010 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001011 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001012 for (int j = 0; j < desc->mRefCount; j++) {
1013 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1014 chain->setEffectSuspendedAll_l(true);
1015 } else {
1016 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1017 desc->mType.timeLow);
1018 chain->setEffectSuspended_l(&desc->mType, true);
1019 }
1020 }
1021 }
1022}
1023
1024void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1025 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001026 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001027{
1028 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1029
1030 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1031
1032 if (suspend) {
1033 if (index >= 0) {
1034 sessionEffects = mSuspendedSessions.valueAt(index);
1035 } else {
1036 mSuspendedSessions.add(sessionId, sessionEffects);
1037 }
1038 } else {
1039 if (index < 0) {
1040 return;
1041 }
1042 sessionEffects = mSuspendedSessions.valueAt(index);
1043 }
1044
1045
1046 int key = EffectChain::kKeyForSuspendAll;
1047 if (type != NULL) {
1048 key = type->timeLow;
1049 }
1050 index = sessionEffects.indexOfKey(key);
1051
1052 sp<SuspendedSessionDesc> desc;
1053 if (suspend) {
1054 if (index >= 0) {
1055 desc = sessionEffects.valueAt(index);
1056 } else {
1057 desc = new SuspendedSessionDesc();
1058 if (type != NULL) {
1059 desc->mType = *type;
1060 }
1061 sessionEffects.add(key, desc);
1062 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1063 }
1064 desc->mRefCount++;
1065 } else {
1066 if (index < 0) {
1067 return;
1068 }
1069 desc = sessionEffects.valueAt(index);
1070 if (--desc->mRefCount == 0) {
1071 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1072 sessionEffects.removeItemsAt(index);
1073 if (sessionEffects.isEmpty()) {
1074 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1075 sessionId);
1076 mSuspendedSessions.removeItem(sessionId);
1077 }
1078 }
1079 }
1080 if (!sessionEffects.isEmpty()) {
1081 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1082 }
1083}
1084
1085void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1086 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001087 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001088{
1089 Mutex::Autolock _l(mLock);
1090 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1091}
1092
1093void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1094 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001095 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001096{
1097 if (mType != RECORD) {
1098 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1099 // another session. This gives the priority to well behaved effect control panels
1100 // and applications not using global effects.
1101 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1102 // global effects
1103 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1104 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1105 }
1106 }
1107
1108 sp<EffectChain> chain = getEffectChain_l(sessionId);
1109 if (chain != 0) {
1110 chain->checkSuspendOnEffectEnabled(effect, enabled);
1111 }
1112}
1113
Eric Laurent4c415062016-06-17 16:14:16 -07001114// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1115status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1116 const effect_descriptor_t *desc, audio_session_t sessionId)
1117{
1118 // No global effect sessions on record threads
1119 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1120 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1121 desc->name, mThreadName);
1122 return BAD_VALUE;
1123 }
1124 // only pre processing effects on record thread
1125 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1126 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1127 desc->name, mThreadName);
1128 return BAD_VALUE;
1129 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001130
1131 // always allow effects without processing load or latency
1132 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1133 return NO_ERROR;
1134 }
1135
Eric Laurent4c415062016-06-17 16:14:16 -07001136 audio_input_flags_t flags = mInput->flags;
1137 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1138 if (flags & AUDIO_INPUT_FLAG_RAW) {
1139 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1140 desc->name, mThreadName);
1141 return BAD_VALUE;
1142 }
1143 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1144 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1145 desc->name, mThreadName);
1146 return BAD_VALUE;
1147 }
1148 }
1149 return NO_ERROR;
1150}
1151
1152// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1153status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1154 const effect_descriptor_t *desc, audio_session_t sessionId)
1155{
1156 // no preprocessing on playback threads
1157 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1158 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1159 " thread %s", desc->name, mThreadName);
1160 return BAD_VALUE;
1161 }
1162
1163 switch (mType) {
1164 case MIXER: {
1165 // Reject any effect on mixer multichannel sinks.
1166 // TODO: fix both format and multichannel issues with effects.
1167 if (mChannelCount != FCC_2) {
1168 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1169 " thread %s", desc->name, mChannelCount, mThreadName);
1170 return BAD_VALUE;
1171 }
1172 audio_output_flags_t flags = mOutput->flags;
1173 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1174 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1175 // global effects are applied only to non fast tracks if they are SW
1176 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1177 break;
1178 }
1179 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1180 // only post processing on output stage session
1181 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1182 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1183 " on output stage session", desc->name);
1184 return BAD_VALUE;
1185 }
1186 } else {
1187 // no restriction on effects applied on non fast tracks
1188 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1189 break;
1190 }
1191 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001192
1193 // always allow effects without processing load or latency
1194 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1195 break;
1196 }
Eric Laurent4c415062016-06-17 16:14:16 -07001197 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1198 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1199 desc->name);
1200 return BAD_VALUE;
1201 }
1202 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1203 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1204 " in fast mode", desc->name);
1205 return BAD_VALUE;
1206 }
1207 }
1208 } break;
1209 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001210 // nothing actionable on offload threads, if the effect:
1211 // - is offloadable: the effect can be created
1212 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1213 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001214 break;
1215 case DIRECT:
1216 // Reject any effect on Direct output threads for now, since the format of
1217 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1218 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1219 desc->name, mThreadName);
1220 return BAD_VALUE;
1221 case DUPLICATING:
1222 // Reject any effect on mixer multichannel sinks.
1223 // TODO: fix both format and multichannel issues with effects.
1224 if (mChannelCount != FCC_2) {
1225 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1226 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1227 return BAD_VALUE;
1228 }
1229 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1230 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1231 " thread %s", desc->name, mThreadName);
1232 return BAD_VALUE;
1233 }
1234 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1235 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1236 " DUPLICATING thread %s", desc->name, mThreadName);
1237 return BAD_VALUE;
1238 }
1239 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1240 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1241 " DUPLICATING thread %s", desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 break;
1245 default:
1246 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1247 }
1248
1249 return NO_ERROR;
1250}
1251
Eric Laurent81784c32012-11-19 14:55:58 -08001252// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1253sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1254 const sp<AudioFlinger::Client>& client,
1255 const sp<IEffectClient>& effectClient,
1256 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001257 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001258 effect_descriptor_t *desc,
1259 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001260 status_t *status,
1261 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001262{
1263 sp<EffectModule> effect;
1264 sp<EffectHandle> handle;
1265 status_t lStatus;
1266 sp<EffectChain> chain;
1267 bool chainCreated = false;
1268 bool effectCreated = false;
1269 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001270 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001271
1272 lStatus = initCheck();
1273 if (lStatus != NO_ERROR) {
1274 ALOGW("createEffect_l() Audio driver not initialized.");
1275 goto Exit;
1276 }
1277
Eric Laurent81784c32012-11-19 14:55:58 -08001278 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1279
1280 { // scope for mLock
1281 Mutex::Autolock _l(mLock);
1282
Eric Laurent4c415062016-06-17 16:14:16 -07001283 lStatus = checkEffectCompatibility_l(desc, sessionId);
1284 if (lStatus != NO_ERROR) {
1285 goto Exit;
1286 }
1287
Eric Laurent81784c32012-11-19 14:55:58 -08001288 // check for existing effect chain with the requested audio session
1289 chain = getEffectChain_l(sessionId);
1290 if (chain == 0) {
1291 // create a new chain for this session
1292 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1293 chain = new EffectChain(this, sessionId);
1294 addEffectChain_l(chain);
1295 chain->setStrategy(getStrategyForSession_l(sessionId));
1296 chainCreated = true;
1297 } else {
1298 effect = chain->getEffectFromDesc_l(desc);
1299 }
1300
1301 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1302
1303 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001304 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001305 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001306 lStatus = AudioSystem::registerEffect(
1307 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001308 if (lStatus != NO_ERROR) {
1309 goto Exit;
1310 }
1311 effectRegistered = true;
1312 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001313 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001314 if (lStatus != NO_ERROR) {
1315 goto Exit;
1316 }
1317 effectCreated = true;
1318
1319 effect->setDevice(mOutDevice);
1320 effect->setDevice(mInDevice);
1321 effect->setMode(mAudioFlinger->getMode());
1322 effect->setAudioSource(mAudioSource);
1323 }
1324 // create effect handle and connect it to effect module
1325 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001326 lStatus = handle->initCheck();
1327 if (lStatus == OK) {
1328 lStatus = effect->addHandle(handle.get());
1329 }
Eric Laurent81784c32012-11-19 14:55:58 -08001330 if (enabled != NULL) {
1331 *enabled = (int)effect->isEnabled();
1332 }
1333 }
1334
1335Exit:
1336 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1337 Mutex::Autolock _l(mLock);
1338 if (effectCreated) {
1339 chain->removeEffect_l(effect);
1340 }
1341 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001342 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001343 }
1344 if (chainCreated) {
1345 removeEffectChain_l(chain);
1346 }
1347 handle.clear();
1348 }
1349
Glenn Kasten9156ef32013-08-06 15:39:08 -07001350 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001351 return handle;
1352}
1353
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001354void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1355 bool unpinIfLast)
1356{
1357 bool remove = false;
1358 sp<EffectModule> effect;
1359 {
1360 Mutex::Autolock _l(mLock);
1361
1362 effect = handle->effect().promote();
1363 if (effect == 0) {
1364 return;
1365 }
1366 // restore suspended effects if the disconnected handle was enabled and the last one.
1367 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1368 if (remove) {
1369 removeEffect_l(effect, true);
1370 }
1371 }
1372 if (remove) {
1373 mAudioFlinger->updateOrphanEffectChains(effect);
1374 AudioSystem::unregisterEffect(effect->id());
1375 if (handle->enabled()) {
1376 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1377 }
1378 }
1379}
1380
Glenn Kastend848eb42016-03-08 13:42:11 -08001381sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1382 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001383{
1384 Mutex::Autolock _l(mLock);
1385 return getEffect_l(sessionId, effectId);
1386}
1387
Glenn Kastend848eb42016-03-08 13:42:11 -08001388sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1389 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001390{
1391 sp<EffectChain> chain = getEffectChain_l(sessionId);
1392 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1393}
1394
1395// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1396// PlaybackThread::mLock held
1397status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1398{
1399 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001400 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001401 sp<EffectChain> chain = getEffectChain_l(sessionId);
1402 bool chainCreated = false;
1403
Eric Laurent5baf2af2013-09-12 17:37:00 -07001404 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1405 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1406 this, effect->desc().name, effect->desc().flags);
1407
Eric Laurent81784c32012-11-19 14:55:58 -08001408 if (chain == 0) {
1409 // create a new chain for this session
1410 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1411 chain = new EffectChain(this, sessionId);
1412 addEffectChain_l(chain);
1413 chain->setStrategy(getStrategyForSession_l(sessionId));
1414 chainCreated = true;
1415 }
1416 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1417
1418 if (chain->getEffectFromId_l(effect->id()) != 0) {
1419 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1420 this, effect->desc().name, chain.get());
1421 return BAD_VALUE;
1422 }
1423
Eric Laurent5baf2af2013-09-12 17:37:00 -07001424 effect->setOffloaded(mType == OFFLOAD, mId);
1425
Eric Laurent81784c32012-11-19 14:55:58 -08001426 status_t status = chain->addEffect_l(effect);
1427 if (status != NO_ERROR) {
1428 if (chainCreated) {
1429 removeEffectChain_l(chain);
1430 }
1431 return status;
1432 }
1433
1434 effect->setDevice(mOutDevice);
1435 effect->setDevice(mInDevice);
1436 effect->setMode(mAudioFlinger->getMode());
1437 effect->setAudioSource(mAudioSource);
1438 return NO_ERROR;
1439}
1440
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001441void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001442
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001443 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001444 effect_descriptor_t desc = effect->desc();
1445 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1446 detachAuxEffect_l(effect->id());
1447 }
1448
1449 sp<EffectChain> chain = effect->chain().promote();
1450 if (chain != 0) {
1451 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001452 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001453 removeEffectChain_l(chain);
1454 }
1455 } else {
1456 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1457 }
1458}
1459
1460void AudioFlinger::ThreadBase::lockEffectChains_l(
1461 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1462{
1463 effectChains = mEffectChains;
1464 for (size_t i = 0; i < mEffectChains.size(); i++) {
1465 mEffectChains[i]->lock();
1466 }
1467}
1468
1469void AudioFlinger::ThreadBase::unlockEffectChains(
1470 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1471{
1472 for (size_t i = 0; i < effectChains.size(); i++) {
1473 effectChains[i]->unlock();
1474 }
1475}
1476
Glenn Kastend848eb42016-03-08 13:42:11 -08001477sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001478{
1479 Mutex::Autolock _l(mLock);
1480 return getEffectChain_l(sessionId);
1481}
1482
Glenn Kastend848eb42016-03-08 13:42:11 -08001483sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1484 const
Eric Laurent81784c32012-11-19 14:55:58 -08001485{
1486 size_t size = mEffectChains.size();
1487 for (size_t i = 0; i < size; i++) {
1488 if (mEffectChains[i]->sessionId() == sessionId) {
1489 return mEffectChains[i];
1490 }
1491 }
1492 return 0;
1493}
1494
1495void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1496{
1497 Mutex::Autolock _l(mLock);
1498 size_t size = mEffectChains.size();
1499 for (size_t i = 0; i < size; i++) {
1500 mEffectChains[i]->setMode_l(mode);
1501 }
1502}
1503
Eric Laurent83b88082014-06-20 18:31:16 -07001504void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1505{
1506 config->type = AUDIO_PORT_TYPE_MIX;
1507 config->ext.mix.handle = mId;
1508 config->sample_rate = mSampleRate;
1509 config->format = mFormat;
1510 config->channel_mask = mChannelMask;
1511 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1512 AUDIO_PORT_CONFIG_FORMAT;
1513}
1514
Eric Laurent72e3f392015-05-20 14:43:50 -07001515void AudioFlinger::ThreadBase::systemReady()
1516{
1517 Mutex::Autolock _l(mLock);
1518 if (mSystemReady) {
1519 return;
1520 }
1521 mSystemReady = true;
1522
1523 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1524 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1525 }
1526 mPendingConfigEvents.clear();
1527}
1528
Andy Hungdae27702016-10-31 14:01:16 -07001529template <typename T>
1530ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1531 ssize_t index = mActiveTracks.indexOf(track);
1532 if (index >= 0) {
1533 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1534 return index;
1535 }
1536 mActiveTracksGeneration++;
1537 mLatestActiveTrack = track;
1538 ++mBatteryCounter[track->uid()].second;
1539 return mActiveTracks.add(track);
1540}
1541
1542template <typename T>
1543ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1544 ssize_t index = mActiveTracks.remove(track);
1545 if (index < 0) {
1546 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1547 return index;
1548 }
1549 mActiveTracksGeneration++;
1550 --mBatteryCounter[track->uid()].second;
1551 // mLatestActiveTrack is not cleared even if is the same as track.
1552 return index;
1553}
1554
1555template <typename T>
1556void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1557 for (const sp<T> &track : mActiveTracks) {
1558 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1559 }
1560 mLastActiveTracksGeneration = mActiveTracksGeneration;
1561 mActiveTracks.clear();
1562 mLatestActiveTrack.clear();
1563 mBatteryCounter.clear();
1564}
1565
1566template <typename T>
1567void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1568 sp<ThreadBase> thread, bool force) {
1569 // Updates ActiveTracks client uids to the thread wakelock.
1570 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1571 thread->updateWakeLockUids_l(getWakeLockUids());
1572 mLastActiveTracksGeneration = mActiveTracksGeneration;
1573 }
1574
1575 // Updates BatteryNotifier uids
1576 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1577 const uid_t uid = it->first;
1578 ssize_t &previous = it->second.first;
1579 ssize_t &current = it->second.second;
1580 if (current > 0) {
1581 if (previous == 0) {
1582 BatteryNotifier::getInstance().noteStartAudio(uid);
1583 }
1584 previous = current;
1585 ++it;
1586 } else if (current == 0) {
1587 if (previous > 0) {
1588 BatteryNotifier::getInstance().noteStopAudio(uid);
1589 }
1590 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1591 } else /* (current < 0) */ {
1592 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1593 }
1594 }
1595}
Eric Laurent83b88082014-06-20 18:31:16 -07001596
Eric Laurent81784c32012-11-19 14:55:58 -08001597// ----------------------------------------------------------------------------
1598// Playback
1599// ----------------------------------------------------------------------------
1600
1601AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1602 AudioStreamOut* output,
1603 audio_io_handle_t id,
1604 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001605 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001606 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001607 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001608 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001609 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001610 mMixerBuffer(NULL),
1611 mMixerBufferSize(0),
1612 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1613 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001614 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001615 mEffectBuffer(NULL),
1616 mEffectBufferSize(0),
1617 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1618 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001619 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001620 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001621 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001622 // mStreamTypes[] initialized in constructor body
1623 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001624 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001625 mMixerStatus(MIXER_IDLE),
1626 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001627 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001628 mBytesRemaining(0),
1629 mCurrentWriteLength(0),
1630 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001631 mWriteAckSequence(0),
1632 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001633 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001634 mScreenState(AudioFlinger::mScreenState),
1635 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001636 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001637 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001638{
Glenn Kastend7dca052015-03-05 16:05:54 -08001639 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1640 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001641
1642 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1643 // it would be safer to explicitly pass initial masterVolume/masterMute as
1644 // parameter.
1645 //
1646 // If the HAL we are using has support for master volume or master mute,
1647 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1648 // and the mute set to false).
1649 mMasterVolume = audioFlinger->masterVolume_l();
1650 mMasterMute = audioFlinger->masterMute_l();
1651 if (mOutput && mOutput->audioHwDev) {
1652 if (mOutput->audioHwDev->canSetMasterVolume()) {
1653 mMasterVolume = 1.0;
1654 }
1655
1656 if (mOutput->audioHwDev->canSetMasterMute()) {
1657 mMasterMute = false;
1658 }
1659 }
1660
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001661 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001662
Eric Laurent223fd5c2014-11-11 13:43:36 -08001663 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001664 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001665 stream = (audio_stream_type_t) (stream + 1)) {
1666 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1667 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1668 }
Eric Laurent81784c32012-11-19 14:55:58 -08001669}
1670
1671AudioFlinger::PlaybackThread::~PlaybackThread()
1672{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001673 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001674 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001675 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001676 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001677}
1678
1679void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1680{
1681 dumpInternals(fd, args);
1682 dumpTracks(fd, args);
1683 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001684 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001685}
1686
Glenn Kasten0f11b512014-01-31 16:18:54 -08001687void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001688{
1689 const size_t SIZE = 256;
1690 char buffer[SIZE];
1691 String8 result;
1692
Marco Nelissenb2208842014-02-07 14:00:50 -08001693 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001694 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1695 const stream_type_t *st = &mStreamTypes[i];
1696 if (i > 0) {
1697 result.appendFormat(", ");
1698 }
1699 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1700 if (st->mute) {
1701 result.append("M");
1702 }
1703 }
1704 result.append("\n");
1705 write(fd, result.string(), result.length());
1706 result.clear();
1707
Eric Laurent81784c32012-11-19 14:55:58 -08001708 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1709 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001710 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001711 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001712
1713 size_t numtracks = mTracks.size();
1714 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001715 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001716 size_t numactiveseen = 0;
1717 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001718 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001719 Track::appendDumpHeader(result);
1720 for (size_t i = 0; i < numtracks; ++i) {
1721 sp<Track> track = mTracks[i];
1722 if (track != 0) {
1723 bool active = mActiveTracks.indexOf(track) >= 0;
1724 if (active) {
1725 numactiveseen++;
1726 }
1727 track->dump(buffer, SIZE, active);
1728 result.append(buffer);
1729 }
1730 }
1731 } else {
1732 result.append("\n");
1733 }
1734 if (numactiveseen != numactive) {
1735 // some tracks in the active list were not in the tracks list
1736 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1737 " not in the track list\n");
1738 result.append(buffer);
1739 Track::appendDumpHeader(result);
1740 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001741 sp<Track> track = mActiveTracks[i];
1742 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001743 track->dump(buffer, SIZE, true);
1744 result.append(buffer);
1745 }
1746 }
1747 }
1748
1749 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001750}
1751
1752void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1753{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001754 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001755
1756 dumpBase(fd, args);
1757
Elliott Hughes87cebad2014-05-22 10:14:43 -07001758 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001759 dprintf(fd, " Last write occurred (msecs): %llu\n",
1760 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001761 dprintf(fd, " Total writes: %d\n", mNumWrites);
1762 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1763 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1764 dprintf(fd, " Suspend count: %d\n", mSuspended);
1765 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1766 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1767 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1768 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001769 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001770 AudioStreamOut *output = mOutput;
1771 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001772 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1773 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001774 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1775 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1776 if (mPipeSink.get() != nullptr) {
1777 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1778 }
1779 if (output != nullptr) {
1780 dprintf(fd, " Hal stream dump:\n");
1781 (void)output->stream->dump(fd);
1782 }
Eric Laurent81784c32012-11-19 14:55:58 -08001783}
1784
1785// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001786
1787void AudioFlinger::PlaybackThread::onFirstRef()
1788{
Glenn Kastend7dca052015-03-05 16:05:54 -08001789 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001790}
1791
1792// ThreadBase virtuals
1793void AudioFlinger::PlaybackThread::preExit()
1794{
1795 ALOGV(" preExit()");
1796 // FIXME this is using hard-coded strings but in the future, this functionality will be
1797 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001798 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1799 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001800}
1801
1802// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1803sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1804 const sp<AudioFlinger::Client>& client,
1805 audio_stream_type_t streamType,
1806 uint32_t sampleRate,
1807 audio_format_t format,
1808 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001809 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001810 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001811 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001812 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001813 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001814 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001815 status_t *status,
1816 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001817{
Glenn Kasten74935e42013-12-19 08:56:45 -08001818 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001819 sp<Track> track;
1820 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001821 audio_output_flags_t outputFlags = mOutput->flags;
1822
1823 // special case for FAST flag considered OK if fast mixer is present
1824 if (hasFastMixer()) {
1825 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1826 }
1827
1828 // Check if requested flags are compatible with output stream flags
1829 if ((*flags & outputFlags) != *flags) {
1830 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1831 *flags, outputFlags);
1832 *flags = (audio_output_flags_t)(*flags & outputFlags);
1833 }
Eric Laurent81784c32012-11-19 14:55:58 -08001834
Eric Laurent81784c32012-11-19 14:55:58 -08001835 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001836 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001837 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001838 // PCM data
1839 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001840 // TODO: extract as a data library function that checks that a computationally
1841 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001842 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001843 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1844 (channelMask == AUDIO_CHANNEL_OUT_MONO
1845 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001846 // hardware sample rate
1847 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001848 // normal mixer has an associated fast mixer
1849 hasFastMixer() &&
1850 // there are sufficient fast track slots available
1851 (mFastTrackAvailMask != 0)
1852 // FIXME test that MixerThread for this fast track has a capable output HAL
1853 // FIXME add a permission test also?
1854 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001855 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1856 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001857 // read the fast track multiplier property the first time it is needed
1858 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1859 if (ok != 0) {
1860 ALOGE("%s pthread_once failed: %d", __func__, ok);
1861 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001862 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001863 }
Eric Laurent4c415062016-06-17 16:14:16 -07001864
1865 // check compatibility with audio effects.
1866 { // scope for mLock
1867 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001868 for (audio_session_t session : {
1869 AUDIO_SESSION_OUTPUT_STAGE,
1870 AUDIO_SESSION_OUTPUT_MIX,
1871 sessionId,
1872 }) {
1873 sp<EffectChain> chain = getEffectChain_l(session);
1874 if (chain.get() != nullptr) {
1875 audio_output_flags_t old = *flags;
1876 chain->checkOutputFlagCompatibility(flags);
1877 if (old != *flags) {
1878 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1879 (int)session, (int)old, (int)*flags);
1880 }
Eric Laurent4c415062016-06-17 16:14:16 -07001881 }
1882 }
1883 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001884 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001885 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1886 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001887 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001888 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1889 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001890 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001891 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001892 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001893 audio_is_linear_pcm(format),
1894 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001895 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001896 }
1897 }
1898 // For normal PCM streaming tracks, update minimum frame count.
1899 // For compatibility with AudioTrack calculation, buffer depth is forced
1900 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1901 // This is probably too conservative, but legacy application code may depend on it.
1902 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001903 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001904 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001905 // this must match AudioTrack.cpp calculateMinFrameCount().
1906 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001907 uint32_t latencyMs = 0;
1908 lStatus = mOutput->stream->getLatency(&latencyMs);
1909 if (lStatus != OK) {
1910 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1911 goto Exit;
1912 }
Eric Laurent81784c32012-11-19 14:55:58 -08001913 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1914 if (minBufCount < 2) {
1915 minBufCount = 2;
1916 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001917 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1918 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001919 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001920 minBufCount * sourceFramesNeededWithTimestretch(
1921 sampleRate, mNormalFrameCount,
1922 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001923 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001924 frameCount = minFrameCount;
1925 }
Eric Laurent81784c32012-11-19 14:55:58 -08001926 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001927 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001928
Glenn Kastenc3df8382014-03-13 15:05:25 -07001929 switch (mType) {
1930
1931 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001932 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001933 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001934 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1935 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001936 sampleRate, format, channelMask, mOutput, mFormat);
1937 lStatus = BAD_VALUE;
1938 goto Exit;
1939 }
1940 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001941 break;
1942
1943 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001944 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001945 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1946 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001947 sampleRate, format, channelMask, mOutput, mFormat);
1948 lStatus = BAD_VALUE;
1949 goto Exit;
1950 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001951 break;
1952
1953 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001954 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001955 ALOGE("createTrack_l() Bad parameter: format %#x \""
1956 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001957 format, mOutput, mFormat);
1958 lStatus = BAD_VALUE;
1959 goto Exit;
1960 }
Andy Hungcd044842014-08-07 11:04:34 -07001961 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001962 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1963 lStatus = BAD_VALUE;
1964 goto Exit;
1965 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001966 break;
1967
Eric Laurent81784c32012-11-19 14:55:58 -08001968 }
1969
1970 lStatus = initCheck();
1971 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001972 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001973 goto Exit;
1974 }
1975
1976 { // scope for mLock
1977 Mutex::Autolock _l(mLock);
1978
1979 // all tracks in same audio session must share the same routing strategy otherwise
1980 // conflicts will happen when tracks are moved from one output to another by audio policy
1981 // manager
1982 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1983 for (size_t i = 0; i < mTracks.size(); ++i) {
1984 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001985 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001986 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1987 if (sessionId == t->sessionId() && strategy != actual) {
1988 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1989 strategy, actual);
1990 lStatus = BAD_VALUE;
1991 goto Exit;
1992 }
1993 }
1994 }
1995
Glenn Kastend79072e2016-01-06 08:41:20 -08001996 track = new Track(this, client, streamType, sampleRate, format,
1997 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001998 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07001999
Glenn Kasten03003332013-08-06 15:40:54 -07002000 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2001 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002002 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002003 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002004 goto Exit;
2005 }
2006 mTracks.add(track);
2007
2008 sp<EffectChain> chain = getEffectChain_l(sessionId);
2009 if (chain != 0) {
2010 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2011 track->setMainBuffer(chain->inBuffer());
2012 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2013 chain->incTrackCnt();
2014 }
2015
Eric Laurent05067782016-06-01 18:27:28 -07002016 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002017 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2018 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2019 // so ask activity manager to do this on our behalf
2020 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2021 }
2022 }
2023
2024 lStatus = NO_ERROR;
2025
2026Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002027 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002028 return track;
2029}
2030
2031uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2032{
2033 return latency;
2034}
2035
2036uint32_t AudioFlinger::PlaybackThread::latency() const
2037{
2038 Mutex::Autolock _l(mLock);
2039 return latency_l();
2040}
2041uint32_t AudioFlinger::PlaybackThread::latency_l() const
2042{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002043 uint32_t latency;
2044 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2045 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002046 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002047 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002048}
2049
2050void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2051{
2052 Mutex::Autolock _l(mLock);
2053 // Don't apply master volume in SW if our HAL can do it for us.
2054 if (mOutput && mOutput->audioHwDev &&
2055 mOutput->audioHwDev->canSetMasterVolume()) {
2056 mMasterVolume = 1.0;
2057 } else {
2058 mMasterVolume = value;
2059 }
2060}
2061
2062void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2063{
2064 Mutex::Autolock _l(mLock);
2065 // Don't apply master mute in SW if our HAL can do it for us.
2066 if (mOutput && mOutput->audioHwDev &&
2067 mOutput->audioHwDev->canSetMasterMute()) {
2068 mMasterMute = false;
2069 } else {
2070 mMasterMute = muted;
2071 }
2072}
2073
2074void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2075{
2076 Mutex::Autolock _l(mLock);
2077 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002078 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002079}
2080
2081void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2082{
2083 Mutex::Autolock _l(mLock);
2084 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002085 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002086}
2087
2088float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2089{
2090 Mutex::Autolock _l(mLock);
2091 return mStreamTypes[stream].volume;
2092}
2093
2094// addTrack_l() must be called with ThreadBase::mLock held
2095status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2096{
2097 status_t status = ALREADY_EXISTS;
2098
Eric Laurent81784c32012-11-19 14:55:58 -08002099 if (mActiveTracks.indexOf(track) < 0) {
2100 // the track is newly added, make sure it fills up all its
2101 // buffers before playing. This is to ensure the client will
2102 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002103 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002104 TrackBase::track_state state = track->mState;
2105 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002106 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002107 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002108 mLock.lock();
2109 // abort track was stopped/paused while we released the lock
2110 if (state != track->mState) {
2111 if (status == NO_ERROR) {
2112 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002113 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002114 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002115 mLock.lock();
2116 }
2117 return INVALID_OPERATION;
2118 }
2119 // abort if start is rejected by audio policy manager
2120 if (status != NO_ERROR) {
2121 return PERMISSION_DENIED;
2122 }
2123#ifdef ADD_BATTERY_DATA
2124 // to track the speaker usage
2125 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2126#endif
2127 }
2128
Eric Laurent51716182016-02-29 18:00:56 -08002129 // set retry count for buffer fill
2130 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002131 if (track->isStopping_1()) {
2132 track->mRetryCount = kMaxTrackStopRetriesOffload;
2133 } else {
2134 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2135 }
2136 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002137 } else {
2138 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002139 track->mFillingUpStatus =
2140 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002141 }
2142
Eric Laurent81784c32012-11-19 14:55:58 -08002143 track->mResetDone = false;
2144 track->mPresentationCompleteFrames = 0;
2145 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002146 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2147 if (chain != 0) {
2148 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2149 track->sessionId());
2150 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002151 }
2152
Andy Hung2148bf02016-11-28 19:01:02 -08002153 char buffer[256];
2154 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2155 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2156
Eric Laurent81784c32012-11-19 14:55:58 -08002157 status = NO_ERROR;
2158 }
2159
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002160 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002161 return status;
2162}
2163
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002165{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002166 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002167 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002168 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2169 track->mState = TrackBase::STOPPED;
2170 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002171 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002172 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002173 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002174 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002175
2176 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002177}
2178
2179void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2180{
2181 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002182
2183 char buffer[256];
2184 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2185 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2186
Eric Laurent81784c32012-11-19 14:55:58 -08002187 mTracks.remove(track);
2188 deleteTrackName_l(track->name());
2189 // redundant as track is about to be destroyed, for dumpsys only
2190 track->mName = -1;
2191 if (track->isFastTrack()) {
2192 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002193 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002194 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2195 mFastTrackAvailMask |= 1 << index;
2196 // redundant as track is about to be destroyed, for dumpsys only
2197 track->mFastIndex = -1;
2198 }
2199 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2200 if (chain != 0) {
2201 chain->decTrackCnt();
2202 }
2203}
2204
Eric Laurentede6c3b2013-09-19 14:37:46 -07002205void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206{
2207 // Thread could be blocked waiting for async
2208 // so signal it to handle state changes immediately
2209 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2210 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2211 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002212 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002213}
2214
Eric Laurent81784c32012-11-19 14:55:58 -08002215String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2216{
Eric Laurent81784c32012-11-19 14:55:58 -08002217 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002218 String8 out_s8;
2219 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2220 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002221 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002222 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002223}
2224
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002225void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002226 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2227 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002228
Eric Laurent73e26b62015-04-27 16:55:58 -07002229 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002230
2231 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002232 case AUDIO_OUTPUT_OPENED:
2233 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002234 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002235 desc->mChannelMask = mChannelMask;
2236 desc->mSamplingRate = mSampleRate;
2237 desc->mFormat = mFormat;
2238 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002239 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002240 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002241 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002242 break;
2243
Eric Laurent73e26b62015-04-27 16:55:58 -07002244 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002245 default:
2246 break;
2247 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002248 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002249}
2250
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002251void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002252{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002253 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002254}
2255
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002256void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002257{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002258 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002259}
2260
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002261void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002262{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002263 mCallbackThread->setAsyncError();
2264}
2265
Eric Laurent3b4529e2013-09-05 18:09:19 -07002266void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002267{
2268 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002269 // reject out of sequence requests
2270 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2271 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002272 mWaitWorkCV.signal();
2273 }
2274}
2275
Eric Laurent3b4529e2013-09-05 18:09:19 -07002276void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002277{
2278 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002279 // reject out of sequence requests
2280 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2281 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002282 mWaitWorkCV.signal();
2283 }
2284}
2285
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002286void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002287{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002288 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002289 mSampleRate = mOutput->getSampleRate();
2290 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002291 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002292 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002293 }
Andy Hung9a592762014-07-21 21:56:01 -07002294 if ((mType == MIXER || mType == DUPLICATING)
2295 && !isValidPcmSinkChannelMask(mChannelMask)) {
2296 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2297 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002298 }
Andy Hunge5412692014-05-16 11:25:07 -07002299 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002300
2301 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002302 status_t result = mOutput->stream->getFormat(&mHALFormat);
2303 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002304 // Get format from the shim, which will be different than the HAL format
2305 // if playing compressed audio over HDMI passthrough.
2306 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002307 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002308 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002309 }
Andy Hung6146c082014-03-18 11:56:15 -07002310 if ((mType == MIXER || mType == DUPLICATING)
2311 && !isValidPcmSinkFormat(mFormat)) {
2312 LOG_FATAL("HAL format %#x not supported for mixed output",
2313 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002314 }
Phil Burk062e67a2015-02-11 13:40:50 -08002315 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002316 result = mOutput->stream->getBufferSize(&mBufferSize);
2317 LOG_ALWAYS_FATAL_IF(result != OK,
2318 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002319 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002320 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002321 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002322 mFrameCount);
2323 }
2324
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002325 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2326 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002327 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002328 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002329 }
2330 }
2331
Eric Laurentd1f69b02014-12-15 14:33:13 -08002332 mHwSupportsPause = false;
2333 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002334 bool supportsPause = false, supportsResume = false;
2335 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2336 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002337 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002338 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002339 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002340 } else if (supportsResume) {
2341 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002342 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002343 }
2344 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002345 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2346 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2347 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002348
Andy Hungfbfc3952015-01-15 13:33:51 -08002349 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2350 // For best precision, we use float instead of the associated output
2351 // device format (typically PCM 16 bit).
2352
2353 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2354 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2355 mBufferSize = mFrameSize * mFrameCount;
2356
2357 // TODO: We currently use the associated output device channel mask and sample rate.
2358 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2359 // (if a valid mask) to avoid premature downmix.
2360 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2361 // instead of the output device sample rate to avoid loss of high frequency information.
2362 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2363 }
2364
Andy Hung09a50072014-02-27 14:30:47 -08002365 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002366 double multiplier = 1.0;
2367 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2368 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002369 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2370 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002371
Eric Laurent81784c32012-11-19 14:55:58 -08002372 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2373 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2374 maxNormalFrameCount = maxNormalFrameCount & ~15;
2375 if (maxNormalFrameCount < minNormalFrameCount) {
2376 maxNormalFrameCount = minNormalFrameCount;
2377 }
2378 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2379 if (multiplier <= 1.0) {
2380 multiplier = 1.0;
2381 } else if (multiplier <= 2.0) {
2382 if (2 * mFrameCount <= maxNormalFrameCount) {
2383 multiplier = 2.0;
2384 } else {
2385 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2386 }
2387 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002388 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002389 }
2390 }
2391 mNormalFrameCount = multiplier * mFrameCount;
2392 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002393 if (mType == MIXER || mType == DUPLICATING) {
2394 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2395 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002396 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002397 mNormalFrameCount);
2398
Andy Hung08fb1742015-05-31 23:22:10 -07002399 // Check if we want to throttle the processing to no more than 2x normal rate
2400 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002401 mThreadThrottleTimeMs = 0;
2402 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002403 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2404
Andy Hung010a1a12014-03-13 13:57:33 -07002405 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2406 // Originally this was int16_t[] array, need to remove legacy implications.
2407 free(mSinkBuffer);
2408 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002409 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2410 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2411 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002412 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002413
Andy Hung69aed5f2014-02-25 17:24:40 -08002414 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2415 // drives the output.
2416 free(mMixerBuffer);
2417 mMixerBuffer = NULL;
2418 if (mMixerBufferEnabled) {
2419 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2420 mMixerBufferSize = mNormalFrameCount * mChannelCount
2421 * audio_bytes_per_sample(mMixerBufferFormat);
2422 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2423 }
Andy Hung98ef9782014-03-04 14:46:50 -08002424 free(mEffectBuffer);
2425 mEffectBuffer = NULL;
2426 if (mEffectBufferEnabled) {
2427 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2428 mEffectBufferSize = mNormalFrameCount * mChannelCount
2429 * audio_bytes_per_sample(mEffectBufferFormat);
2430 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2431 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002432
Eric Laurent81784c32012-11-19 14:55:58 -08002433 // force reconfiguration of effect chains and engines to take new buffer size and audio
2434 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002435 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002436 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2437 // matter.
2438 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2439 Vector< sp<EffectChain> > effectChains = mEffectChains;
2440 for (size_t i = 0; i < effectChains.size(); i ++) {
2441 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2442 }
2443}
2444
2445
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002446status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002447{
2448 if (halFrames == NULL || dspFrames == NULL) {
2449 return BAD_VALUE;
2450 }
2451 Mutex::Autolock _l(mLock);
2452 if (initCheck() != NO_ERROR) {
2453 return INVALID_OPERATION;
2454 }
Andy Hung818e7a32016-02-16 18:08:07 -08002455 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002456 *halFrames = framesWritten;
2457
2458 if (isSuspended()) {
2459 // return an estimation of rendered frames when the output is suspended
2460 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002461 *dspFrames = (uint32_t)
2462 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002463 return NO_ERROR;
2464 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002465 status_t status;
2466 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002467 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002468 *dspFrames = (size_t)frames;
2469 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002470 }
2471}
2472
Eric Laurent4c415062016-06-17 16:14:16 -07002473// hasAudioSession_l() must be called with ThreadBase::mLock held
2474uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002475{
Eric Laurent81784c32012-11-19 14:55:58 -08002476 uint32_t result = 0;
2477 if (getEffectChain_l(sessionId) != 0) {
2478 result = EFFECT_SESSION;
2479 }
2480
2481 for (size_t i = 0; i < mTracks.size(); ++i) {
2482 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002483 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002484 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002485 if (track->isFastTrack()) {
2486 result |= FAST_SESSION;
2487 }
Eric Laurent81784c32012-11-19 14:55:58 -08002488 break;
2489 }
2490 }
2491
2492 return result;
2493}
2494
Glenn Kastend848eb42016-03-08 13:42:11 -08002495uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002496{
2497 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2498 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2499 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2500 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2501 }
2502 for (size_t i = 0; i < mTracks.size(); i++) {
2503 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002504 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002505 return AudioSystem::getStrategyForStream(track->streamType());
2506 }
2507 }
2508 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2509}
2510
2511
Phil Burk062e67a2015-02-11 13:40:50 -08002512AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002513{
2514 Mutex::Autolock _l(mLock);
2515 return mOutput;
2516}
2517
Phil Burk062e67a2015-02-11 13:40:50 -08002518AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002519{
2520 Mutex::Autolock _l(mLock);
2521 AudioStreamOut *output = mOutput;
2522 mOutput = NULL;
2523 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2524 // must push a NULL and wait for ack
2525 mOutputSink.clear();
2526 mPipeSink.clear();
2527 mNormalSink.clear();
2528 return output;
2529}
2530
2531// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002532sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002533{
2534 if (mOutput == NULL) {
2535 return NULL;
2536 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002537 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002538}
2539
2540uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2541{
2542 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2543}
2544
2545status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2546{
2547 if (!isValidSyncEvent(event)) {
2548 return BAD_VALUE;
2549 }
2550
2551 Mutex::Autolock _l(mLock);
2552
2553 for (size_t i = 0; i < mTracks.size(); ++i) {
2554 sp<Track> track = mTracks[i];
2555 if (event->triggerSession() == track->sessionId()) {
2556 (void) track->setSyncEvent(event);
2557 return NO_ERROR;
2558 }
2559 }
2560
2561 return NAME_NOT_FOUND;
2562}
2563
2564bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2565{
2566 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2567}
2568
2569void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2570 const Vector< sp<Track> >& tracksToRemove)
2571{
2572 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002573 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002574 for (size_t i = 0 ; i < count ; i++) {
2575 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002576 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002577 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002578 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002579#ifdef ADD_BATTERY_DATA
2580 // to track the speaker usage
2581 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2582#endif
2583 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002584 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002585 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002586 }
Eric Laurent81784c32012-11-19 14:55:58 -08002587 }
2588 }
2589 }
Eric Laurent81784c32012-11-19 14:55:58 -08002590}
2591
2592void AudioFlinger::PlaybackThread::checkSilentMode_l()
2593{
2594 if (!mMasterMute) {
2595 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002596 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2597 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2598 return;
2599 }
Eric Laurent81784c32012-11-19 14:55:58 -08002600 if (property_get("ro.audio.silent", value, "0") > 0) {
2601 char *endptr;
2602 unsigned long ul = strtoul(value, &endptr, 0);
2603 if (*endptr == '\0' && ul != 0) {
2604 ALOGD("Silence is golden");
2605 // The setprop command will not allow a property to be changed after
2606 // the first time it is set, so we don't have to worry about un-muting.
2607 setMasterMute_l(true);
2608 }
2609 }
2610 }
2611}
2612
2613// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002614ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002615{
Eric Laurent81784c32012-11-19 14:55:58 -08002616 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002617 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002618 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002619
2620 // If an NBAIO sink is present, use it to write the normal mixer's submix
2621 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002622
Andy Hung010a1a12014-03-13 13:57:33 -07002623 const size_t count = mBytesRemaining / mFrameSize;
2624
Simon Wilson2d590962012-11-29 15:18:50 -08002625 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002626 // update the setpoint when AudioFlinger::mScreenState changes
2627 uint32_t screenState = AudioFlinger::mScreenState;
2628 if (screenState != mScreenState) {
2629 mScreenState = screenState;
2630 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2631 if (pipe != NULL) {
2632 pipe->setAvgFrames((mScreenState & 1) ?
2633 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2634 }
2635 }
Andy Hung010a1a12014-03-13 13:57:33 -07002636 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002637 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002638 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002639 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002640 } else {
2641 bytesWritten = framesWritten;
2642 }
2643 // otherwise use the HAL / AudioStreamOut directly
2644 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002645 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002646
Eric Laurentbfb1b832013-01-07 09:53:42 -08002647 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002648 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2649 mWriteAckSequence += 2;
2650 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002652 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002653 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002654 // FIXME We should have an implementation of timestamps for direct output threads.
2655 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002656 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002657
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 if (mUseAsyncWrite &&
2659 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2660 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002661 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002662 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002663 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 }
Eric Laurent81784c32012-11-19 14:55:58 -08002665 }
2666
Eric Laurent81784c32012-11-19 14:55:58 -08002667 mNumWrites++;
2668 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002669 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002670 return bytesWritten;
2671}
2672
2673void AudioFlinger::PlaybackThread::threadLoop_drain()
2674{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002675 bool supportsDrain = false;
2676 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2678 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002679 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2680 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002681 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002682 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002683 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002684 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002685 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686 }
2687}
2688
2689void AudioFlinger::PlaybackThread::threadLoop_exit()
2690{
Eric Laurent275e8e92014-11-30 15:14:47 -08002691 {
2692 Mutex::Autolock _l(mLock);
2693 for (size_t i = 0; i < mTracks.size(); i++) {
2694 sp<Track> track = mTracks[i];
2695 track->invalidate();
2696 }
Andy Hungdae27702016-10-31 14:01:16 -07002697 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2698 // After we exit there are no more track changes sent to BatteryNotifier
2699 // because that requires an active threadLoop.
2700 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2701 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002702 }
Eric Laurent81784c32012-11-19 14:55:58 -08002703}
2704
2705/*
2706The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002707 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002708 - mActiveSleepTimeUs from activeSleepTimeUs()
2709 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002710 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2711 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002712 - maxPeriod from frame count and sample rate (MIXER only)
2713
2714The parameters that affect these derived values are:
2715 - frame count
2716 - frame size
2717 - sample rate
2718 - device type: A2DP or not
2719 - device latency
2720 - format: PCM or not
2721 - active sleep time
2722 - idle sleep time
2723*/
2724
2725void AudioFlinger::PlaybackThread::cacheParameters_l()
2726{
Andy Hung25c2dac2014-02-27 14:56:00 -08002727 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002728 mActiveSleepTimeUs = activeSleepTimeUs();
2729 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002730
2731 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2732 // truncating audio when going to standby.
2733 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2734 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2735 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2736 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2737 }
2738 }
Eric Laurent81784c32012-11-19 14:55:58 -08002739}
2740
Eric Laurent13084622016-05-17 10:51:49 -07002741bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002742{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002743 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002744 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002745 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002746 size_t size = mTracks.size();
2747 for (size_t i = 0; i < size; i++) {
2748 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002749 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002750 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002751 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002752 }
2753 }
Eric Laurent13084622016-05-17 10:51:49 -07002754 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002755}
2756
Haynes Mathew George05317d22016-05-03 16:34:26 -07002757void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2758{
2759 Mutex::Autolock _l(mLock);
2760 invalidateTracks_l(streamType);
2761}
2762
Eric Laurent81784c32012-11-19 14:55:58 -08002763status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2764{
Glenn Kastend848eb42016-03-08 13:42:11 -08002765 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002766 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2767 status_t result = EffectBufferHalInterface::mirror(
2768 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2769 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2770 &halInBuffer);
2771 if (result != OK) return result;
2772 halOutBuffer = halInBuffer;
2773 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002774
2775 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002776 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002777 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002778 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002779 if (mType != DIRECT) {
2780 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002781 status_t result = EffectBufferHalInterface::allocate(
2782 numSamples * sizeof(int16_t),
2783 &halInBuffer);
2784 if (result != OK) return result;
2785 buffer = halInBuffer->audioBuffer()->s16;
2786 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2787 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002788 }
2789
2790 // Attach all tracks with same session ID to this chain.
2791 for (size_t i = 0; i < mTracks.size(); ++i) {
2792 sp<Track> track = mTracks[i];
2793 if (session == track->sessionId()) {
2794 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2795 buffer);
2796 track->setMainBuffer(buffer);
2797 chain->incTrackCnt();
2798 }
2799 }
2800
2801 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002802 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002803 if (session == track->sessionId()) {
2804 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2805 chain->incActiveTrackCnt();
2806 }
2807 }
2808 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002809 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002810 chain->setInBuffer(halInBuffer);
2811 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002812 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002813 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002814 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2815 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002816 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002817 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002818 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002819 // Effect chain for other sessions are inserted at beginning of effect
2820 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002821 // sessions is not important.
2822 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2823 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2824 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002825 size_t size = mEffectChains.size();
2826 size_t i = 0;
2827 for (i = 0; i < size; i++) {
2828 if (mEffectChains[i]->sessionId() < session) {
2829 break;
2830 }
2831 }
2832 mEffectChains.insertAt(chain, i);
2833 checkSuspendOnAddEffectChain_l(chain);
2834
2835 return NO_ERROR;
2836}
2837
2838size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2839{
Glenn Kastend848eb42016-03-08 13:42:11 -08002840 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002841
2842 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2843
2844 for (size_t i = 0; i < mEffectChains.size(); i++) {
2845 if (chain == mEffectChains[i]) {
2846 mEffectChains.removeAt(i);
2847 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002848 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002849 if (session == track->sessionId()) {
2850 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2851 chain.get(), session);
2852 chain->decActiveTrackCnt();
2853 }
2854 }
2855
2856 // detach all tracks with same session ID from this chain
2857 for (size_t i = 0; i < mTracks.size(); ++i) {
2858 sp<Track> track = mTracks[i];
2859 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002860 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002861 chain->decTrackCnt();
2862 }
2863 }
2864 break;
2865 }
2866 }
2867 return mEffectChains.size();
2868}
2869
2870status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002871 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002872{
2873 Mutex::Autolock _l(mLock);
2874 return attachAuxEffect_l(track, EffectId);
2875}
2876
2877status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002878 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002879{
2880 status_t status = NO_ERROR;
2881
2882 if (EffectId == 0) {
2883 track->setAuxBuffer(0, NULL);
2884 } else {
2885 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2886 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2887 if (effect != 0) {
2888 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2889 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2890 } else {
2891 status = INVALID_OPERATION;
2892 }
2893 } else {
2894 status = BAD_VALUE;
2895 }
2896 }
2897 return status;
2898}
2899
2900void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2901{
2902 for (size_t i = 0; i < mTracks.size(); ++i) {
2903 sp<Track> track = mTracks[i];
2904 if (track->auxEffectId() == effectId) {
2905 attachAuxEffect_l(track, 0);
2906 }
2907 }
2908}
2909
2910bool AudioFlinger::PlaybackThread::threadLoop()
2911{
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002912 logWriterTLS = mNBLogWriter.get();
2913
Eric Laurent81784c32012-11-19 14:55:58 -08002914 Vector< sp<Track> > tracksToRemove;
2915
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002916 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002917 nsecs_t lastWriteFinished = -1; // time last server write completed
2918 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002919
2920 // MIXER
2921 nsecs_t lastWarning = 0;
2922
2923 // DUPLICATING
2924 // FIXME could this be made local to while loop?
2925 writeFrames = 0;
2926
2927 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002928 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002929
2930 if (mType == MIXER) {
2931 sleepTimeShift = 0;
2932 }
2933
2934 CpuStats cpuStats;
2935 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2936
2937 acquireWakeLock();
2938
Glenn Kasten9e58b552013-01-18 15:09:48 -08002939 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2940 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2941 // and then that string will be logged at the next convenient opportunity.
2942 const char *logString = NULL;
2943
Eric Laurent664539d2013-09-23 18:24:31 -07002944 checkSilentMode_l();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002945#if 0
2946 int z = 0; // used in logFormat example
2947#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002948 while (!exitPending())
2949 {
2950 cpuStats.sample(myName);
2951
2952 Vector< sp<EffectChain> > effectChains;
2953
Eric Laurent81784c32012-11-19 14:55:58 -08002954 { // scope for mLock
2955
2956 Mutex::Autolock _l(mLock);
2957
Eric Laurent021cf962014-05-13 10:18:14 -07002958 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002959
Glenn Kasten9e58b552013-01-18 15:09:48 -08002960 if (logString != NULL) {
2961 mNBLogWriter->logTimestamp();
2962 mNBLogWriter->log(logString);
2963 logString = NULL;
2964 }
2965
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002966 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002967 // and associate with the sink frames written out. We need
2968 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002969 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002970 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002971 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002972 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002973 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002974 ExtendedTimestamp timestamp; // use private copy to fetch
2975 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002976
2977 // We keep track of the last valid kernel position in case we are in underrun
2978 // and the normal mixer period is the same as the fast mixer period, or there
2979 // is some error from the HAL.
2980 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2981 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2982 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2983 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2984 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2985
2986 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2987 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2988 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2989 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002990 }
2991
2992 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2993 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002994 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002995 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002996 }
2997
Andy Hung818e7a32016-02-16 18:08:07 -08002998 // copy over kernel info
2999 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003000 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3001 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003002 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3003 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003004 }
3005 // mFramesWritten for non-offloaded tracks are contiguous
3006 // even after standby() is called. This is useful for the track frame
3007 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003008 bool serverLocationUpdate = false;
3009 if (mFramesWritten != lastFramesWritten) {
3010 serverLocationUpdate = true;
3011 lastFramesWritten = mFramesWritten;
3012 }
3013 // Only update timestamps if there is a meaningful change.
3014 // Either the kernel timestamp must be valid or we have written something.
3015 if (kernelLocationUpdate || serverLocationUpdate) {
3016 if (serverLocationUpdate) {
3017 // use the time before we called the HAL write - it is a bit more accurate
3018 // to when the server last read data than the current time here.
3019 //
3020 // If we haven't written anything, mLastWriteTime will be -1
3021 // and we use systemTime().
3022 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3023 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3024 ? systemTime() : mLastWriteTime;
3025 }
Andy Hungdae27702016-10-31 14:01:16 -07003026
3027 for (const sp<Track> &t : mActiveTracks) {
3028 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003029 t->updateTrackFrameInfo(
3030 t->mAudioTrackServerProxy->framesReleased(),
3031 mFramesWritten,
3032 mTimestamp);
3033 }
Andy Hunge10393e2015-06-12 13:59:33 -07003034 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003035 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003036#if 0
3037 // logFormat example
3038 if (!(z % 100)) {
3039 timespec ts;
3040 clock_gettime(CLOCK_MONOTONIC, &ts);
3041 LOGF("This is an integer %d, this is a float %f, this is my "
3042 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
3043 LOGF("A deceptive null-terminated string %\0");
3044 }
3045 ++z;
3046#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003047 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003048 if (mSignalPending) {
3049 // A signal was raised while we were unlocked
3050 mSignalPending = false;
3051 } else if (waitingAsyncCallback_l()) {
3052 if (exitPending()) {
3053 break;
3054 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003055 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003056 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003057 releaseWakeLock_l();
3058 released = true;
3059 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003060 ALOGV("wait async completion");
3061 mWaitWorkCV.wait(mLock);
3062 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003063 if (released) {
3064 acquireWakeLock_l();
3065 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003066 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3067 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003068
3069 continue;
3070 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003071 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003072 isSuspended()) {
3073 // put audio hardware into standby after short delay
3074 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003075
3076 threadLoop_standby();
3077
3078 mStandby = true;
3079 }
3080
3081 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3082 // we're about to wait, flush the binder command buffer
3083 IPCThreadState::self()->flushCommands();
3084
3085 clearOutputTracks();
3086
3087 if (exitPending()) {
3088 break;
3089 }
3090
3091 releaseWakeLock_l();
3092 // wait until we have something to do...
3093 ALOGV("%s going to sleep", myName.string());
3094 mWaitWorkCV.wait(mLock);
3095 ALOGV("%s waking up", myName.string());
3096 acquireWakeLock_l();
3097
3098 mMixerStatus = MIXER_IDLE;
3099 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3100 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003101 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003102 checkSilentMode_l();
3103
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003104 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3105 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003106 if (mType == MIXER) {
3107 sleepTimeShift = 0;
3108 }
3109
3110 continue;
3111 }
3112 }
Eric Laurent81784c32012-11-19 14:55:58 -08003113 // mMixerStatusIgnoringFastTracks is also updated internally
3114 mMixerStatus = prepareTracks_l(&tracksToRemove);
3115
Andy Hungdae27702016-10-31 14:01:16 -07003116 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003117
Eric Laurent81784c32012-11-19 14:55:58 -08003118 // prevent any changes in effect chain list and in each effect chain
3119 // during mixing and effect process as the audio buffers could be deleted
3120 // or modified if an effect is created or deleted
3121 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003122 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003123
Eric Laurentbfb1b832013-01-07 09:53:42 -08003124 if (mBytesRemaining == 0) {
3125 mCurrentWriteLength = 0;
3126 if (mMixerStatus == MIXER_TRACKS_READY) {
3127 // threadLoop_mix() sets mCurrentWriteLength
3128 threadLoop_mix();
3129 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3130 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003131 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003132 // must be written to HAL
3133 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003134 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003135 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003136 }
3137 }
Andy Hung98ef9782014-03-04 14:46:50 -08003138 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003139 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003140 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3141 // or mSinkBuffer (if there are no effects).
3142 //
3143 // This is done pre-effects computation; if effects change to
3144 // support higher precision, this needs to move.
3145 //
3146 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003147 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003148 if (mMixerBufferValid) {
3149 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3150 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3151
Andy Hung2ddee192015-12-18 17:34:44 -08003152 // mono blend occurs for mixer threads only (not direct or offloaded)
3153 // and is handled here if we're going directly to the sink.
3154 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003155 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3156 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003157 }
3158
Andy Hung98ef9782014-03-04 14:46:50 -08003159 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3160 mNormalFrameCount * mChannelCount);
3161 }
3162
Eric Laurentbfb1b832013-01-07 09:53:42 -08003163 mBytesRemaining = mCurrentWriteLength;
3164 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003165 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3166 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3167 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3168 mBytesWritten += mBytesRemaining;
3169 mFramesWritten += framesRemaining;
3170 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003171 mBytesRemaining = 0;
3172 }
Eric Laurent81784c32012-11-19 14:55:58 -08003173
Eric Laurentbfb1b832013-01-07 09:53:42 -08003174 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003175 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003176 for (size_t i = 0; i < effectChains.size(); i ++) {
3177 effectChains[i]->process_l();
3178 }
Eric Laurent81784c32012-11-19 14:55:58 -08003179 }
3180 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003181 // Process effect chains for offloaded thread even if no audio
3182 // was read from audio track: process only updates effect state
3183 // and thus does have to be synchronized with audio writes but may have
3184 // to be called while waiting for async write callback
3185 if (mType == OFFLOAD) {
3186 for (size_t i = 0; i < effectChains.size(); i ++) {
3187 effectChains[i]->process_l();
3188 }
3189 }
Eric Laurent81784c32012-11-19 14:55:58 -08003190
Andy Hung98ef9782014-03-04 14:46:50 -08003191 // Only if the Effects buffer is enabled and there is data in the
3192 // Effects buffer (buffer valid), we need to
3193 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003194 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003195 if (mEffectBufferValid) {
3196 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003197
3198 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003199 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3200 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003201 }
3202
Andy Hung98ef9782014-03-04 14:46:50 -08003203 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3204 mNormalFrameCount * mChannelCount);
3205 }
3206
Eric Laurent81784c32012-11-19 14:55:58 -08003207 // enable changes in effect chain
3208 unlockEffectChains(effectChains);
3209
Eric Laurentbfb1b832013-01-07 09:53:42 -08003210 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003211 // mSleepTimeUs == 0 means we must write to audio hardware
3212 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003213 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003214 // We save lastWriteFinished here, as previousLastWriteFinished,
3215 // for throttling. On thread start, previousLastWriteFinished will be
3216 // set to -1, which properly results in no throttling after the first write.
3217 nsecs_t previousLastWriteFinished = lastWriteFinished;
3218 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003219 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003220 // FIXME rewrite to reduce number of system calls
3221 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003222 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003223 lastWriteFinished = systemTime();
3224 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003225 if (ret < 0) {
3226 mBytesRemaining = 0;
3227 } else {
3228 mBytesWritten += ret;
3229 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003230 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003231 }
3232 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3233 (mMixerStatus == MIXER_DRAIN_ALL)) {
3234 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003235 }
Andy Hung08fb1742015-05-31 23:22:10 -07003236 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003237 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003238 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003239 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003240 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003241 ATRACE_NAME("underrun");
3242 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003243 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003244 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003245 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003246 }
Andy Hung08fb1742015-05-31 23:22:10 -07003247
3248 if (mThreadThrottle
3249 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3250 && ret > 0) { // we wrote something
3251 // Limit MixerThread data processing to no more than twice the
3252 // expected processing rate.
3253 //
3254 // This helps prevent underruns with NuPlayer and other applications
3255 // which may set up buffers that are close to the minimum size, or use
3256 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3257 //
3258 // The throttle smooths out sudden large data drains from the device,
3259 // e.g. when it comes out of standby, which often causes problems with
3260 // (1) mixer threads without a fast mixer (which has its own warm-up)
3261 // (2) minimum buffer sized tracks (even if the track is full,
3262 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003263 //
3264 // Total time spent in last processing cycle equals time spent in
3265 // 1. threadLoop_write, as well as time spent in
3266 // 2. threadLoop_mix (significant for heavy mixing, especially
3267 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003268
Andy Hung69488c42016-05-16 18:43:33 -07003269 // it's OK if deltaMs is an overestimate.
3270 const int32_t deltaMs =
3271 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003272 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3273 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3274 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003275 // notify of throttle start on verbose log
3276 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3277 "mixer(%p) throttle begin:"
3278 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003279 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003280 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003281 // Throttle must be attributed to the previous mixer loop's write time
3282 // to allow back-to-back throttling.
3283 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003284 } else {
3285 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3286 if (diff > 0) {
3287 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003288 // but prevent spamming for bluetooth
3289 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3290 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003291 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3292 }
Andy Hung08fb1742015-05-31 23:22:10 -07003293 }
3294 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003295 }
Eric Laurent81784c32012-11-19 14:55:58 -08003296
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003298 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003299 Mutex::Autolock _l(mLock);
3300 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3301 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003302 }
Glenn Kastene7754022014-10-31 12:11:26 -07003303 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003304 }
Eric Laurent81784c32012-11-19 14:55:58 -08003305 }
3306
3307 // Finally let go of removed track(s), without the lock held
3308 // since we can't guarantee the destructors won't acquire that
3309 // same lock. This will also mutate and push a new fast mixer state.
3310 threadLoop_removeTracks(tracksToRemove);
3311 tracksToRemove.clear();
3312
3313 // FIXME I don't understand the need for this here;
3314 // it was in the original code but maybe the
3315 // assignment in saveOutputTracks() makes this unnecessary?
3316 clearOutputTracks();
3317
3318 // Effect chains will be actually deleted here if they were removed from
3319 // mEffectChains list during mixing or effects processing
3320 effectChains.clear();
3321
3322 // FIXME Note that the above .clear() is no longer necessary since effectChains
3323 // is now local to this block, but will keep it for now (at least until merge done).
3324 }
3325
Eric Laurentbfb1b832013-01-07 09:53:42 -08003326 threadLoop_exit();
3327
Eric Laurentcf817a22014-08-04 20:36:31 -07003328 if (!mStandby) {
3329 threadLoop_standby();
3330 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003331 }
3332
3333 releaseWakeLock();
3334
3335 ALOGV("Thread %p type %d exiting", this, mType);
3336 return false;
3337}
3338
Eric Laurentbfb1b832013-01-07 09:53:42 -08003339// removeTracks_l() must be called with ThreadBase::mLock held
3340void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3341{
3342 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003343 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003344 for (size_t i=0 ; i<count ; i++) {
3345 const sp<Track>& track = tracksToRemove.itemAt(i);
3346 mActiveTracks.remove(track);
3347 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3348 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3349 if (chain != 0) {
3350 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3351 track->sessionId());
3352 chain->decActiveTrackCnt();
3353 }
3354 if (track->isTerminated()) {
3355 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003356 } else { // inactive but not terminated
3357 char buffer[256];
3358 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3359 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003360 }
3361 }
3362 }
3363
3364}
Eric Laurent81784c32012-11-19 14:55:58 -08003365
Eric Laurentaccc1472013-09-20 09:36:34 -07003366status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3367{
3368 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003369 ExtendedTimestamp ets;
3370 status_t status = mNormalSink->getTimestamp(ets);
3371 if (status == NO_ERROR) {
3372 status = ets.getBestTimestamp(&timestamp);
3373 }
3374 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003375 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003376 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003377 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003378 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003379 timestamp.mPosition = (uint32_t)position64;
3380 return NO_ERROR;
3381 }
3382 }
3383 return INVALID_OPERATION;
3384}
Eric Laurent1c333e22014-05-20 10:48:17 -07003385
Eric Laurent054d9d32015-04-24 08:48:48 -07003386status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3387 audio_patch_handle_t *handle)
3388{
Andy Hungf60abce2016-08-26 11:37:54 -07003389 status_t status;
3390 if (property_get_bool("af.patch_park", false /* default_value */)) {
3391 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3392 // or if HAL does not properly lock against access.
3393 AutoPark<FastMixer> park(mFastMixer);
3394 status = PlaybackThread::createAudioPatch_l(patch, handle);
3395 } else {
3396 status = PlaybackThread::createAudioPatch_l(patch, handle);
3397 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003398 return status;
3399}
3400
Eric Laurent1c333e22014-05-20 10:48:17 -07003401status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3402 audio_patch_handle_t *handle)
3403{
3404 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003405
3406 // store new device and send to effects
3407 audio_devices_t type = AUDIO_DEVICE_NONE;
3408 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3409 type |= patch->sinks[i].ext.device.type;
3410 }
3411
3412#ifdef ADD_BATTERY_DATA
3413 // when changing the audio output device, call addBatteryData to notify
3414 // the change
3415 if (mOutDevice != type) {
3416 uint32_t params = 0;
3417 // check whether speaker is on
3418 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3419 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003420 }
3421
Eric Laurent054d9d32015-04-24 08:48:48 -07003422 audio_devices_t deviceWithoutSpeaker
3423 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3424 // check if any other device (except speaker) is on
3425 if (type & deviceWithoutSpeaker) {
3426 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3427 }
3428
3429 if (params != 0) {
3430 addBatteryData(params);
3431 }
3432 }
3433#endif
3434
3435 for (size_t i = 0; i < mEffectChains.size(); i++) {
3436 mEffectChains[i]->setDevice_l(type);
3437 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003438
3439 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3440 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3441 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003442 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003443 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003444
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003445 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003446 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3447 status = hwDevice->createAudioPatch(patch->num_sources,
3448 patch->sources,
3449 patch->num_sinks,
3450 patch->sinks,
3451 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003452 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003453 char *address;
3454 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3455 //FIXME: we only support address on first sink with HAL version < 3.0
3456 address = audio_device_address_to_parameter(
3457 patch->sinks[0].ext.device.type,
3458 patch->sinks[0].ext.device.address);
3459 } else {
3460 address = (char *)calloc(1, 1);
3461 }
3462 AudioParameter param = AudioParameter(String8(address));
3463 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003464 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003465 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003466 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003467 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003468 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003469 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003470 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3471 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003472 return status;
3473}
3474
Eric Laurent054d9d32015-04-24 08:48:48 -07003475status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3476{
Andy Hungf60abce2016-08-26 11:37:54 -07003477 status_t status;
3478 if (property_get_bool("af.patch_park", false /* default_value */)) {
3479 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3480 // or if HAL does not properly lock against access.
3481 AutoPark<FastMixer> park(mFastMixer);
3482 status = PlaybackThread::releaseAudioPatch_l(handle);
3483 } else {
3484 status = PlaybackThread::releaseAudioPatch_l(handle);
3485 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003486 return status;
3487}
3488
Eric Laurent1c333e22014-05-20 10:48:17 -07003489status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3490{
3491 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003492
3493 mOutDevice = AUDIO_DEVICE_NONE;
3494
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003495 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003496 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3497 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003498 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003499 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003500 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003501 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003502 }
3503 return status;
3504}
3505
Eric Laurent83b88082014-06-20 18:31:16 -07003506void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3507{
3508 Mutex::Autolock _l(mLock);
3509 mTracks.add(track);
3510}
3511
3512void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3513{
3514 Mutex::Autolock _l(mLock);
3515 destroyTrack_l(track);
3516}
3517
3518void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3519{
3520 ThreadBase::getAudioPortConfig(config);
3521 config->role = AUDIO_PORT_ROLE_SOURCE;
3522 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3523 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3524}
3525
Eric Laurent81784c32012-11-19 14:55:58 -08003526// ----------------------------------------------------------------------------
3527
3528AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003529 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3530 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003531 // mAudioMixer below
3532 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003533 mFastMixerFutex(0),
3534 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003535 // mOutputSink below
3536 // mPipeSink below
3537 // mNormalSink below
3538{
3539 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003540 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3541 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003542 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3543 mNormalFrameCount);
3544 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3545
Andy Hungfbfc3952015-01-15 13:33:51 -08003546 if (type == DUPLICATING) {
3547 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3548 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3549 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3550 return;
3551 }
Eric Laurent81784c32012-11-19 14:55:58 -08003552 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003553 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003554 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003555 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003556#if !LOG_NDEBUG
3557 ssize_t index =
3558#else
3559 (void)
3560#endif
3561 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003562 ALOG_ASSERT(index == 0);
3563
3564 // initialize fast mixer depending on configuration
3565 bool initFastMixer;
3566 switch (kUseFastMixer) {
3567 case FastMixer_Never:
3568 initFastMixer = false;
3569 break;
3570 case FastMixer_Always:
3571 initFastMixer = true;
3572 break;
3573 case FastMixer_Static:
3574 case FastMixer_Dynamic:
3575 initFastMixer = mFrameCount < mNormalFrameCount;
3576 break;
3577 }
3578 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003579 audio_format_t fastMixerFormat;
3580 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3581 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3582 } else {
3583 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3584 }
3585 if (mFormat != fastMixerFormat) {
3586 // change our Sink format to accept our intermediate precision
3587 mFormat = fastMixerFormat;
3588 free(mSinkBuffer);
3589 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3590 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3591 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3592 }
Eric Laurent81784c32012-11-19 14:55:58 -08003593
3594 // create a MonoPipe to connect our submix to FastMixer
3595 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003596#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003597 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003598#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003599 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003600 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003601 format.mFormat = fastMixerFormat;
3602 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3603
Eric Laurent81784c32012-11-19 14:55:58 -08003604 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3605 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3606 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3607 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3608 const NBAIO_Format offers[1] = {format};
3609 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003610#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003611 ssize_t index =
3612#else
3613 (void)
3614#endif
3615 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003616 ALOG_ASSERT(index == 0);
3617 monoPipe->setAvgFrames((mScreenState & 1) ?
3618 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3619 mPipeSink = monoPipe;
3620
Glenn Kasten46909e72013-02-26 09:20:22 -08003621#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003622 if (mTeeSinkOutputEnabled) {
3623 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003624 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3625 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003626 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003627 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003628 ALOG_ASSERT(index == 0);
3629 mTeeSink = teeSink;
3630 PipeReader *teeSource = new PipeReader(*teeSink);
3631 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003632 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003633 ALOG_ASSERT(index == 0);
3634 mTeeSource = teeSource;
3635 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003636#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003637
3638 // create fast mixer and configure it initially with just one fast track for our submix
3639 mFastMixer = new FastMixer();
3640 FastMixerStateQueue *sq = mFastMixer->sq();
3641#ifdef STATE_QUEUE_DUMP
3642 sq->setObserverDump(&mStateQueueObserverDump);
3643 sq->setMutatorDump(&mStateQueueMutatorDump);
3644#endif
3645 FastMixerState *state = sq->begin();
3646 FastTrack *fastTrack = &state->mFastTracks[0];
3647 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3648 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3649 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003650 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3651 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003652 fastTrack->mGeneration++;
3653 state->mFastTracksGen++;
3654 state->mTrackMask = 1;
3655 // fast mixer will use the HAL output sink
3656 state->mOutputSink = mOutputSink.get();
3657 state->mOutputSinkGen++;
3658 state->mFrameCount = mFrameCount;
3659 state->mCommand = FastMixerState::COLD_IDLE;
3660 // already done in constructor initialization list
3661 //mFastMixerFutex = 0;
3662 state->mColdFutexAddr = &mFastMixerFutex;
3663 state->mColdGen++;
3664 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003665#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003666 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003667#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003668 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3669 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003670 sq->end();
3671 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3672
3673 // start the fast mixer
3674 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3675 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003676 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003677 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003678
3679#ifdef AUDIO_WATCHDOG
3680 // create and start the watchdog
3681 mAudioWatchdog = new AudioWatchdog();
3682 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3683 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3684 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003685 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003686#endif
3687
Eric Laurent81784c32012-11-19 14:55:58 -08003688 }
3689
3690 switch (kUseFastMixer) {
3691 case FastMixer_Never:
3692 case FastMixer_Dynamic:
3693 mNormalSink = mOutputSink;
3694 break;
3695 case FastMixer_Always:
3696 mNormalSink = mPipeSink;
3697 break;
3698 case FastMixer_Static:
3699 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3700 break;
3701 }
3702}
3703
3704AudioFlinger::MixerThread::~MixerThread()
3705{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003706 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003707 FastMixerStateQueue *sq = mFastMixer->sq();
3708 FastMixerState *state = sq->begin();
3709 if (state->mCommand == FastMixerState::COLD_IDLE) {
3710 int32_t old = android_atomic_inc(&mFastMixerFutex);
3711 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003712 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003713 }
3714 }
3715 state->mCommand = FastMixerState::EXIT;
3716 sq->end();
3717 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3718 mFastMixer->join();
3719 // Though the fast mixer thread has exited, it's state queue is still valid.
3720 // We'll use that extract the final state which contains one remaining fast track
3721 // corresponding to our sub-mix.
3722 state = sq->begin();
3723 ALOG_ASSERT(state->mTrackMask == 1);
3724 FastTrack *fastTrack = &state->mFastTracks[0];
3725 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3726 delete fastTrack->mBufferProvider;
3727 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003728 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003729#ifdef AUDIO_WATCHDOG
3730 if (mAudioWatchdog != 0) {
3731 mAudioWatchdog->requestExit();
3732 mAudioWatchdog->requestExitAndWait();
3733 mAudioWatchdog.clear();
3734 }
3735#endif
3736 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003737 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003738 delete mAudioMixer;
3739}
3740
3741
3742uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3743{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003744 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003745 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3746 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3747 }
3748 return latency;
3749}
3750
3751
3752void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3753{
3754 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3755}
3756
Eric Laurentbfb1b832013-01-07 09:53:42 -08003757ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003758{
3759 // FIXME we should only do one push per cycle; confirm this is true
3760 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003761 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003762 FastMixerStateQueue *sq = mFastMixer->sq();
3763 FastMixerState *state = sq->begin();
3764 if (state->mCommand != FastMixerState::MIX_WRITE &&
3765 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3766 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003767
3768 // FIXME workaround for first HAL write being CPU bound on some devices
3769 ATRACE_BEGIN("write");
3770 mOutput->write((char *)mSinkBuffer, 0);
3771 ATRACE_END();
3772
Eric Laurent81784c32012-11-19 14:55:58 -08003773 int32_t old = android_atomic_inc(&mFastMixerFutex);
3774 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003775 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003776 }
3777#ifdef AUDIO_WATCHDOG
3778 if (mAudioWatchdog != 0) {
3779 mAudioWatchdog->resume();
3780 }
3781#endif
3782 }
3783 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003784#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003785 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003786 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003787#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003788 sq->end();
3789 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3790 if (kUseFastMixer == FastMixer_Dynamic) {
3791 mNormalSink = mPipeSink;
3792 }
3793 } else {
3794 sq->end(false /*didModify*/);
3795 }
3796 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003797 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003798}
3799
3800void AudioFlinger::MixerThread::threadLoop_standby()
3801{
3802 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003803 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003804 FastMixerStateQueue *sq = mFastMixer->sq();
3805 FastMixerState *state = sq->begin();
3806 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003807 // Report any frames trapped in the Monopipe
3808 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3809 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3810 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3811 "monoPipeWritten:%lld monoPipeLeft:%lld",
3812 (long long)mFramesWritten, (long long)mSuspendedFrames,
3813 (long long)mPipeSink->framesWritten(), pipeFrames);
3814 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3815
Eric Laurent81784c32012-11-19 14:55:58 -08003816 state->mCommand = FastMixerState::COLD_IDLE;
3817 state->mColdFutexAddr = &mFastMixerFutex;
3818 state->mColdGen++;
3819 mFastMixerFutex = 0;
3820 sq->end();
3821 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3822 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3823 if (kUseFastMixer == FastMixer_Dynamic) {
3824 mNormalSink = mOutputSink;
3825 }
3826#ifdef AUDIO_WATCHDOG
3827 if (mAudioWatchdog != 0) {
3828 mAudioWatchdog->pause();
3829 }
3830#endif
3831 } else {
3832 sq->end(false /*didModify*/);
3833 }
3834 }
3835 PlaybackThread::threadLoop_standby();
3836}
3837
Eric Laurentbfb1b832013-01-07 09:53:42 -08003838bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3839{
3840 return false;
3841}
3842
3843bool AudioFlinger::PlaybackThread::shouldStandby_l()
3844{
3845 return !mStandby;
3846}
3847
3848bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3849{
3850 Mutex::Autolock _l(mLock);
3851 return waitingAsyncCallback_l();
3852}
3853
Eric Laurent81784c32012-11-19 14:55:58 -08003854// shared by MIXER and DIRECT, overridden by DUPLICATING
3855void AudioFlinger::PlaybackThread::threadLoop_standby()
3856{
3857 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003858 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003859 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003860 // discard any pending drain or write ack by incrementing sequence
3861 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3862 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003863 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003864 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3865 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003866 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003867 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003868}
3869
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003870void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3871{
3872 ALOGV("signal playback thread");
3873 broadcast_l();
3874}
3875
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003876void AudioFlinger::PlaybackThread::onAsyncError()
3877{
3878 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3879 invalidateTracks((audio_stream_type_t)i);
3880 }
3881}
3882
Eric Laurent81784c32012-11-19 14:55:58 -08003883void AudioFlinger::MixerThread::threadLoop_mix()
3884{
Eric Laurent81784c32012-11-19 14:55:58 -08003885 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003886 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003887 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003888 // increase sleep time progressively when application underrun condition clears.
3889 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3890 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3891 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003892 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003893 sleepTimeShift--;
3894 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003895 mSleepTimeUs = 0;
3896 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003897 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003898
Eric Laurent81784c32012-11-19 14:55:58 -08003899}
3900
3901void AudioFlinger::MixerThread::threadLoop_sleepTime()
3902{
3903 // If no tracks are ready, sleep once for the duration of an output
3904 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003905 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003906 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003907 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3908 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3909 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003910 }
3911 // reduce sleep time in case of consecutive application underruns to avoid
3912 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3913 // duration we would end up writing less data than needed by the audio HAL if
3914 // the condition persists.
3915 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3916 sleepTimeShift++;
3917 }
3918 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003919 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003920 }
3921 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003922 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3923 // before effects processing or output.
3924 if (mMixerBufferValid) {
3925 memset(mMixerBuffer, 0, mMixerBufferSize);
3926 } else {
3927 memset(mSinkBuffer, 0, mSinkBufferSize);
3928 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003929 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003930 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3931 "anticipated start");
3932 }
3933 // TODO add standby time extension fct of effect tail
3934}
3935
3936// prepareTracks_l() must be called with ThreadBase::mLock held
3937AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3938 Vector< sp<Track> > *tracksToRemove)
3939{
3940
3941 mixer_state mixerStatus = MIXER_IDLE;
3942 // find out which tracks need to be processed
3943 size_t count = mActiveTracks.size();
3944 size_t mixedTracks = 0;
3945 size_t tracksWithEffect = 0;
3946 // counts only _active_ fast tracks
3947 size_t fastTracks = 0;
3948 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3949
3950 float masterVolume = mMasterVolume;
3951 bool masterMute = mMasterMute;
3952
3953 if (masterMute) {
3954 masterVolume = 0;
3955 }
3956 // Delegate master volume control to effect in output mix effect chain if needed
3957 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3958 if (chain != 0) {
3959 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3960 chain->setVolume_l(&v, &v);
3961 masterVolume = (float)((v + (1 << 23)) >> 24);
3962 chain.clear();
3963 }
3964
3965 // prepare a new state to push
3966 FastMixerStateQueue *sq = NULL;
3967 FastMixerState *state = NULL;
3968 bool didModify = false;
3969 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003970 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003971 sq = mFastMixer->sq();
3972 state = sq->begin();
3973 }
3974
Andy Hung69aed5f2014-02-25 17:24:40 -08003975 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003976 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003977
Eric Laurent81784c32012-11-19 14:55:58 -08003978 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07003979 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003980
3981 // this const just means the local variable doesn't change
3982 Track* const track = t.get();
3983
3984 // process fast tracks
3985 if (track->isFastTrack()) {
3986
3987 // It's theoretically possible (though unlikely) for a fast track to be created
3988 // and then removed within the same normal mix cycle. This is not a problem, as
3989 // the track never becomes active so it's fast mixer slot is never touched.
3990 // The converse, of removing an (active) track and then creating a new track
3991 // at the identical fast mixer slot within the same normal mix cycle,
3992 // is impossible because the slot isn't marked available until the end of each cycle.
3993 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003994 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003995 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3996 FastTrack *fastTrack = &state->mFastTracks[j];
3997
3998 // Determine whether the track is currently in underrun condition,
3999 // and whether it had a recent underrun.
4000 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4001 FastTrackUnderruns underruns = ftDump->mUnderruns;
4002 uint32_t recentFull = (underruns.mBitFields.mFull -
4003 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4004 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4005 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4006 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4007 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4008 uint32_t recentUnderruns = recentPartial + recentEmpty;
4009 track->mObservedUnderruns = underruns;
4010 // don't count underruns that occur while stopping or pausing
4011 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004012 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4013 recentUnderruns > 0) {
4014 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4015 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004016 } else {
4017 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004018 }
4019
4020 // This is similar to the state machine for normal tracks,
4021 // with a few modifications for fast tracks.
4022 bool isActive = true;
4023 switch (track->mState) {
4024 case TrackBase::STOPPING_1:
4025 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004026 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004027 track->mState = TrackBase::STOPPING_2;
4028 }
4029 break;
4030 case TrackBase::PAUSING:
4031 // ramp down is not yet implemented
4032 track->setPaused();
4033 break;
4034 case TrackBase::RESUMING:
4035 // ramp up is not yet implemented
4036 track->mState = TrackBase::ACTIVE;
4037 break;
4038 case TrackBase::ACTIVE:
4039 if (recentFull > 0 || recentPartial > 0) {
4040 // track has provided at least some frames recently: reset retry count
4041 track->mRetryCount = kMaxTrackRetries;
4042 }
4043 if (recentUnderruns == 0) {
4044 // no recent underruns: stay active
4045 break;
4046 }
4047 // there has recently been an underrun of some kind
4048 if (track->sharedBuffer() == 0) {
4049 // were any of the recent underruns "empty" (no frames available)?
4050 if (recentEmpty == 0) {
4051 // no, then ignore the partial underruns as they are allowed indefinitely
4052 break;
4053 }
4054 // there has recently been an "empty" underrun: decrement the retry counter
4055 if (--(track->mRetryCount) > 0) {
4056 break;
4057 }
4058 // indicate to client process that the track was disabled because of underrun;
4059 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004060 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004061 // remove from active list, but state remains ACTIVE [confusing but true]
4062 isActive = false;
4063 break;
4064 }
4065 // fall through
4066 case TrackBase::STOPPING_2:
4067 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004068 case TrackBase::STOPPED:
4069 case TrackBase::FLUSHED: // flush() while active
4070 // Check for presentation complete if track is inactive
4071 // We have consumed all the buffers of this track.
4072 // This would be incomplete if we auto-paused on underrun
4073 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004074 uint32_t latency = 0;
4075 status_t result = mOutput->stream->getLatency(&latency);
4076 ALOGE_IF(result != OK,
4077 "Error when retrieving output stream latency: %d", result);
4078 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004079 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004080 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4081 // track stays in active list until presentation is complete
4082 break;
4083 }
4084 }
4085 if (track->isStopping_2()) {
4086 track->mState = TrackBase::STOPPED;
4087 }
4088 if (track->isStopped()) {
4089 // Can't reset directly, as fast mixer is still polling this track
4090 // track->reset();
4091 // So instead mark this track as needing to be reset after push with ack
4092 resetMask |= 1 << i;
4093 }
4094 isActive = false;
4095 break;
4096 case TrackBase::IDLE:
4097 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004098 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004099 }
4100
4101 if (isActive) {
4102 // was it previously inactive?
4103 if (!(state->mTrackMask & (1 << j))) {
4104 ExtendedAudioBufferProvider *eabp = track;
4105 VolumeProvider *vp = track;
4106 fastTrack->mBufferProvider = eabp;
4107 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004108 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004109 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004110 fastTrack->mGeneration++;
4111 state->mTrackMask |= 1 << j;
4112 didModify = true;
4113 // no acknowledgement required for newly active tracks
4114 }
4115 // cache the combined master volume and stream type volume for fast mixer; this
4116 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004117 const float vh = track->getVolumeHandler()->getVolume(
4118 track->mAudioTrackServerProxy->framesReleased());
4119 track->mCachedVolume = masterVolume
4120 * mStreamTypes[track->streamType()].volume
4121 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004122 ++fastTracks;
4123 } else {
4124 // was it previously active?
4125 if (state->mTrackMask & (1 << j)) {
4126 fastTrack->mBufferProvider = NULL;
4127 fastTrack->mGeneration++;
4128 state->mTrackMask &= ~(1 << j);
4129 didModify = true;
4130 // If any fast tracks were removed, we must wait for acknowledgement
4131 // because we're about to decrement the last sp<> on those tracks.
4132 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4133 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004134 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4135 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4136 j, track->mState, state->mTrackMask, recentUnderruns,
4137 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004138 }
4139 tracksToRemove->add(track);
4140 // Avoids a misleading display in dumpsys
4141 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4142 }
4143 continue;
4144 }
4145
4146 { // local variable scope to avoid goto warning
4147
4148 audio_track_cblk_t* cblk = track->cblk();
4149
4150 // The first time a track is added we wait
4151 // for all its buffers to be filled before processing it
4152 int name = track->name();
4153 // make sure that we have enough frames to mix one full buffer.
4154 // enforce this condition only once to enable draining the buffer in case the client
4155 // app does not call stop() and relies on underrun to stop:
4156 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4157 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004158 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004159 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004160 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004161
4162 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004163 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004164 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4165 // add frames already consumed but not yet released by the resampler
4166 // because mAudioTrackServerProxy->framesReady() will include these frames
4167 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4168
Eric Laurent81784c32012-11-19 14:55:58 -08004169 uint32_t minFrames = 1;
4170 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4171 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004172 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004173 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004174
4175 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004176 if (ATRACE_ENABLED()) {
4177 // I wish we had formatted trace names
4178 char traceName[16];
4179 strcpy(traceName, "nRdy");
4180 int name = track->name();
4181 if (AudioMixer::TRACK0 <= name &&
4182 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4183 name -= AudioMixer::TRACK0;
4184 traceName[4] = (name / 10) + '0';
4185 traceName[5] = (name % 10) + '0';
4186 } else {
4187 traceName[4] = '?';
4188 traceName[5] = '?';
4189 }
4190 traceName[6] = '\0';
4191 ATRACE_INT(traceName, framesReady);
4192 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004193 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004194 !track->isPaused() && !track->isTerminated())
4195 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004196 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004197
4198 mixedTracks++;
4199
Andy Hung69aed5f2014-02-25 17:24:40 -08004200 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4201 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004202 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004203 if (track->mainBuffer() != mSinkBuffer &&
4204 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004205 if (mEffectBufferEnabled) {
4206 mEffectBufferValid = true; // Later can set directly.
4207 }
Eric Laurent81784c32012-11-19 14:55:58 -08004208 chain = getEffectChain_l(track->sessionId());
4209 // Delegate volume control to effect in track effect chain if needed
4210 if (chain != 0) {
4211 tracksWithEffect++;
4212 } else {
4213 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4214 "session %d",
4215 name, track->sessionId());
4216 }
4217 }
4218
4219
4220 int param = AudioMixer::VOLUME;
4221 if (track->mFillingUpStatus == Track::FS_FILLED) {
4222 // no ramp for the first volume setting
4223 track->mFillingUpStatus = Track::FS_ACTIVE;
4224 if (track->mState == TrackBase::RESUMING) {
4225 track->mState = TrackBase::ACTIVE;
4226 param = AudioMixer::RAMP_VOLUME;
4227 }
4228 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004229 // FIXME should not make a decision based on mServer
4230 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004231 // If the track is stopped before the first frame was mixed,
4232 // do not apply ramp
4233 param = AudioMixer::RAMP_VOLUME;
4234 }
4235
4236 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004237 uint32_t vl, vr; // in U8.24 integer format
4238 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004239 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004240 vl = vr = 0;
4241 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004242 if (track->isPausing()) {
4243 track->setPaused();
4244 }
4245 } else {
4246
4247 // read original volumes with volume control
4248 float typeVolume = mStreamTypes[track->streamType()].volume;
4249 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004250 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004251 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004252 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4253 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004254 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004255 if (vlf > GAIN_FLOAT_UNITY) {
4256 ALOGV("Track left volume out of range: %.3g", vlf);
4257 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004258 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004259 if (vrf > GAIN_FLOAT_UNITY) {
4260 ALOGV("Track right volume out of range: %.3g", vrf);
4261 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004262 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004263 const float vh = track->getVolumeHandler()->getVolume(
4264 track->mAudioTrackServerProxy->framesReleased());
4265 // now apply the master volume and stream type volume and shaper volume
4266 vlf *= v * vh;
4267 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004268 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004269 // then derive vl and vr as U8.24 versions for the effect chain
4270 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4271 vl = (uint32_t) (scaleto8_24 * vlf);
4272 vr = (uint32_t) (scaleto8_24 * vrf);
4273 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004274 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004275 // send level comes from shared memory and so may be corrupt
4276 if (sendLevel > MAX_GAIN_INT) {
4277 ALOGV("Track send level out of range: %04X", sendLevel);
4278 sendLevel = MAX_GAIN_INT;
4279 }
Andy Hung6be49402014-05-30 10:42:03 -07004280 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4281 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004282 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004283
Eric Laurent81784c32012-11-19 14:55:58 -08004284 // Delegate volume control to effect in track effect chain if needed
4285 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4286 // Do not ramp volume if volume is controlled by effect
4287 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004288 // Update remaining floating point volume levels
4289 vlf = (float)vl / (1 << 24);
4290 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004291 track->mHasVolumeController = true;
4292 } else {
4293 // force no volume ramp when volume controller was just disabled or removed
4294 // from effect chain to avoid volume spike
4295 if (track->mHasVolumeController) {
4296 param = AudioMixer::VOLUME;
4297 }
4298 track->mHasVolumeController = false;
4299 }
4300
Eric Laurent81784c32012-11-19 14:55:58 -08004301 // XXX: these things DON'T need to be done each time
4302 mAudioMixer->setBufferProvider(name, track);
4303 mAudioMixer->enable(name);
4304
Andy Hung6be49402014-05-30 10:42:03 -07004305 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4306 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4307 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004308 mAudioMixer->setParameter(
4309 name,
4310 AudioMixer::TRACK,
4311 AudioMixer::FORMAT, (void *)track->format());
4312 mAudioMixer->setParameter(
4313 name,
4314 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004315 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004316 mAudioMixer->setParameter(
4317 name,
4318 AudioMixer::TRACK,
4319 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004320 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004321 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004322 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004323 if (reqSampleRate == 0) {
4324 reqSampleRate = mSampleRate;
4325 } else if (reqSampleRate > maxSampleRate) {
4326 reqSampleRate = maxSampleRate;
4327 }
Eric Laurent81784c32012-11-19 14:55:58 -08004328 mAudioMixer->setParameter(
4329 name,
4330 AudioMixer::RESAMPLE,
4331 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004332 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004333
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004334 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004335 mAudioMixer->setParameter(
4336 name,
4337 AudioMixer::TIMESTRETCH,
4338 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004339 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004340
Andy Hung69aed5f2014-02-25 17:24:40 -08004341 /*
4342 * Select the appropriate output buffer for the track.
4343 *
Andy Hung98ef9782014-03-04 14:46:50 -08004344 * Tracks with effects go into their own effects chain buffer
4345 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004346 *
4347 * Other tracks can use mMixerBuffer for higher precision
4348 * channel accumulation. If this buffer is enabled
4349 * (mMixerBufferEnabled true), then selected tracks will accumulate
4350 * into it.
4351 *
4352 */
4353 if (mMixerBufferEnabled
4354 && (track->mainBuffer() == mSinkBuffer
4355 || track->mainBuffer() == mMixerBuffer)) {
4356 mAudioMixer->setParameter(
4357 name,
4358 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004359 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004360 mAudioMixer->setParameter(
4361 name,
4362 AudioMixer::TRACK,
4363 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4364 // TODO: override track->mainBuffer()?
4365 mMixerBufferValid = true;
4366 } else {
4367 mAudioMixer->setParameter(
4368 name,
4369 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004370 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004371 mAudioMixer->setParameter(
4372 name,
4373 AudioMixer::TRACK,
4374 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4375 }
Eric Laurent81784c32012-11-19 14:55:58 -08004376 mAudioMixer->setParameter(
4377 name,
4378 AudioMixer::TRACK,
4379 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4380
4381 // reset retry count
4382 track->mRetryCount = kMaxTrackRetries;
4383
4384 // If one track is ready, set the mixer ready if:
4385 // - the mixer was not ready during previous round OR
4386 // - no other track is not ready
4387 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4388 mixerStatus != MIXER_TRACKS_ENABLED) {
4389 mixerStatus = MIXER_TRACKS_READY;
4390 }
4391 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004392 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004393 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4394 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004395 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004396 } else {
4397 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004398 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004399
Eric Laurent81784c32012-11-19 14:55:58 -08004400 // clear effect chain input buffer if an active track underruns to avoid sending
4401 // previous audio buffer again to effects
4402 chain = getEffectChain_l(track->sessionId());
4403 if (chain != 0) {
4404 chain->clearInputBuffer();
4405 }
4406
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004407 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004408 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4409 track->isStopped() || track->isPaused()) {
4410 // We have consumed all the buffers of this track.
4411 // Remove it from the list of active tracks.
4412 // TODO: use actual buffer filling status instead of latency when available from
4413 // audio HAL
4414 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004415 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004416 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4417 if (track->isStopped()) {
4418 track->reset();
4419 }
4420 tracksToRemove->add(track);
4421 }
4422 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004423 // No buffers for this track. Give it a few chances to
4424 // fill a buffer, then remove it from active list.
4425 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004426 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004427 tracksToRemove->add(track);
4428 // indicate to client process that the track was disabled because of underrun;
4429 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004430 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004431 // If one track is not ready, mark the mixer also not ready if:
4432 // - the mixer was ready during previous round OR
4433 // - no other track is ready
4434 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4435 mixerStatus != MIXER_TRACKS_READY) {
4436 mixerStatus = MIXER_TRACKS_ENABLED;
4437 }
4438 }
4439 mAudioMixer->disable(name);
4440 }
4441
4442 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004443
4444 }
4445
4446 // Push the new FastMixer state if necessary
4447 bool pauseAudioWatchdog = false;
4448 if (didModify) {
4449 state->mFastTracksGen++;
4450 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4451 if (kUseFastMixer == FastMixer_Dynamic &&
4452 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4453 state->mCommand = FastMixerState::COLD_IDLE;
4454 state->mColdFutexAddr = &mFastMixerFutex;
4455 state->mColdGen++;
4456 mFastMixerFutex = 0;
4457 if (kUseFastMixer == FastMixer_Dynamic) {
4458 mNormalSink = mOutputSink;
4459 }
4460 // If we go into cold idle, need to wait for acknowledgement
4461 // so that fast mixer stops doing I/O.
4462 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4463 pauseAudioWatchdog = true;
4464 }
Eric Laurent81784c32012-11-19 14:55:58 -08004465 }
4466 if (sq != NULL) {
4467 sq->end(didModify);
4468 sq->push(block);
4469 }
4470#ifdef AUDIO_WATCHDOG
4471 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4472 mAudioWatchdog->pause();
4473 }
4474#endif
4475
4476 // Now perform the deferred reset on fast tracks that have stopped
4477 while (resetMask != 0) {
4478 size_t i = __builtin_ctz(resetMask);
4479 ALOG_ASSERT(i < count);
4480 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004481 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004482 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4483 track->reset();
4484 }
4485
4486 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004487 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004488
Eric Laurent97d547d2014-09-02 14:45:53 -07004489 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4490 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004491 }
4492
4493 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004494 // as long as there are effects we should clear the effects buffer, to avoid
4495 // passing a non-clean buffer to the effect chain
4496 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004497 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004498 // sink or mix buffer must be cleared if all tracks are connected to an
4499 // effect chain as in this case the mixer will not write to the sink or mix buffer
4500 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004501 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4502 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004503 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004504 if (mMixerBufferValid) {
4505 memset(mMixerBuffer, 0, mMixerBufferSize);
4506 // TODO: In testing, mSinkBuffer below need not be cleared because
4507 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4508 // after mixing.
4509 //
4510 // To enforce this guarantee:
4511 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4512 // (mixedTracks == 0 && fastTracks > 0))
4513 // must imply MIXER_TRACKS_READY.
4514 // Later, we may clear buffers regardless, and skip much of this logic.
4515 }
Andy Hung98ef9782014-03-04 14:46:50 -08004516 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004517 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004518 }
4519
4520 // if any fast tracks, then status is ready
4521 mMixerStatusIgnoringFastTracks = mixerStatus;
4522 if (fastTracks > 0) {
4523 mixerStatus = MIXER_TRACKS_READY;
4524 }
4525 return mixerStatus;
4526}
4527
Eric Laurentad7dd962016-09-22 12:38:37 -07004528// trackCountForUid_l() must be called with ThreadBase::mLock held
4529uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4530{
4531 uint32_t trackCount = 0;
4532 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004533 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004534 trackCount++;
4535 }
4536 }
4537 return trackCount;
4538}
4539
Eric Laurent81784c32012-11-19 14:55:58 -08004540// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004541int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004542 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004543{
Eric Laurentad7dd962016-09-22 12:38:37 -07004544 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4545 return -1;
4546 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004547 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004548}
4549
4550// deleteTrackName_l() must be called with ThreadBase::mLock held
4551void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4552{
4553 ALOGV("remove track (%d) and delete from mixer", name);
4554 mAudioMixer->deleteTrackName(name);
4555}
4556
Eric Laurent10351942014-05-08 18:49:52 -07004557// checkForNewParameter_l() must be called with ThreadBase::mLock held
4558bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4559 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004560{
Eric Laurent81784c32012-11-19 14:55:58 -08004561 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004562 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004563
Eric Laurent10351942014-05-08 18:49:52 -07004564 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004565
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004566 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004567
Eric Laurent10351942014-05-08 18:49:52 -07004568 AudioParameter param = AudioParameter(keyValuePair);
4569 int value;
4570 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4571 reconfig = true;
4572 }
4573 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004574 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004575 status = BAD_VALUE;
4576 } else {
4577 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004578 reconfig = true;
4579 }
Eric Laurent10351942014-05-08 18:49:52 -07004580 }
4581 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004582 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004583 status = BAD_VALUE;
4584 } else {
4585 // no need to save value, since it's constant
4586 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004587 }
Eric Laurent10351942014-05-08 18:49:52 -07004588 }
4589 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4590 // do not accept frame count changes if tracks are open as the track buffer
4591 // size depends on frame count and correct behavior would not be guaranteed
4592 // if frame count is changed after track creation
4593 if (!mTracks.isEmpty()) {
4594 status = INVALID_OPERATION;
4595 } else {
4596 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004597 }
Eric Laurent10351942014-05-08 18:49:52 -07004598 }
4599 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004600#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004601 // when changing the audio output device, call addBatteryData to notify
4602 // the change
4603 if (mOutDevice != value) {
4604 uint32_t params = 0;
4605 // check whether speaker is on
4606 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4607 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004608 }
Eric Laurent10351942014-05-08 18:49:52 -07004609
4610 audio_devices_t deviceWithoutSpeaker
4611 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4612 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004613 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004614 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4615 }
4616
4617 if (params != 0) {
4618 addBatteryData(params);
4619 }
4620 }
Eric Laurent81784c32012-11-19 14:55:58 -08004621#endif
4622
Eric Laurent10351942014-05-08 18:49:52 -07004623 // forward device change to effects that have requested to be
4624 // aware of attached audio device.
4625 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004626 a2dpDeviceChanged =
4627 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004628 mOutDevice = value;
4629 for (size_t i = 0; i < mEffectChains.size(); i++) {
4630 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004631 }
4632 }
Eric Laurent10351942014-05-08 18:49:52 -07004633 }
Eric Laurent81784c32012-11-19 14:55:58 -08004634
Eric Laurent10351942014-05-08 18:49:52 -07004635 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004636 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004637 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004638 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004639 mStandby = true;
4640 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004641 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004642 }
Eric Laurent10351942014-05-08 18:49:52 -07004643 if (status == NO_ERROR && reconfig) {
4644 readOutputParameters_l();
4645 delete mAudioMixer;
4646 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4647 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004648 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004649 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004650 if (name < 0) {
4651 break;
4652 }
4653 mTracks[i]->mName = name;
4654 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004655 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004656 }
Eric Laurent81784c32012-11-19 14:55:58 -08004657 }
4658
Eric Laurent42537be2016-01-08 17:16:42 -08004659 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004660}
4661
4662
4663void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4664{
Eric Laurent81784c32012-11-19 14:55:58 -08004665 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004666 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004667 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004668 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004669
4670 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004671 // while we are dumping it. It may be inconsistent, but it won't mutate!
4672 // This is a large object so we place it on the heap.
4673 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4674 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4675 copy->dump(fd);
4676 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004677
4678#ifdef STATE_QUEUE_DUMP
4679 // Similar for state queue
4680 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4681 observerCopy.dump(fd);
4682 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4683 mutatorCopy.dump(fd);
4684#endif
4685
Glenn Kasten46909e72013-02-26 09:20:22 -08004686#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004687 // Write the tee output to a .wav file
4688 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004689#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004690
4691#ifdef AUDIO_WATCHDOG
4692 if (mAudioWatchdog != 0) {
4693 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4694 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4695 wdCopy.dump(fd);
4696 }
4697#endif
4698}
4699
4700uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4701{
4702 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4703}
4704
4705uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4706{
4707 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4708}
4709
4710void AudioFlinger::MixerThread::cacheParameters_l()
4711{
4712 PlaybackThread::cacheParameters_l();
4713
4714 // FIXME: Relaxed timing because of a certain device that can't meet latency
4715 // Should be reduced to 2x after the vendor fixes the driver issue
4716 // increase threshold again due to low power audio mode. The way this warning
4717 // threshold is calculated and its usefulness should be reconsidered anyway.
4718 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4719}
4720
4721// ----------------------------------------------------------------------------
4722
4723AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004724 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4725 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004726 // mLeftVolFloat, mRightVolFloat
4727{
4728}
4729
Eric Laurentbfb1b832013-01-07 09:53:42 -08004730AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4731 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004732 ThreadBase::type_t type, bool systemReady)
4733 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004734 // mLeftVolFloat, mRightVolFloat
4735{
4736}
4737
Eric Laurent81784c32012-11-19 14:55:58 -08004738AudioFlinger::DirectOutputThread::~DirectOutputThread()
4739{
4740}
4741
Eric Laurent5850c4c2016-11-10 13:04:31 -08004742void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004743{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004744 float left, right;
4745
4746 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4747 left = right = 0;
4748 } else {
4749 float typeVolume = mStreamTypes[track->streamType()].volume;
4750 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004751 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004752
4753 if (audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4754 const float vh = track->getVolumeHandler()->getVolume(
4755 track->mAudioTrackServerProxy->framesReleased());
4756 v *= vh;
4757 } else {
4758 // TODO: implement volume scaling in HW
4759 }
4760
Glenn Kastenc56f3422014-03-21 17:53:17 -07004761 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4762 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4763 if (left > GAIN_FLOAT_UNITY) {
4764 left = GAIN_FLOAT_UNITY;
4765 }
4766 left *= v;
4767 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4768 if (right > GAIN_FLOAT_UNITY) {
4769 right = GAIN_FLOAT_UNITY;
4770 }
4771 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004772 }
4773
4774 if (lastTrack) {
4775 if (left != mLeftVolFloat || right != mRightVolFloat) {
4776 mLeftVolFloat = left;
4777 mRightVolFloat = right;
4778
4779 // Convert volumes from float to 8.24
4780 uint32_t vl = (uint32_t)(left * (1 << 24));
4781 uint32_t vr = (uint32_t)(right * (1 << 24));
4782
4783 // Delegate volume control to effect in track effect chain if needed
4784 // only one effect chain can be present on DirectOutputThread, so if
4785 // there is one, the track is connected to it
4786 if (!mEffectChains.isEmpty()) {
4787 mEffectChains[0]->setVolume_l(&vl, &vr);
4788 left = (float)vl / (1 << 24);
4789 right = (float)vr / (1 << 24);
4790 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004791 status_t result = mOutput->stream->setVolume(left, right);
4792 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004793 }
4794 }
4795}
4796
Phil Burk43b4dcc2015-06-09 16:53:44 -07004797void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4798{
4799 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004800 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004801
Eric Laurent0f0631e2015-07-06 18:01:25 -07004802 if (previousTrack != 0 && latestTrack != 0) {
4803 if (mType == DIRECT) {
4804 if (previousTrack.get() != latestTrack.get()) {
4805 mFlushPending = true;
4806 }
4807 } else /* mType == OFFLOAD */ {
4808 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4809 mFlushPending = true;
4810 }
4811 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004812 }
4813 PlaybackThread::onAddNewTrack_l();
4814}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004815
Eric Laurent81784c32012-11-19 14:55:58 -08004816AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4817 Vector< sp<Track> > *tracksToRemove
4818)
4819{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004820 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004821 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004822 bool doHwPause = false;
4823 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004824
4825 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004826 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004827 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004828 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004829 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004830 continue;
4831 }
4832
Eric Laurent5850c4c2016-11-10 13:04:31 -08004833 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004834#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004835 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004836#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004837 // Only consider last track started for volume and mixer state control.
4838 // In theory an older track could underrun and restart after the new one starts
4839 // but as we only care about the transition phase between two tracks on a
4840 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004841 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004842 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004843
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004844 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004845 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004846 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004847 doHwPause = true;
4848 mHwPaused = true;
4849 }
4850 tracksToRemove->add(track);
4851 } else if (track->isFlushPending()) {
4852 track->flushAck();
4853 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004854 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004855 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004856 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004857 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004858 if (last) {
4859 mLeftVolFloat = mRightVolFloat = -1.0;
4860 if (mHwPaused) {
4861 doHwResume = true;
4862 mHwPaused = false;
4863 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004864 }
4865 }
4866
Eric Laurent81784c32012-11-19 14:55:58 -08004867 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004868 // for all its buffers to be filled before processing it.
4869 // Allow draining the buffer in case the client
4870 // app does not call stop() and relies on underrun to stop:
4871 // hence the test on (track->mRetryCount > 1).
4872 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004873 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004874 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004875 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004876 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004877 minFrames = mNormalFrameCount;
4878 } else {
4879 minFrames = 1;
4880 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004881
Eric Laurentab5cdba2014-06-09 17:22:27 -07004882 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4883 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004884 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004885 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004886
4887 if (track->mFillingUpStatus == Track::FS_FILLED) {
4888 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004889 if (last) {
4890 // make sure processVolume_l() will apply new volume even if 0
4891 mLeftVolFloat = mRightVolFloat = -1.0;
4892 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004893 if (!mHwSupportsPause) {
4894 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004895 }
4896 }
4897
4898 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004899 processVolume_l(track, last);
4900 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004901 sp<Track> previousTrack = mPreviousTrack.promote();
4902 if (previousTrack != 0) {
4903 if (track != previousTrack.get()) {
4904 // Flush any data still being written from last track
4905 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004906 // Invalidate previous track to force a seek when resuming.
4907 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004908 }
4909 }
4910 mPreviousTrack = track;
4911
Eric Laurentd595b7c2013-04-03 17:27:56 -07004912 // reset retry count
4913 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004914 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004915 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004916 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004917 doHwResume = true;
4918 mHwPaused = false;
4919 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004920 }
Eric Laurent81784c32012-11-19 14:55:58 -08004921 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004922 // clear effect chain input buffer if the last active track started underruns
4923 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004924 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004925 mEffectChains[0]->clearInputBuffer();
4926 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004927 if (track->isStopping_1()) {
4928 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004929 if (last && mHwPaused) {
4930 doHwResume = true;
4931 mHwPaused = false;
4932 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004933 }
4934 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4935 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004936 // We have consumed all the buffers of this track.
4937 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004938 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004939 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004940 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4941 } else {
4942 audioHALFrames = 0;
4943 }
4944
Andy Hung818e7a32016-02-16 18:08:07 -08004945 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004946 if (mStandby || !last ||
4947 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004948 if (track->isStopping_2()) {
4949 track->mState = TrackBase::STOPPED;
4950 }
Eric Laurent81784c32012-11-19 14:55:58 -08004951 if (track->isStopped()) {
4952 track->reset();
4953 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004954 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004955 }
4956 } else {
4957 // No buffers for this track. Give it a few chances to
4958 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004959 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004960 if (--(track->mRetryCount) <= 0) {
4961 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004962 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004963 // indicate to client process that the track was disabled because of underrun;
4964 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004965 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004966 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004967 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4968 "minFrames = %u, mFormat = %#x",
4969 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004970 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004971 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004972 doHwPause = true;
4973 mHwPaused = true;
4974 }
Eric Laurent81784c32012-11-19 14:55:58 -08004975 }
4976 }
4977 }
4978 }
4979
Eric Laurentd1f69b02014-12-15 14:33:13 -08004980 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004981 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004982 for (size_t i = 0; i < mTracks.size(); i++) {
4983 if (mTracks[i]->isFlushPending()) {
4984 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004985 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004986 }
4987 }
4988 }
4989
4990 // make sure the pause/flush/resume sequence is executed in the right order.
4991 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4992 // before flush and then resume HW. This can happen in case of pause/flush/resume
4993 // if resume is received before pause is executed.
4994 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004995 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004996 status_t result = mOutput->stream->pause();
4997 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004998 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004999 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005000 flushHw_l();
5001 }
5002 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005003 status_t result = mOutput->stream->resume();
5004 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005005 }
Eric Laurent81784c32012-11-19 14:55:58 -08005006 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005007 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005008
5009 return mixerStatus;
5010}
5011
5012void AudioFlinger::DirectOutputThread::threadLoop_mix()
5013{
Eric Laurent81784c32012-11-19 14:55:58 -08005014 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005015 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005016 // output audio to hardware
5017 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005018 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005019 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005020 status_t status = mActiveTrack->getNextBuffer(&buffer);
5021 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005022 // no need to pad with 0 for compressed audio
5023 if (audio_has_proportional_frames(mFormat)) {
5024 memset(curBuf, 0, frameCount * mFrameSize);
5025 }
Eric Laurent81784c32012-11-19 14:55:58 -08005026 break;
5027 }
5028 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5029 frameCount -= buffer.frameCount;
5030 curBuf += buffer.frameCount * mFrameSize;
5031 mActiveTrack->releaseBuffer(&buffer);
5032 }
Andy Hung2098f272014-02-27 14:00:06 -08005033 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005034 mSleepTimeUs = 0;
5035 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005036 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005037}
5038
5039void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5040{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005041 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005042 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005043 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005044 return;
5045 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005046 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005047 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005048 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005049 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005050 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005051 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005052 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005053 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005054 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005055 }
5056}
5057
Eric Laurentd1f69b02014-12-15 14:33:13 -08005058void AudioFlinger::DirectOutputThread::threadLoop_exit()
5059{
5060 {
5061 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005062 for (size_t i = 0; i < mTracks.size(); i++) {
5063 if (mTracks[i]->isFlushPending()) {
5064 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005065 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005066 }
5067 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005068 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005069 flushHw_l();
5070 }
5071 }
5072 PlaybackThread::threadLoop_exit();
5073}
5074
5075// must be called with thread mutex locked
5076bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5077{
5078 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005079 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005080
vivek mehta9cd7ad12016-03-17 00:18:29 -07005081 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5082 return !mStandby;
5083 }
5084
Eric Laurentd1f69b02014-12-15 14:33:13 -08005085 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5086 // after a timeout and we will enter standby then.
5087 if (mTracks.size() > 0) {
5088 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005089 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5090 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005091 }
5092
Eric Laurent5cff4032015-05-26 13:49:58 -07005093 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005094}
5095
Eric Laurent81784c32012-11-19 14:55:58 -08005096// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005097int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005098 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005099{
Eric Laurentad7dd962016-09-22 12:38:37 -07005100 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5101 return -1;
5102 }
Eric Laurent81784c32012-11-19 14:55:58 -08005103 return 0;
5104}
5105
5106// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005107void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005108{
5109}
5110
Eric Laurent10351942014-05-08 18:49:52 -07005111// checkForNewParameter_l() must be called with ThreadBase::mLock held
5112bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5113 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005114{
5115 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005116 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005117
Eric Laurent10351942014-05-08 18:49:52 -07005118 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005119
Eric Laurent10351942014-05-08 18:49:52 -07005120 AudioParameter param = AudioParameter(keyValuePair);
5121 int value;
5122 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5123 // forward device change to effects that have requested to be
5124 // aware of attached audio device.
5125 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005126 a2dpDeviceChanged =
5127 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005128 mOutDevice = value;
5129 for (size_t i = 0; i < mEffectChains.size(); i++) {
5130 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005131 }
5132 }
Eric Laurent81784c32012-11-19 14:55:58 -08005133 }
Eric Laurent10351942014-05-08 18:49:52 -07005134 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5135 // do not accept frame count changes if tracks are open as the track buffer
5136 // size depends on frame count and correct behavior would not be garantied
5137 // if frame count is changed after track creation
5138 if (!mTracks.isEmpty()) {
5139 status = INVALID_OPERATION;
5140 } else {
5141 reconfig = true;
5142 }
5143 }
5144 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005145 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005146 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005147 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005148 mStandby = true;
5149 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005150 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005151 }
5152 if (status == NO_ERROR && reconfig) {
5153 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005154 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005155 }
5156 }
5157
Eric Laurent42537be2016-01-08 17:16:42 -08005158 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005159}
5160
5161uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5162{
5163 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005164 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005165 time = PlaybackThread::activeSleepTimeUs();
5166 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005167 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005168 }
5169 return time;
5170}
5171
5172uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5173{
5174 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005175 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005176 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5177 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005178 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005179 }
5180 return time;
5181}
5182
5183uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5184{
5185 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005186 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005187 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5188 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005189 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005190 }
5191 return time;
5192}
5193
5194void AudioFlinger::DirectOutputThread::cacheParameters_l()
5195{
5196 PlaybackThread::cacheParameters_l();
5197
5198 // use shorter standby delay as on normal output to release
5199 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005200 // no delay on outputs with HW A/V sync
5201 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005202 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005203 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005204 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005205 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005206 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005207 }
Eric Laurent81784c32012-11-19 14:55:58 -08005208}
5209
Eric Laurente659ef42014-09-29 13:06:46 -07005210void AudioFlinger::DirectOutputThread::flushHw_l()
5211{
Phil Burk062e67a2015-02-11 13:40:50 -08005212 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005213 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005214 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005215}
5216
Eric Laurent81784c32012-11-19 14:55:58 -08005217// ----------------------------------------------------------------------------
5218
Eric Laurentbfb1b832013-01-07 09:53:42 -08005219AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005220 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005221 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005222 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005223 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005224 mDrainSequence(0),
5225 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005226{
5227}
5228
5229AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5230{
5231}
5232
5233void AudioFlinger::AsyncCallbackThread::onFirstRef()
5234{
5235 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5236}
5237
5238bool AudioFlinger::AsyncCallbackThread::threadLoop()
5239{
5240 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005241 uint32_t writeAckSequence;
5242 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005243 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005244
5245 {
5246 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005247 while (!((mWriteAckSequence & 1) ||
5248 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005249 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005250 exitPending())) {
5251 mWaitWorkCV.wait(mLock);
5252 }
5253
Eric Laurentbfb1b832013-01-07 09:53:42 -08005254 if (exitPending()) {
5255 break;
5256 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005257 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5258 mWriteAckSequence, mDrainSequence);
5259 writeAckSequence = mWriteAckSequence;
5260 mWriteAckSequence &= ~1;
5261 drainSequence = mDrainSequence;
5262 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005263 asyncError = mAsyncError;
5264 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005265 }
5266 {
Eric Laurent4de95592013-09-26 15:28:21 -07005267 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5268 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005269 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005270 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005271 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005272 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005273 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005274 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005275 if (asyncError) {
5276 playbackThread->onAsyncError();
5277 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005278 }
5279 }
5280 }
5281 return false;
5282}
5283
5284void AudioFlinger::AsyncCallbackThread::exit()
5285{
5286 ALOGV("AsyncCallbackThread::exit");
5287 Mutex::Autolock _l(mLock);
5288 requestExit();
5289 mWaitWorkCV.broadcast();
5290}
5291
Eric Laurent3b4529e2013-09-05 18:09:19 -07005292void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005293{
5294 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005295 // bit 0 is cleared
5296 mWriteAckSequence = sequence << 1;
5297}
5298
5299void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5300{
5301 Mutex::Autolock _l(mLock);
5302 // ignore unexpected callbacks
5303 if (mWriteAckSequence & 2) {
5304 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005305 mWaitWorkCV.signal();
5306 }
5307}
5308
Eric Laurent3b4529e2013-09-05 18:09:19 -07005309void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005310{
5311 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005312 // bit 0 is cleared
5313 mDrainSequence = sequence << 1;
5314}
5315
5316void AudioFlinger::AsyncCallbackThread::resetDraining()
5317{
5318 Mutex::Autolock _l(mLock);
5319 // ignore unexpected callbacks
5320 if (mDrainSequence & 2) {
5321 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005322 mWaitWorkCV.signal();
5323 }
5324}
5325
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005326void AudioFlinger::AsyncCallbackThread::setAsyncError()
5327{
5328 Mutex::Autolock _l(mLock);
5329 mAsyncError = true;
5330 mWaitWorkCV.signal();
5331}
5332
Eric Laurentbfb1b832013-01-07 09:53:42 -08005333
5334// ----------------------------------------------------------------------------
5335AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005336 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5337 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005338 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5339 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005340{
Eric Laurentfd477972013-10-25 18:10:40 -07005341 //FIXME: mStandby should be set to true by ThreadBase constructor
5342 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005343 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344}
5345
Eric Laurentbfb1b832013-01-07 09:53:42 -08005346void AudioFlinger::OffloadThread::threadLoop_exit()
5347{
5348 if (mFlushPending || mHwPaused) {
5349 // If a flush is pending or track was paused, just discard buffered data
5350 flushHw_l();
5351 } else {
5352 mMixerStatus = MIXER_DRAIN_ALL;
5353 threadLoop_drain();
5354 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005355 if (mUseAsyncWrite) {
5356 ALOG_ASSERT(mCallbackThread != 0);
5357 mCallbackThread->exit();
5358 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005359 PlaybackThread::threadLoop_exit();
5360}
5361
5362AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5363 Vector< sp<Track> > *tracksToRemove
5364)
5365{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005366 size_t count = mActiveTracks.size();
5367
5368 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005369 bool doHwPause = false;
5370 bool doHwResume = false;
5371
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005372 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005373
Eric Laurentbfb1b832013-01-07 09:53:42 -08005374 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005375 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005376 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005377#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005378 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005379#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005380 // Only consider last track started for volume and mixer state control.
5381 // In theory an older track could underrun and restart after the new one starts
5382 // but as we only care about the transition phase between two tracks on a
5383 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005384 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005385 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005386
Haynes Mathew George7844f672014-01-15 12:32:55 -08005387 if (track->isInvalid()) {
5388 ALOGW("An invalidated track shouldn't be in active list");
5389 tracksToRemove->add(track);
5390 continue;
5391 }
5392
5393 if (track->mState == TrackBase::IDLE) {
5394 ALOGW("An idle track shouldn't be in active list");
5395 continue;
5396 }
5397
Eric Laurentbfb1b832013-01-07 09:53:42 -08005398 if (track->isPausing()) {
5399 track->setPaused();
5400 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005401 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005402 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005403 mHwPaused = true;
5404 }
5405 // If we were part way through writing the mixbuffer to
5406 // the HAL we must save this until we resume
5407 // BUG - this will be wrong if a different track is made active,
5408 // in that case we want to discard the pending data in the
5409 // mixbuffer and tell the client to present it again when the
5410 // track is resumed
5411 mPausedWriteLength = mCurrentWriteLength;
5412 mPausedBytesRemaining = mBytesRemaining;
5413 mBytesRemaining = 0; // stop writing
5414 }
5415 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005416 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005417 if (track->isStopping_1()) {
5418 track->mRetryCount = kMaxTrackStopRetriesOffload;
5419 } else {
5420 track->mRetryCount = kMaxTrackRetriesOffload;
5421 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005422 track->flushAck();
5423 if (last) {
5424 mFlushPending = true;
5425 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005426 } else if (track->isResumePending()){
5427 track->resumeAck();
5428 if (last) {
5429 if (mPausedBytesRemaining) {
5430 // Need to continue write that was interrupted
5431 mCurrentWriteLength = mPausedWriteLength;
5432 mBytesRemaining = mPausedBytesRemaining;
5433 mPausedBytesRemaining = 0;
5434 }
5435 if (mHwPaused) {
5436 doHwResume = true;
5437 mHwPaused = false;
5438 // threadLoop_mix() will handle the case that we need to
5439 // resume an interrupted write
5440 }
5441 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005442 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005443
Eric Laurent3df841a2016-07-15 15:15:40 -07005444 mLeftVolFloat = mRightVolFloat = -1.0;
5445
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005446 // Do not handle new data in this iteration even if track->framesReady()
5447 mixerStatus = MIXER_TRACKS_ENABLED;
5448 }
5449 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005450 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005451 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005452 if (track->mFillingUpStatus == Track::FS_FILLED) {
5453 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005454 if (last) {
5455 // make sure processVolume_l() will apply new volume even if 0
5456 mLeftVolFloat = mRightVolFloat = -1.0;
5457 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005458 }
5459
5460 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005461 sp<Track> previousTrack = mPreviousTrack.promote();
5462 if (previousTrack != 0) {
5463 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005464 // Flush any data still being written from last track
5465 mBytesRemaining = 0;
5466 if (mPausedBytesRemaining) {
5467 // Last track was paused so we also need to flush saved
5468 // mixbuffer state and invalidate track so that it will
5469 // re-submit that unwritten data when it is next resumed
5470 mPausedBytesRemaining = 0;
5471 // Invalidate is a bit drastic - would be more efficient
5472 // to have a flag to tell client that some of the
5473 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005474 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005475 }
5476 // flush data already sent to the DSP if changing audio session as audio
5477 // comes from a different source. Also invalidate previous track to force a
5478 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005479 if (previousTrack->sessionId() != track->sessionId()) {
5480 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005481 }
5482 }
5483 }
5484 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005485 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005486 if (track->isStopping_1()) {
5487 track->mRetryCount = kMaxTrackStopRetriesOffload;
5488 } else {
5489 track->mRetryCount = kMaxTrackRetriesOffload;
5490 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005491 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005492 mixerStatus = MIXER_TRACKS_READY;
5493 }
5494 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005495 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005496 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005497 if (--(track->mRetryCount) <= 0) {
5498 // Hardware buffer can hold a large amount of audio so we must
5499 // wait for all current track's data to drain before we say
5500 // that the track is stopped.
5501 if (mBytesRemaining == 0) {
5502 // Only start draining when all data in mixbuffer
5503 // has been written
5504 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5505 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5506 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5507 if (last && !mStandby) {
5508 // do not modify drain sequence if we are already draining. This happens
5509 // when resuming from pause after drain.
5510 if ((mDrainSequence & 1) == 0) {
5511 mSleepTimeUs = 0;
5512 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5513 mixerStatus = MIXER_DRAIN_TRACK;
5514 mDrainSequence += 2;
5515 }
5516 if (mHwPaused) {
5517 // It is possible to move from PAUSED to STOPPING_1 without
5518 // a resume so we must ensure hardware is running
5519 doHwResume = true;
5520 mHwPaused = false;
5521 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005522 }
5523 }
Eric Laurente93cc032016-05-05 10:15:10 -07005524 } else if (last) {
5525 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5526 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005527 }
5528 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005529 // Drain has completed or we are in standby, signal presentation complete
5530 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005531 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005532 uint32_t latency = 0;
5533 status_t result = mOutput->stream->getLatency(&latency);
5534 ALOGE_IF(result != OK,
5535 "Error when retrieving output stream latency: %d", result);
5536 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005537 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005538 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005539 track->presentationComplete(framesWritten, audioHALFrames);
5540 track->reset();
5541 tracksToRemove->add(track);
5542 }
5543 } else {
5544 // No buffers for this track. Give it a few chances to
5545 // fill a buffer, then remove it from active list.
5546 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005547 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005548 uint64_t position = 0;
5549 struct timespec unused;
5550 // The running check restarts the retry counter at least once.
5551 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5552 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5553 running = true;
5554 mOffloadUnderrunPosition = position;
5555 }
5556 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005557 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5558 (long long)position, (long long)mOffloadUnderrunPosition);
5559 }
5560 if (running) { // still running, give us more time.
5561 track->mRetryCount = kMaxTrackRetriesOffload;
5562 } else {
5563 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5564 track->name());
5565 tracksToRemove->add(track);
5566 // indicate to client process that the track was disabled because of underrun;
5567 // it will then automatically call start() when data is available
5568 track->disable();
5569 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005570 } else if (last){
5571 mixerStatus = MIXER_TRACKS_ENABLED;
5572 }
5573 }
5574 }
5575 // compute volume for this track
5576 processVolume_l(track, last);
5577 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005578
Eric Laurentea0fade2013-10-04 16:23:48 -07005579 // make sure the pause/flush/resume sequence is executed in the right order.
5580 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5581 // before flush and then resume HW. This can happen in case of pause/flush/resume
5582 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005583 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005584 status_t result = mOutput->stream->pause();
5585 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005586 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005587 if (mFlushPending) {
5588 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005589 }
Eric Laurentfd477972013-10-25 18:10:40 -07005590 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005591 status_t result = mOutput->stream->resume();
5592 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005593 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005594
Eric Laurentbfb1b832013-01-07 09:53:42 -08005595 // remove all the tracks that need to be...
5596 removeTracks_l(*tracksToRemove);
5597
5598 return mixerStatus;
5599}
5600
Eric Laurentbfb1b832013-01-07 09:53:42 -08005601// must be called with thread mutex locked
5602bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5603{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005604 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5605 mWriteAckSequence, mDrainSequence);
5606 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005607 return true;
5608 }
5609 return false;
5610}
5611
Eric Laurentbfb1b832013-01-07 09:53:42 -08005612bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5613{
5614 Mutex::Autolock _l(mLock);
5615 return waitingAsyncCallback_l();
5616}
5617
5618void AudioFlinger::OffloadThread::flushHw_l()
5619{
Eric Laurente659ef42014-09-29 13:06:46 -07005620 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005621 // Flush anything still waiting in the mixbuffer
5622 mCurrentWriteLength = 0;
5623 mBytesRemaining = 0;
5624 mPausedWriteLength = 0;
5625 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005626 // reset bytes written count to reflect that DSP buffers are empty after flush.
5627 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005628 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005629
Eric Laurentbfb1b832013-01-07 09:53:42 -08005630 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005631 // discard any pending drain or write ack by incrementing sequence
5632 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5633 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005634 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005635 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5636 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005637 }
5638}
5639
Haynes Mathew George05317d22016-05-03 16:34:26 -07005640void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5641{
5642 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005643 if (PlaybackThread::invalidateTracks_l(streamType)) {
5644 mFlushPending = true;
5645 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005646}
5647
Eric Laurentbfb1b832013-01-07 09:53:42 -08005648// ----------------------------------------------------------------------------
5649
Eric Laurent81784c32012-11-19 14:55:58 -08005650AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005651 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005652 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005653 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005654 mWaitTimeMs(UINT_MAX)
5655{
5656 addOutputTrack(mainThread);
5657}
5658
5659AudioFlinger::DuplicatingThread::~DuplicatingThread()
5660{
5661 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5662 mOutputTracks[i]->destroy();
5663 }
5664}
5665
5666void AudioFlinger::DuplicatingThread::threadLoop_mix()
5667{
5668 // mix buffers...
5669 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005670 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005671 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005672 if (mMixerBufferValid) {
5673 memset(mMixerBuffer, 0, mMixerBufferSize);
5674 } else {
5675 memset(mSinkBuffer, 0, mSinkBufferSize);
5676 }
Eric Laurent81784c32012-11-19 14:55:58 -08005677 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005678 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005679 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005680 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005681 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005682}
5683
5684void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5685{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005686 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005687 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005688 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005689 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005690 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005691 }
5692 } else if (mBytesWritten != 0) {
5693 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5694 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005695 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005696 } else {
5697 // flush remaining overflow buffers in output tracks
5698 writeFrames = 0;
5699 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005700 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005701 }
5702}
5703
Eric Laurentbfb1b832013-01-07 09:53:42 -08005704ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005705{
5706 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005707 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005708 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005709 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005710 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005711}
5712
5713void AudioFlinger::DuplicatingThread::threadLoop_standby()
5714{
5715 // DuplicatingThread implements standby by stopping all tracks
5716 for (size_t i = 0; i < outputTracks.size(); i++) {
5717 outputTracks[i]->stop();
5718 }
5719}
5720
5721void AudioFlinger::DuplicatingThread::saveOutputTracks()
5722{
5723 outputTracks = mOutputTracks;
5724}
5725
5726void AudioFlinger::DuplicatingThread::clearOutputTracks()
5727{
5728 outputTracks.clear();
5729}
5730
5731void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5732{
5733 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005734 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5735 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5736 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5737 const size_t frameCount =
5738 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5739 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5740 // from different OutputTracks and their associated MixerThreads (e.g. one may
5741 // nearly empty and the other may be dropping data).
5742
5743 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005744 this,
5745 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005746 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005747 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005748 frameCount,
5749 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005750 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5751 if (status != NO_ERROR) {
5752 ALOGE("addOutputTrack() initCheck failed %d", status);
5753 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005754 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005755 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5756 mOutputTracks.add(outputTrack);
5757 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5758 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005759}
5760
5761void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5762{
5763 Mutex::Autolock _l(mLock);
5764 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5765 if (mOutputTracks[i]->thread() == thread) {
5766 mOutputTracks[i]->destroy();
5767 mOutputTracks.removeAt(i);
5768 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005769 if (thread->getOutput() == mOutput) {
5770 mOutput = NULL;
5771 }
Eric Laurent81784c32012-11-19 14:55:58 -08005772 return;
5773 }
5774 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005775 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005776}
5777
5778// caller must hold mLock
5779void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5780{
5781 mWaitTimeMs = UINT_MAX;
5782 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5783 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5784 if (strong != 0) {
5785 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5786 if (waitTimeMs < mWaitTimeMs) {
5787 mWaitTimeMs = waitTimeMs;
5788 }
5789 }
5790 }
5791}
5792
5793
5794bool AudioFlinger::DuplicatingThread::outputsReady(
5795 const SortedVector< sp<OutputTrack> > &outputTracks)
5796{
5797 for (size_t i = 0; i < outputTracks.size(); i++) {
5798 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5799 if (thread == 0) {
5800 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5801 outputTracks[i].get());
5802 return false;
5803 }
5804 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5805 // see note at standby() declaration
5806 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5807 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5808 thread.get());
5809 return false;
5810 }
5811 }
5812 return true;
5813}
5814
5815uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5816{
5817 return (mWaitTimeMs * 1000) / 2;
5818}
5819
5820void AudioFlinger::DuplicatingThread::cacheParameters_l()
5821{
5822 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5823 updateWaitTime_l();
5824
5825 MixerThread::cacheParameters_l();
5826}
5827
5828// ----------------------------------------------------------------------------
5829// Record
5830// ----------------------------------------------------------------------------
5831
5832AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5833 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005834 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005835 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005836 audio_devices_t inDevice,
5837 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005838#ifdef TEE_SINK
5839 , const sp<NBAIO_Sink>& teeSink
5840#endif
5841 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005842 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005843 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005844 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005845 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005846#ifdef TEE_SINK
5847 , mTeeSink(teeSink)
5848#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005849 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5850 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005851 // mFastCapture below
5852 , mFastCaptureFutex(0)
5853 // mInputSource
5854 // mPipeSink
5855 // mPipeSource
5856 , mPipeFramesP2(0)
5857 // mPipeMemory
5858 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005859 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005860{
Glenn Kastend7dca052015-03-05 16:05:54 -08005861 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5862 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005863
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005864 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005865
5866 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005867 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005868 size_t numCounterOffers = 0;
5869 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005870#if !LOG_NDEBUG
5871 ssize_t index =
5872#else
5873 (void)
5874#endif
5875 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005876 ALOG_ASSERT(index == 0);
5877
5878 // initialize fast capture depending on configuration
5879 bool initFastCapture;
5880 switch (kUseFastCapture) {
5881 case FastCapture_Never:
5882 initFastCapture = false;
5883 break;
5884 case FastCapture_Always:
5885 initFastCapture = true;
5886 break;
5887 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005888 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005889 break;
5890 // case FastCapture_Dynamic:
5891 }
5892
5893 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005894 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005895 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005896 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5897 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005898 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5899 void *pipeBuffer;
5900 const sp<MemoryDealer> roHeap(readOnlyHeap());
5901 sp<IMemory> pipeMemory;
5902 if ((roHeap == 0) ||
5903 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5904 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5905 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5906 goto failed;
5907 }
5908 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5909 memset(pipeBuffer, 0, pipeSize);
5910 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5911 const NBAIO_Format offers[1] = {format};
5912 size_t numCounterOffers = 0;
5913 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5914 ALOG_ASSERT(index == 0);
5915 mPipeSink = pipe;
5916 PipeReader *pipeReader = new PipeReader(*pipe);
5917 numCounterOffers = 0;
5918 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5919 ALOG_ASSERT(index == 0);
5920 mPipeSource = pipeReader;
5921 mPipeFramesP2 = pipeFramesP2;
5922 mPipeMemory = pipeMemory;
5923
5924 // create fast capture
5925 mFastCapture = new FastCapture();
5926 FastCaptureStateQueue *sq = mFastCapture->sq();
5927#ifdef STATE_QUEUE_DUMP
5928 // FIXME
5929#endif
5930 FastCaptureState *state = sq->begin();
5931 state->mCblk = NULL;
5932 state->mInputSource = mInputSource.get();
5933 state->mInputSourceGen++;
5934 state->mPipeSink = pipe;
5935 state->mPipeSinkGen++;
5936 state->mFrameCount = mFrameCount;
5937 state->mCommand = FastCaptureState::COLD_IDLE;
5938 // already done in constructor initialization list
5939 //mFastCaptureFutex = 0;
5940 state->mColdFutexAddr = &mFastCaptureFutex;
5941 state->mColdGen++;
5942 state->mDumpState = &mFastCaptureDumpState;
5943#ifdef TEE_SINK
5944 // FIXME
5945#endif
5946 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5947 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5948 sq->end();
5949 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5950
5951 // start the fast capture
5952 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5953 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005954 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005955 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005956#ifdef AUDIO_WATCHDOG
5957 // FIXME
5958#endif
5959
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005960 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005961 }
5962failed: ;
5963
5964 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005965}
5966
Eric Laurent81784c32012-11-19 14:55:58 -08005967AudioFlinger::RecordThread::~RecordThread()
5968{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005969 if (mFastCapture != 0) {
5970 FastCaptureStateQueue *sq = mFastCapture->sq();
5971 FastCaptureState *state = sq->begin();
5972 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5973 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5974 if (old == -1) {
5975 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5976 }
5977 }
5978 state->mCommand = FastCaptureState::EXIT;
5979 sq->end();
5980 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5981 mFastCapture->join();
5982 mFastCapture.clear();
5983 }
5984 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005985 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005986 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005987}
5988
5989void AudioFlinger::RecordThread::onFirstRef()
5990{
Glenn Kastend7dca052015-03-05 16:05:54 -08005991 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005992}
5993
Eric Laurent81784c32012-11-19 14:55:58 -08005994bool AudioFlinger::RecordThread::threadLoop()
5995{
Eric Laurent81784c32012-11-19 14:55:58 -08005996 nsecs_t lastWarning = 0;
5997
5998 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005999
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006000reacquire_wakelock:
6001 sp<RecordTrack> activeTrack;
6002 {
6003 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006004 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006005 }
6006
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006007 // used to request a deferred sleep, to be executed later while mutex is unlocked
6008 uint32_t sleepUs = 0;
6009
6010 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006011 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006012 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006013
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006014 // activeTracks accumulates a copy of a subset of mActiveTracks
6015 Vector< sp<RecordTrack> > activeTracks;
6016
Glenn Kasten735f45f2014-08-18 15:51:59 -07006017 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006018 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006019
Glenn Kasten735f45f2014-08-18 15:51:59 -07006020 // reference to a fast track which is about to be removed
6021 sp<RecordTrack> fastTrackToRemove;
6022
Eric Laurent81784c32012-11-19 14:55:58 -08006023 { // scope for mLock
6024 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006025
Eric Laurent021cf962014-05-13 10:18:14 -07006026 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006027
Eric Laurent000a4192014-01-29 15:17:32 -08006028 // check exitPending here because checkForNewParameters_l() and
6029 // checkForNewParameters_l() can temporarily release mLock
6030 if (exitPending()) {
6031 break;
6032 }
6033
Eric Laurent5c25d562016-07-13 17:17:45 -07006034 // sleep with mutex unlocked
6035 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006036 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006037 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6038 ATRACE_END();
6039 sleepUs = 0;
6040 continue;
6041 }
6042
Glenn Kasten2b806402013-11-20 16:37:38 -08006043 // if no active track(s), then standby and release wakelock
6044 size_t size = mActiveTracks.size();
6045 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006046 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006047 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006048 releaseWakeLock_l();
6049 ALOGV("RecordThread: loop stopping");
6050 // go to sleep
6051 mWaitWorkCV.wait(mLock);
6052 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006053 goto reacquire_wakelock;
6054 }
6055
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006056 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006057 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006058 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006059
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006060 activeTrack = mActiveTracks[i];
6061 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006062 if (activeTrack->isFastTrack()) {
6063 ALOG_ASSERT(fastTrackToRemove == 0);
6064 fastTrackToRemove = activeTrack;
6065 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006066 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006067 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006068 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006069 continue;
6070 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006071
6072 TrackBase::track_state activeTrackState = activeTrack->mState;
6073 switch (activeTrackState) {
6074
6075 case TrackBase::PAUSING:
6076 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006077 doBroadcast = true;
6078 size--;
6079 continue;
6080
6081 case TrackBase::STARTING_1:
6082 sleepUs = 10000;
6083 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006084 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006085 continue;
6086
6087 case TrackBase::STARTING_2:
6088 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006089 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006090 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006091 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006092 break;
6093
6094 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006095 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006096 break;
6097
6098 case TrackBase::IDLE:
6099 i++;
6100 continue;
6101
6102 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006103 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006104 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006105
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006106 activeTracks.add(activeTrack);
6107 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006108
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006109 if (activeTrack->isFastTrack()) {
6110 ALOG_ASSERT(!mFastTrackAvail);
6111 ALOG_ASSERT(fastTrack == 0);
6112 fastTrack = activeTrack;
6113 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006114 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006115
Andy Hungdae27702016-10-31 14:01:16 -07006116 mActiveTracks.updatePowerState(this);
6117
Eric Laurent5c25d562016-07-13 17:17:45 -07006118 if (allStopped) {
6119 standbyIfNotAlreadyInStandby();
6120 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006121 if (doBroadcast) {
6122 mStartStopCond.broadcast();
6123 }
6124
6125 // sleep if there are no active tracks to process
6126 if (activeTracks.size() == 0) {
6127 if (sleepUs == 0) {
6128 sleepUs = kRecordThreadSleepUs;
6129 }
6130 continue;
6131 }
6132 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006133
Eric Laurent81784c32012-11-19 14:55:58 -08006134 lockEffectChains_l(effectChains);
6135 }
6136
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006137 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006138
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006139 size_t size = effectChains.size();
6140 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006141 // thread mutex is not locked, but effect chain is locked
6142 effectChains[i]->process_l();
6143 }
6144
Glenn Kasten735f45f2014-08-18 15:51:59 -07006145 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006146 if (mFastCapture != 0) {
6147 FastCaptureStateQueue *sq = mFastCapture->sq();
6148 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006149 bool didModify = false;
6150 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006151 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6152 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6153 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6154 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6155 if (old == -1) {
6156 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6157 }
6158 }
6159 state->mCommand = FastCaptureState::READ_WRITE;
6160#if 0 // FIXME
6161 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006162 FastThreadDumpState::kSamplingNforLowRamDevice :
6163 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006164#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006165 didModify = true;
6166 }
6167 audio_track_cblk_t *cblkOld = state->mCblk;
6168 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6169 if (cblkNew != cblkOld) {
6170 state->mCblk = cblkNew;
6171 // block until acked if removing a fast track
6172 if (cblkOld != NULL) {
6173 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6174 }
6175 didModify = true;
6176 }
6177 sq->end(didModify);
6178 if (didModify) {
6179 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006180#if 0
6181 if (kUseFastCapture == FastCapture_Dynamic) {
6182 mNormalSource = mPipeSource;
6183 }
6184#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006185 }
6186 }
6187
Glenn Kasten735f45f2014-08-18 15:51:59 -07006188 // now run the fast track destructor with thread mutex unlocked
6189 fastTrackToRemove.clear();
6190
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006191 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6192 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6193 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6194 // If destination is non-contiguous, first read past the nominal end of buffer, then
6195 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006196
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006197 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006198 ssize_t framesRead;
6199
6200 // If an NBAIO source is present, use it to read the normal capture's data
6201 if (mPipeSource != 0) {
6202 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006203 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006204 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006205 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006206 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6207 // buffer size or at least for 20ms.
6208 size_t sleepFrames = max(
6209 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6210 if (framesRead <= (ssize_t) sleepFrames) {
6211 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6212 }
6213 if (framesRead < 0) {
6214 status_t status = (status_t) framesRead;
6215 switch (status) {
6216 case OVERRUN:
6217 ALOGW("overrun on read from pipe");
6218 framesRead = 0;
6219 break;
6220 case NEGOTIATE:
6221 ALOGE("re-negotiation is needed");
6222 framesRead = -1; // Will cause an attempt to recover.
6223 break;
6224 default:
6225 ALOGE("unknown error %d on read from pipe", status);
6226 break;
6227 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006228 }
6229 // otherwise use the HAL / AudioStreamIn directly
6230 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006231 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006232 size_t bytesRead;
6233 status_t result = mInput->stream->read(
6234 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006235 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006236 if (result < 0) {
6237 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006238 } else {
6239 framesRead = bytesRead / mFrameSize;
6240 }
6241 }
6242
Andy Hung3f0c9022016-01-15 17:49:46 -08006243 // Update server timestamp with server stats
6244 // systemTime() is optional if the hardware supports timestamps.
6245 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6246 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6247
6248 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006249 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006250 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006251 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006252 if (ret == NO_ERROR) {
6253 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6254 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6255 // Note: In general record buffers should tend to be empty in
6256 // a properly running pipeline.
6257 //
6258 // Also, it is not advantageous to call get_presentation_position during the read
6259 // as the read obtains a lock, preventing the timestamp call from executing.
6260 }
6261 }
6262 // Use this to track timestamp information
6263 // ALOGD("%s", mTimestamp.toString().c_str());
6264
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006265 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006266 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006267 // Force input into standby so that it tries to recover at next read attempt
6268 inputStandBy();
6269 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006270 }
6271 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006272 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006273 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006274 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006275
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006276 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006277 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006278 }
6279 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006280 {
6281 size_t part1 = mRsmpInFramesP2 - rear;
6282 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006283 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006284 (framesRead - part1) * mFrameSize);
6285 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006286 }
6287 rear = mRsmpInRear += framesRead;
6288
6289 size = activeTracks.size();
6290 // loop over each active track
6291 for (size_t i = 0; i < size; i++) {
6292 activeTrack = activeTracks[i];
6293
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006294 // skip fast tracks, as those are handled directly by FastCapture
6295 if (activeTrack->isFastTrack()) {
6296 continue;
6297 }
6298
Andy Hung73c02e42015-03-29 01:13:58 -07006299 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006300 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6301
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006302 enum {
6303 OVERRUN_UNKNOWN,
6304 OVERRUN_TRUE,
6305 OVERRUN_FALSE
6306 } overrun = OVERRUN_UNKNOWN;
6307
6308 // loop over getNextBuffer to handle circular sink
6309 for (;;) {
6310
6311 activeTrack->mSink.frameCount = ~0;
6312 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6313 size_t framesOut = activeTrack->mSink.frameCount;
6314 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6315
Andy Hung73c02e42015-03-29 01:13:58 -07006316 // check available frames and handle overrun conditions
6317 // if the record track isn't draining fast enough.
6318 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006319 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006320 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6321 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006322 overrun = OVERRUN_TRUE;
6323 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006324 if (framesOut == 0 || framesIn == 0) {
6325 break;
6326 }
6327
Andy Hung6770c6f2015-04-07 13:43:36 -07006328 // Don't allow framesOut to be larger than what is possible with resampling
6329 // from framesIn.
6330 // This isn't strictly necessary but helps limit buffer resizing in
6331 // RecordBufferConverter. TODO: remove when no longer needed.
6332 framesOut = min(framesOut,
6333 destinationFramesPossible(
6334 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006335 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6336 framesOut = activeTrack->mRecordBufferConverter->convert(
6337 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006338
6339 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6340 overrun = OVERRUN_FALSE;
6341 }
6342
6343 if (activeTrack->mFramesToDrop == 0) {
6344 if (framesOut > 0) {
6345 activeTrack->mSink.frameCount = framesOut;
6346 activeTrack->releaseBuffer(&activeTrack->mSink);
6347 }
6348 } else {
6349 // FIXME could do a partial drop of framesOut
6350 if (activeTrack->mFramesToDrop > 0) {
6351 activeTrack->mFramesToDrop -= framesOut;
6352 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006353 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006354 }
6355 } else {
6356 activeTrack->mFramesToDrop += framesOut;
6357 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6358 activeTrack->mSyncStartEvent->isCancelled()) {
6359 ALOGW("Synced record %s, session %d, trigger session %d",
6360 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6361 activeTrack->sessionId(),
6362 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006363 activeTrack->mSyncStartEvent->triggerSession() :
6364 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006365 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006366 }
6367 }
6368 }
6369
6370 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006371 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006372 }
6373 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006374
6375 switch (overrun) {
6376 case OVERRUN_TRUE:
6377 // client isn't retrieving buffers fast enough
6378 if (!activeTrack->setOverflow()) {
6379 nsecs_t now = systemTime();
6380 // FIXME should lastWarning per track?
6381 if ((now - lastWarning) > kWarningThrottleNs) {
6382 ALOGW("RecordThread: buffer overflow");
6383 lastWarning = now;
6384 }
6385 }
6386 break;
6387 case OVERRUN_FALSE:
6388 activeTrack->clearOverflow();
6389 break;
6390 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006391 break;
6392 }
6393
Andy Hung3f0c9022016-01-15 17:49:46 -08006394 // update frame information and push timestamp out
6395 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006396 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006397 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6398 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006399 }
6400
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006401unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006402 // enable changes in effect chain
6403 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006404 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006405 }
6406
Glenn Kasten93e471f2013-08-19 08:40:07 -07006407 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006408
6409 {
6410 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006411 for (size_t i = 0; i < mTracks.size(); i++) {
6412 sp<RecordTrack> track = mTracks[i];
6413 track->invalidate();
6414 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006415 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006416 mStartStopCond.broadcast();
6417 }
6418
6419 releaseWakeLock();
6420
6421 ALOGV("RecordThread %p exiting", this);
6422 return false;
6423}
6424
Glenn Kasten93e471f2013-08-19 08:40:07 -07006425void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006426{
6427 if (!mStandby) {
6428 inputStandBy();
6429 mStandby = true;
6430 }
6431}
6432
6433void AudioFlinger::RecordThread::inputStandBy()
6434{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006435 // Idle the fast capture if it's currently running
6436 if (mFastCapture != 0) {
6437 FastCaptureStateQueue *sq = mFastCapture->sq();
6438 FastCaptureState *state = sq->begin();
6439 if (!(state->mCommand & FastCaptureState::IDLE)) {
6440 state->mCommand = FastCaptureState::COLD_IDLE;
6441 state->mColdFutexAddr = &mFastCaptureFutex;
6442 state->mColdGen++;
6443 mFastCaptureFutex = 0;
6444 sq->end();
6445 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6446 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6447#if 0
6448 if (kUseFastCapture == FastCapture_Dynamic) {
6449 // FIXME
6450 }
6451#endif
6452#ifdef AUDIO_WATCHDOG
6453 // FIXME
6454#endif
6455 } else {
6456 sq->end(false /*didModify*/);
6457 }
6458 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006459 status_t result = mInput->stream->standby();
6460 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006461
6462 // If going into standby, flush the pipe source.
6463 if (mPipeSource.get() != nullptr) {
6464 const ssize_t flushed = mPipeSource->flush();
6465 if (flushed > 0) {
6466 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6467 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6468 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6469 }
6470 }
Eric Laurent81784c32012-11-19 14:55:58 -08006471}
6472
Glenn Kasten05997e22014-03-13 15:08:33 -07006473// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006474sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006475 const sp<AudioFlinger::Client>& client,
6476 uint32_t sampleRate,
6477 audio_format_t format,
6478 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006479 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006480 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006481 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006482 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006483 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006484 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006485 status_t *status,
6486 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006487{
Glenn Kasten74935e42013-12-19 08:56:45 -08006488 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006489 sp<RecordTrack> track;
6490 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006491 audio_input_flags_t inputFlags = mInput->flags;
6492
6493 // special case for FAST flag considered OK if fast capture is present
6494 if (hasFastCapture()) {
6495 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6496 }
6497
6498 // Check if requested flags are compatible with output stream flags
6499 if ((*flags & inputFlags) != *flags) {
6500 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6501 " input flags (%08x)",
6502 *flags, inputFlags);
6503 *flags = (audio_input_flags_t)(*flags & inputFlags);
6504 }
Eric Laurent81784c32012-11-19 14:55:58 -08006505
Glenn Kasten90e58b12013-07-31 16:16:02 -07006506 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006507 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006508 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006509 // we formerly checked for a callback handler (non-0 tid),
6510 // but that is no longer required for TRANSFER_OBTAIN mode
6511 //
Glenn Kasten74105912014-07-03 12:28:53 -07006512 // frame count is not specified, or is exactly the pipe depth
6513 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006514 // PCM data
6515 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006516 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006517 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006518 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006519 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006520 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006521 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006522 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006523 hasFastCapture() &&
6524 // there are sufficient fast track slots available
6525 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006526 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006527 // check compatibility with audio effects.
6528 Mutex::Autolock _l(mLock);
6529 // Do not accept FAST flag if the session has software effects
6530 sp<EffectChain> chain = getEffectChain_l(sessionId);
6531 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006532 audio_input_flags_t old = *flags;
6533 chain->checkInputFlagCompatibility(flags);
6534 if (old != *flags) {
6535 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6536 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006537 }
6538 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006539 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006540 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6541 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006542 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006543 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006544 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006545 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006546 frameCount, mFrameCount, mPipeFramesP2,
6547 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6548 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006549 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006550 }
6551 }
6552
6553 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006554 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006555 // fast track: frame count is exactly the pipe depth
6556 frameCount = mPipeFramesP2;
6557 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6558 *notificationFrames = mFrameCount;
6559 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006560 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6561 // or 20 ms if there is a fast capture
6562 // TODO This could be a roundupRatio inline, and const
6563 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6564 * sampleRate + mSampleRate - 1) / mSampleRate;
6565 // minimum number of notification periods is at least kMinNotifications,
6566 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6567 static const size_t kMinNotifications = 3;
6568 static const uint32_t kMinMs = 30;
6569 // TODO This could be a roundupRatio inline
6570 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6571 // TODO This could be a roundupRatio inline
6572 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6573 maxNotificationFrames;
6574 const size_t minFrameCount = maxNotificationFrames *
6575 max(kMinNotifications, minNotificationsByMs);
6576 frameCount = max(frameCount, minFrameCount);
6577 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6578 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006579 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006580 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006581 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006582
Glenn Kasten15e57982013-09-24 11:52:37 -07006583 lStatus = initCheck();
6584 if (lStatus != NO_ERROR) {
6585 ALOGE("createRecordTrack_l() audio driver not initialized");
6586 goto Exit;
6587 }
Eric Laurent81784c32012-11-19 14:55:58 -08006588
6589 { // scope for mLock
6590 Mutex::Autolock _l(mLock);
6591
6592 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006593 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006594 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006595
Glenn Kasten03003332013-08-06 15:40:54 -07006596 lStatus = track->initCheck();
6597 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006598 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006599 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006600 goto Exit;
6601 }
6602 mTracks.add(track);
6603
6604 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6605 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6606 mAudioFlinger->btNrecIsOff();
6607 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6608 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006609
Eric Laurent05067782016-06-01 18:27:28 -07006610 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006611 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6612 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6613 // so ask activity manager to do this on our behalf
6614 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6615 }
Eric Laurent81784c32012-11-19 14:55:58 -08006616 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006617
Eric Laurent81784c32012-11-19 14:55:58 -08006618 lStatus = NO_ERROR;
6619
6620Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006621 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006622 return track;
6623}
6624
6625status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6626 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006627 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006628{
6629 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6630 sp<ThreadBase> strongMe = this;
6631 status_t status = NO_ERROR;
6632
6633 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006634 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006635 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006636 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006637 triggerSession,
6638 recordTrack->sessionId(),
6639 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006640 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006641 // Sync event can be cancelled by the trigger session if the track is not in a
6642 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006643 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006644 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006645 } else {
6646 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006647 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006648 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006649 }
6650 }
6651
6652 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006653 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006654 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006655 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6656 if (recordTrack->mState == TrackBase::PAUSING) {
6657 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006658 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006659 } else {
6660 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006661 }
6662 return status;
6663 }
6664
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006665 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6666 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6667 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006668 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006669 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006670 status_t status = NO_ERROR;
6671 if (recordTrack->isExternalTrack()) {
6672 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006673 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006674 mLock.lock();
6675 // FIXME should verify that recordTrack is still in mActiveTracks
6676 if (status != NO_ERROR) {
6677 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006678 recordTrack->clearSyncStartEvent();
6679 ALOGV("RecordThread::start error %d", status);
6680 return status;
6681 }
Eric Laurent81784c32012-11-19 14:55:58 -08006682 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006683 // Catch up with current buffer indices if thread is already running.
6684 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6685 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6686 // see previously buffered data before it called start(), but with greater risk of overrun.
6687
Andy Hung73c02e42015-03-29 01:13:58 -07006688 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006689 // clear any converter state as new data will be discontinuous
6690 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006691 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006692 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006693 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006694 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006695 ALOGV("Record failed to start");
6696 status = BAD_VALUE;
6697 goto startError;
6698 }
Eric Laurent81784c32012-11-19 14:55:58 -08006699 return status;
6700 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006701
Eric Laurent81784c32012-11-19 14:55:58 -08006702startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006703 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006704 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006705 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006706 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006707 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006708 return status;
6709}
6710
Eric Laurent81784c32012-11-19 14:55:58 -08006711void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6712{
6713 sp<SyncEvent> strongEvent = event.promote();
6714
6715 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006716 sp<RefBase> ptr = strongEvent->cookie().promote();
6717 if (ptr != 0) {
6718 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6719 recordTrack->handleSyncStartEvent(strongEvent);
6720 }
Eric Laurent81784c32012-11-19 14:55:58 -08006721 }
6722}
6723
Glenn Kastena8356f62013-07-25 14:37:52 -07006724bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006725 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006726 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006727 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006728 return false;
6729 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006730 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006731 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006732 // signal thread to stop
6733 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006734 // do not wait for mStartStopCond if exiting
6735 if (exitPending()) {
6736 return true;
6737 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006738 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006739 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006740 // if we have been restarted, recordTrack is in mActiveTracks here
6741 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006742 ALOGV("Record stopped OK");
6743 return true;
6744 }
6745 return false;
6746}
6747
Glenn Kasten0f11b512014-01-31 16:18:54 -08006748bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006749{
6750 return false;
6751}
6752
Glenn Kasten0f11b512014-01-31 16:18:54 -08006753status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006754{
6755#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6756 if (!isValidSyncEvent(event)) {
6757 return BAD_VALUE;
6758 }
6759
Glenn Kastend848eb42016-03-08 13:42:11 -08006760 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006761 status_t ret = NAME_NOT_FOUND;
6762
6763 Mutex::Autolock _l(mLock);
6764
6765 for (size_t i = 0; i < mTracks.size(); i++) {
6766 sp<RecordTrack> track = mTracks[i];
6767 if (eventSession == track->sessionId()) {
6768 (void) track->setSyncEvent(event);
6769 ret = NO_ERROR;
6770 }
6771 }
6772 return ret;
6773#else
6774 return BAD_VALUE;
6775#endif
6776}
6777
6778// destroyTrack_l() must be called with ThreadBase::mLock held
6779void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6780{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006781 track->terminate();
6782 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006783 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006784 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006785 removeTrack_l(track);
6786 }
6787}
6788
6789void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6790{
6791 mTracks.remove(track);
6792 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006793 if (track->isFastTrack()) {
6794 ALOG_ASSERT(!mFastTrackAvail);
6795 mFastTrackAvail = true;
6796 }
Eric Laurent81784c32012-11-19 14:55:58 -08006797}
6798
6799void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6800{
6801 dumpInternals(fd, args);
6802 dumpTracks(fd, args);
6803 dumpEffectChains(fd, args);
6804}
6805
6806void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6807{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006808 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006809
Glenn Kasten44182c22015-03-05 17:12:23 -08006810 dumpBase(fd, args);
6811
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006812 AudioStreamIn *input = mInput;
6813 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6814 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6815 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006816 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006817 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006818 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006819 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006820 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006821
Glenn Kasten2f90c512015-12-02 11:40:09 -08006822 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6823 // while we are dumping it. It may be inconsistent, but it won't mutate!
6824 // This is a large object so we place it on the heap.
6825 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6826 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6827 copy->dump(fd);
6828 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006829}
6830
Glenn Kasten0f11b512014-01-31 16:18:54 -08006831void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006832{
6833 const size_t SIZE = 256;
6834 char buffer[SIZE];
6835 String8 result;
6836
Marco Nelissenb2208842014-02-07 14:00:50 -08006837 size_t numtracks = mTracks.size();
6838 size_t numactive = mActiveTracks.size();
6839 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006840 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006841 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006842 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006843 RecordTrack::appendDumpHeader(result);
6844 for (size_t i = 0; i < numtracks ; ++i) {
6845 sp<RecordTrack> track = mTracks[i];
6846 if (track != 0) {
6847 bool active = mActiveTracks.indexOf(track) >= 0;
6848 if (active) {
6849 numactiveseen++;
6850 }
6851 track->dump(buffer, SIZE, active);
6852 result.append(buffer);
6853 }
Eric Laurent81784c32012-11-19 14:55:58 -08006854 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006855 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006856 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006857 }
6858
Marco Nelissenb2208842014-02-07 14:00:50 -08006859 if (numactiveseen != numactive) {
6860 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6861 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006862 result.append(buffer);
6863 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006864 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006865 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006866 if (mTracks.indexOf(track) < 0) {
6867 track->dump(buffer, SIZE, true);
6868 result.append(buffer);
6869 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006870 }
Eric Laurent81784c32012-11-19 14:55:58 -08006871
6872 }
6873 write(fd, result.string(), result.size());
6874}
6875
Andy Hung73c02e42015-03-29 01:13:58 -07006876
6877void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6878{
6879 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6880 RecordThread *recordThread = (RecordThread *) threadBase.get();
6881 mRsmpInFront = recordThread->mRsmpInRear;
6882 mRsmpInUnrel = 0;
6883}
6884
6885void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6886 size_t *framesAvailable, bool *hasOverrun)
6887{
6888 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6889 RecordThread *recordThread = (RecordThread *) threadBase.get();
6890 const int32_t rear = recordThread->mRsmpInRear;
6891 const int32_t front = mRsmpInFront;
6892 const ssize_t filled = rear - front;
6893
6894 size_t framesIn;
6895 bool overrun = false;
6896 if (filled < 0) {
6897 // should not happen, but treat like a massive overrun and re-sync
6898 framesIn = 0;
6899 mRsmpInFront = rear;
6900 overrun = true;
6901 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6902 framesIn = (size_t) filled;
6903 } else {
6904 // client is not keeping up with server, but give it latest data
6905 framesIn = recordThread->mRsmpInFrames;
6906 mRsmpInFront = /* front = */ rear - framesIn;
6907 overrun = true;
6908 }
6909 if (framesAvailable != NULL) {
6910 *framesAvailable = framesIn;
6911 }
6912 if (hasOverrun != NULL) {
6913 *hasOverrun = overrun;
6914 }
6915}
6916
Eric Laurent81784c32012-11-19 14:55:58 -08006917// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006918status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006919 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006920{
Andy Hung73c02e42015-03-29 01:13:58 -07006921 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006922 if (threadBase == 0) {
6923 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006924 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006925 return NOT_ENOUGH_DATA;
6926 }
6927 RecordThread *recordThread = (RecordThread *) threadBase.get();
6928 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006929 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006930 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006931 // FIXME should not be P2 (don't want to increase latency)
6932 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006933 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006934 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006935 front &= recordThread->mRsmpInFramesP2 - 1;
6936 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006937 if (part1 > (size_t) filled) {
6938 part1 = filled;
6939 }
6940 size_t ask = buffer->frameCount;
6941 ALOG_ASSERT(ask > 0);
6942 if (part1 > ask) {
6943 part1 = ask;
6944 }
6945 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006946 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006947 buffer->raw = NULL;
6948 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006949 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006950 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006951 }
6952
Andy Hung57446612015-04-19 23:56:46 -07006953 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006954 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006955 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006956 return NO_ERROR;
6957}
6958
6959// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006960void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6961 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006962{
Glenn Kasten85948432013-08-19 12:09:05 -07006963 size_t stepCount = buffer->frameCount;
6964 if (stepCount == 0) {
6965 return;
6966 }
Andy Hung73c02e42015-03-29 01:13:58 -07006967 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6968 mRsmpInUnrel -= stepCount;
6969 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006970 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006971 buffer->frameCount = 0;
6972}
6973
Andy Hung97a893e2015-03-29 01:03:07 -07006974
Eric Laurent10351942014-05-08 18:49:52 -07006975bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6976 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006977{
6978 bool reconfig = false;
6979
Eric Laurent10351942014-05-08 18:49:52 -07006980 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006981
Eric Laurent10351942014-05-08 18:49:52 -07006982 audio_format_t reqFormat = mFormat;
6983 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006984 // 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 -07006985 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6986
6987 AudioParameter param = AudioParameter(keyValuePair);
6988 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07006989
6990 // scope for AutoPark extends to end of method
6991 AutoPark<FastCapture> park(mFastCapture);
6992
Eric Laurent10351942014-05-08 18:49:52 -07006993 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6994 // channel count change can be requested. Do we mandate the first client defines the
6995 // HAL sampling rate and channel count or do we allow changes on the fly?
6996 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6997 samplingRate = value;
6998 reconfig = true;
6999 }
7000 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007001 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007002 status = BAD_VALUE;
7003 } else {
7004 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007005 reconfig = true;
7006 }
Eric Laurent10351942014-05-08 18:49:52 -07007007 }
7008 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7009 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007010 if (!audio_is_input_channel(mask) ||
7011 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007012 status = BAD_VALUE;
7013 } else {
7014 channelMask = mask;
7015 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007016 }
Eric Laurent10351942014-05-08 18:49:52 -07007017 }
7018 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7019 // do not accept frame count changes if tracks are open as the track buffer
7020 // size depends on frame count and correct behavior would not be guaranteed
7021 // if frame count is changed after track creation
7022 if (mActiveTracks.size() > 0) {
7023 status = INVALID_OPERATION;
7024 } else {
7025 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007026 }
Eric Laurent10351942014-05-08 18:49:52 -07007027 }
7028 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7029 // forward device change to effects that have requested to be
7030 // aware of attached audio device.
7031 for (size_t i = 0; i < mEffectChains.size(); i++) {
7032 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007033 }
Eric Laurent81784c32012-11-19 14:55:58 -08007034
Eric Laurent10351942014-05-08 18:49:52 -07007035 // store input device and output device but do not forward output device to audio HAL.
7036 // Note that status is ignored by the caller for output device
7037 // (see AudioFlinger::setParameters()
7038 if (audio_is_output_devices(value)) {
7039 mOutDevice = value;
7040 status = BAD_VALUE;
7041 } else {
7042 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007043 if (value != AUDIO_DEVICE_NONE) {
7044 mPrevInDevice = value;
7045 }
Eric Laurent10351942014-05-08 18:49:52 -07007046 // disable AEC and NS if the device is a BT SCO headset supporting those
7047 // pre processings
7048 if (mTracks.size() > 0) {
7049 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7050 mAudioFlinger->btNrecIsOff();
7051 for (size_t i = 0; i < mTracks.size(); i++) {
7052 sp<RecordTrack> track = mTracks[i];
7053 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7054 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007055 }
7056 }
7057 }
Eric Laurent10351942014-05-08 18:49:52 -07007058 }
7059 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7060 mAudioSource != (audio_source_t)value) {
7061 // forward device change to effects that have requested to be
7062 // aware of attached audio device.
7063 for (size_t i = 0; i < mEffectChains.size(); i++) {
7064 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007065 }
Eric Laurent10351942014-05-08 18:49:52 -07007066 mAudioSource = (audio_source_t)value;
7067 }
Glenn Kastene198c362013-08-13 09:13:36 -07007068
Eric Laurent10351942014-05-08 18:49:52 -07007069 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007070 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007071 if (status == INVALID_OPERATION) {
7072 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007073 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007074 }
7075 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007076 if (status == BAD_VALUE) {
7077 uint32_t sRate;
7078 audio_channel_mask_t channelMask;
7079 audio_format_t format;
7080 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7081 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7082 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7083 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7084 status = NO_ERROR;
7085 }
Eric Laurent81784c32012-11-19 14:55:58 -08007086 }
Eric Laurent10351942014-05-08 18:49:52 -07007087 if (status == NO_ERROR) {
7088 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007089 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007090 }
7091 }
Eric Laurent81784c32012-11-19 14:55:58 -08007092 }
Eric Laurent10351942014-05-08 18:49:52 -07007093
Eric Laurent81784c32012-11-19 14:55:58 -08007094 return reconfig;
7095}
7096
7097String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7098{
Eric Laurent81784c32012-11-19 14:55:58 -08007099 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007100 if (initCheck() == NO_ERROR) {
7101 String8 out_s8;
7102 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7103 return out_s8;
7104 }
Eric Laurent81784c32012-11-19 14:55:58 -08007105 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007106 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007107}
7108
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007109void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007110 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7111
7112 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007113
7114 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007115 case AUDIO_INPUT_OPENED:
7116 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007117 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007118 desc->mChannelMask = mChannelMask;
7119 desc->mSamplingRate = mSampleRate;
7120 desc->mFormat = mFormat;
7121 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007122 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007123 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007124 break;
7125
Eric Laurent73e26b62015-04-27 16:55:58 -07007126 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007127 default:
7128 break;
7129 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007130 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007131}
7132
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007133void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007134{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007135 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7136 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007137 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007138 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007139 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007140 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7141 result = mInput->stream->getFrameSize(&mFrameSize);
7142 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7143 result = mInput->stream->getBufferSize(&mBufferSize);
7144 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007145 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007146 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007147 // 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 -07007148 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007149 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007150 // A larger value should allow more old data to be read after a track calls start(),
7151 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007152 //
7153 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007154 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007155 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007156 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007157 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007158
7159 // TODO optimize audio capture buffer sizes ...
7160 // Here we calculate the size of the sliding buffer used as a source
7161 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7162 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7163 // be better to have it derived from the pipe depth in the long term.
7164 // The current value is higher than necessary. However it should not add to latency.
7165
Glenn Kasten85948432013-08-19 12:09:05 -07007166 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007167 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7168 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7169 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007170
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007171 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7172 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007173}
7174
Glenn Kasten5f972c02014-01-13 09:59:31 -08007175uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007176{
7177 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007178 uint32_t result;
7179 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7180 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007181 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007182 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007183}
7184
Eric Laurent4c415062016-06-17 16:14:16 -07007185// hasAudioSession_l() must be called with ThreadBase::mLock held
7186uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007187{
Eric Laurent81784c32012-11-19 14:55:58 -08007188 uint32_t result = 0;
7189 if (getEffectChain_l(sessionId) != 0) {
7190 result = EFFECT_SESSION;
7191 }
7192
7193 for (size_t i = 0; i < mTracks.size(); ++i) {
7194 if (sessionId == mTracks[i]->sessionId()) {
7195 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007196 if (mTracks[i]->isFastTrack()) {
7197 result |= FAST_SESSION;
7198 }
Eric Laurent81784c32012-11-19 14:55:58 -08007199 break;
7200 }
7201 }
7202
7203 return result;
7204}
7205
Glenn Kastend848eb42016-03-08 13:42:11 -08007206KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007207{
Glenn Kastend848eb42016-03-08 13:42:11 -08007208 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007209 Mutex::Autolock _l(mLock);
7210 for (size_t j = 0; j < mTracks.size(); ++j) {
7211 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007212 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007213 if (ids.indexOfKey(sessionId) < 0) {
7214 ids.add(sessionId, true);
7215 }
7216 }
7217 return ids;
7218}
7219
7220AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7221{
7222 Mutex::Autolock _l(mLock);
7223 AudioStreamIn *input = mInput;
7224 mInput = NULL;
7225 return input;
7226}
7227
7228// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007229sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007230{
7231 if (mInput == NULL) {
7232 return NULL;
7233 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007234 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007235}
7236
7237status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7238{
7239 // only one chain per input thread
7240 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007241 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007242 return INVALID_OPERATION;
7243 }
7244 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007245 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007246 chain->setInBuffer(NULL);
7247 chain->setOutBuffer(NULL);
7248
7249 checkSuspendOnAddEffectChain_l(chain);
7250
Eric Laurent1b928682014-10-02 19:41:47 -07007251 // make sure enabled pre processing effects state is communicated to the HAL as we
7252 // just moved them to a new input stream.
7253 chain->syncHalEffectsState();
7254
Eric Laurent81784c32012-11-19 14:55:58 -08007255 mEffectChains.add(chain);
7256
7257 return NO_ERROR;
7258}
7259
7260size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7261{
7262 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7263 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007264 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007265 chain.get(), mEffectChains.size(), this);
7266 if (mEffectChains.size() == 1) {
7267 mEffectChains.removeAt(0);
7268 }
7269 return 0;
7270}
7271
Eric Laurent1c333e22014-05-20 10:48:17 -07007272status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7273 audio_patch_handle_t *handle)
7274{
7275 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007276
7277 // store new device and send to effects
7278 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007279 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007280 for (size_t i = 0; i < mEffectChains.size(); i++) {
7281 mEffectChains[i]->setDevice_l(mInDevice);
7282 }
7283
7284 // disable AEC and NS if the device is a BT SCO headset supporting those
7285 // pre processings
7286 if (mTracks.size() > 0) {
7287 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7288 mAudioFlinger->btNrecIsOff();
7289 for (size_t i = 0; i < mTracks.size(); i++) {
7290 sp<RecordTrack> track = mTracks[i];
7291 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7292 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7293 }
7294 }
7295
7296 // store new source and send to effects
7297 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7298 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007299 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007300 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007301 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007302 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007303
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007304 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007305 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7306 status = hwDevice->createAudioPatch(patch->num_sources,
7307 patch->sources,
7308 patch->num_sinks,
7309 patch->sinks,
7310 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007311 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007312 char *address;
7313 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7314 address = audio_device_address_to_parameter(
7315 patch->sources[0].ext.device.type,
7316 patch->sources[0].ext.device.address);
7317 } else {
7318 address = (char *)calloc(1, 1);
7319 }
7320 AudioParameter param = AudioParameter(String8(address));
7321 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007322 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007323 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007324 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007325 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007326 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007327 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007328 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007329
Eric Laurente8726fe2015-06-26 09:39:24 -07007330 if (mInDevice != mPrevInDevice) {
7331 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7332 mPrevInDevice = mInDevice;
7333 }
Eric Laurent296fb132015-05-01 11:38:42 -07007334
Eric Laurent1c333e22014-05-20 10:48:17 -07007335 return status;
7336}
7337
7338status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7339{
7340 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007341
7342 mInDevice = AUDIO_DEVICE_NONE;
7343
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007344 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007345 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7346 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007347 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007348 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007349 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007350 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007351 }
7352 return status;
7353}
7354
Eric Laurent83b88082014-06-20 18:31:16 -07007355void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7356{
7357 Mutex::Autolock _l(mLock);
7358 mTracks.add(record);
7359}
7360
7361void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7362{
7363 Mutex::Autolock _l(mLock);
7364 destroyTrack_l(record);
7365}
7366
7367void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7368{
7369 ThreadBase::getAudioPortConfig(config);
7370 config->role = AUDIO_PORT_ROLE_SINK;
7371 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7372 config->ext.mix.usecase.source = mAudioSource;
7373}
Eric Laurent1c333e22014-05-20 10:48:17 -07007374
Glenn Kasten63238ef2015-03-02 15:50:29 -08007375} // namespace android