blob: 8bf1688aabd2ccffbc24b9fcc97dab2c7017c320 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080032#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070033#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080035#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036
37#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070038#include <private/android_filesystem_config.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070043#include <system/audio_effects/effect_ns.h>
44#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046
47// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070048#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <media/nbaio/AudioStreamOutSink.h>
50#include <media/nbaio/MonoPipe.h>
51#include <media/nbaio/MonoPipeReader.h>
52#include <media/nbaio/Pipe.h>
53#include <media/nbaio/PipeReader.h>
54#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080055#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57#include <powermanager/PowerManager.h>
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
Glenn Kastenc05b8d72016-03-24 09:48:17 -070075#include "AutoPark.h"
76
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080077#include <pthread.h>
78#include "TypedLogger.h"
79
Eric Laurent81784c32012-11-19 14:55:58 -080080// ----------------------------------------------------------------------------
81
82// Note: the following macro is used for extremely verbose logging message. In
83// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
84// 0; but one side effect of this is to turn all LOGV's as well. Some messages
85// are so verbose that we want to suppress them even when we have ALOG_ASSERT
86// turned on. Do not uncomment the #def below unless you really know what you
87// are doing and want to see all of the extremely verbose messages.
88//#define VERY_VERY_VERBOSE_LOGGING
89#ifdef VERY_VERY_VERBOSE_LOGGING
90#define ALOGVV ALOGV
91#else
92#define ALOGVV(a...) do { } while(0)
93#endif
94
Andy Hung6770c6f2015-04-07 13:43:36 -070095// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070097template <typename T>
98static inline T min(const T& a, const T& b)
99{
100 return a < b ? a : b;
101}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700102
Andy Hungd330ee42015-04-20 13:23:41 -0700103#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700104#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700105#endif
106
Eric Laurent81784c32012-11-19 14:55:58 -0800107namespace android {
108
109// retry counts for buffer fill timeout
110// 50 * ~20msecs = 1 second
111static const int8_t kMaxTrackRetries = 50;
112static const int8_t kMaxTrackStartupRetries = 50;
113// allow less retry attempts on direct output thread.
114// direct outputs can be a scarce resource in audio hardware and should
115// be released as quickly as possible.
116static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700117
Eric Laurent51716182016-02-29 18:00:56 -0800118
Eric Laurent81784c32012-11-19 14:55:58 -0800119
120// don't warn about blocked writes or record buffer overflows more often than this
121static const nsecs_t kWarningThrottleNs = seconds(5);
122
123// RecordThread loop sleep time upon application overrun or audio HAL read error
124static const int kRecordThreadSleepUs = 5000;
125
Eric Laurent10351942014-05-08 18:49:52 -0700126// maximum time to wait in sendConfigEvent_l() for a status to be received
127static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800128
129// minimum sleep time for the mixer thread loop when tracks are active but in underrun
130static const uint32_t kMinThreadSleepTimeUs = 5000;
131// maximum divider applied to the active sleep time in the mixer thread loop
132static const uint32_t kMaxThreadSleepTimeShift = 2;
133
Andy Hung09a50072014-02-27 14:30:47 -0800134// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700135// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800136static const uint32_t kMinNormalSinkBufferSizeMs = 20;
137// maximum normal sink buffer size
138static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800139
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700140// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
141// FIXME This should be based on experimentally observed scheduling jitter
142static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
143
Eric Laurent972a1732013-09-04 09:42:59 -0700144// Offloaded output thread standby delay: allows track transition without going to standby
145static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
146
Eric Laurent51716182016-02-29 18:00:56 -0800147// Direct output thread minimum sleep time in idle or active(underrun) state
148static const nsecs_t kDirectMinSleepTimeUs = 10000;
149
Glenn Kasten1b291842016-07-18 14:55:21 -0700150// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
151// balance between power consumption and latency, and allows threads to be scheduled reliably
152// by the CFS scheduler.
153// FIXME Express other hardcoded references to 20ms with references to this constant and move
154// it appropriately.
155#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800156
Eric Laurent81784c32012-11-19 14:55:58 -0800157// Whether to use fast mixer
158static const enum {
159 FastMixer_Never, // never initialize or use: for debugging only
160 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
161 // normal mixer multiplier is 1
162 FastMixer_Static, // initialize if needed, then use all the time if initialized,
163 // multiplier is calculated based on min & max normal mixer buffer size
164 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
165 // multiplier is calculated based on min & max normal mixer buffer size
166 // FIXME for FastMixer_Dynamic:
167 // Supporting this option will require fixing HALs that can't handle large writes.
168 // For example, one HAL implementation returns an error from a large write,
169 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
170 // We could either fix the HAL implementations, or provide a wrapper that breaks
171 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
172} kUseFastMixer = FastMixer_Static;
173
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700174// Whether to use fast capture
175static const enum {
176 FastCapture_Never, // never initialize or use: for debugging only
177 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
178 FastCapture_Static, // initialize if needed, then use all the time if initialized
179} kUseFastCapture = FastCapture_Static;
180
Eric Laurent81784c32012-11-19 14:55:58 -0800181// Priorities for requestPriority
182static const int kPriorityAudioApp = 2;
183static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700184static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800185
Glenn Kastenea38ee72016-04-18 11:08:01 -0700186// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
187// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
188// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700189
190// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800191static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800192
Glenn Kasten03490092014-05-27 12:30:54 -0700193// The minimum and maximum allowed values
194static const int kFastTrackMultiplierMin = 1;
195static const int kFastTrackMultiplierMax = 2;
196
197// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
198static int sFastTrackMultiplier = kFastTrackMultiplier;
199
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700200// See Thread::readOnlyHeap().
201// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
202// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
203// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700204static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700205
Eric Laurent81784c32012-11-19 14:55:58 -0800206// ----------------------------------------------------------------------------
207
Glenn Kasten03490092014-05-27 12:30:54 -0700208static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
209
210static void sFastTrackMultiplierInit()
211{
212 char value[PROPERTY_VALUE_MAX];
213 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
214 char *endptr;
215 unsigned long ul = strtoul(value, &endptr, 0);
216 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
217 sFastTrackMultiplier = (int) ul;
218 }
219 }
220}
221
222// ----------------------------------------------------------------------------
223
Eric Laurent81784c32012-11-19 14:55:58 -0800224#ifdef ADD_BATTERY_DATA
225// To collect the amplifier usage
226static void addBatteryData(uint32_t params) {
227 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
228 if (service == NULL) {
229 // it already logged
230 return;
231 }
232
233 service->addBatteryData(params);
234}
235#endif
236
Andy Hung3f0c9022016-01-15 17:49:46 -0800237// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
238struct {
239 // call when you acquire a partial wakelock
240 void acquire(const sp<IBinder> &wakeLockToken) {
241 pthread_mutex_lock(&mLock);
242 if (wakeLockToken.get() == nullptr) {
243 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
244 } else {
245 if (mCount == 0) {
246 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
247 }
248 ++mCount;
249 }
250 pthread_mutex_unlock(&mLock);
251 }
252
253 // call when you release a partial wakelock.
254 void release(const sp<IBinder> &wakeLockToken) {
255 if (wakeLockToken.get() == nullptr) {
256 return;
257 }
258 pthread_mutex_lock(&mLock);
259 if (--mCount < 0) {
260 ALOGE("negative wakelock count");
261 mCount = 0;
262 }
263 pthread_mutex_unlock(&mLock);
264 }
265
266 // retrieves the boottime timebase offset from monotonic.
267 int64_t getBoottimeOffset() {
268 pthread_mutex_lock(&mLock);
269 int64_t boottimeOffset = mBoottimeOffset;
270 pthread_mutex_unlock(&mLock);
271 return boottimeOffset;
272 }
273
274 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
275 // and the selected timebase.
276 // Currently only TIMEBASE_BOOTTIME is allowed.
277 //
278 // This only needs to be called upon acquiring the first partial wakelock
279 // after all other partial wakelocks are released.
280 //
281 // We do an empirical measurement of the offset rather than parsing
282 // /proc/timer_list since the latter is not a formal kernel ABI.
283 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
284 int clockbase;
285 switch (timebase) {
286 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
287 clockbase = SYSTEM_TIME_BOOTTIME;
288 break;
289 default:
290 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
291 break;
292 }
293 // try three times to get the clock offset, choose the one
294 // with the minimum gap in measurements.
295 const int tries = 3;
296 nsecs_t bestGap, measured;
297 for (int i = 0; i < tries; ++i) {
298 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
299 const nsecs_t tbase = systemTime(clockbase);
300 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
301 const nsecs_t gap = tmono2 - tmono;
302 if (i == 0 || gap < bestGap) {
303 bestGap = gap;
304 measured = tbase - ((tmono + tmono2) >> 1);
305 }
306 }
307
308 // to avoid micro-adjusting, we don't change the timebase
309 // unless it is significantly different.
310 //
311 // Assumption: It probably takes more than toleranceNs to
312 // suspend and resume the device.
313 static int64_t toleranceNs = 10000; // 10 us
314 if (llabs(*offset - measured) > toleranceNs) {
315 ALOGV("Adjusting timebase offset old: %lld new: %lld",
316 (long long)*offset, (long long)measured);
317 *offset = measured;
318 }
319 }
320
321 pthread_mutex_t mLock;
322 int32_t mCount;
323 int64_t mBoottimeOffset;
324} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800325
326// ----------------------------------------------------------------------------
327// CPU Stats
328// ----------------------------------------------------------------------------
329
330class CpuStats {
331public:
332 CpuStats();
333 void sample(const String8 &title);
334#ifdef DEBUG_CPU_USAGE
335private:
336 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
337 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
338
339 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
340
341 int mCpuNum; // thread's current CPU number
342 int mCpukHz; // frequency of thread's current CPU in kHz
343#endif
344};
345
346CpuStats::CpuStats()
347#ifdef DEBUG_CPU_USAGE
348 : mCpuNum(-1), mCpukHz(-1)
349#endif
350{
351}
352
Glenn Kasten0f11b512014-01-31 16:18:54 -0800353void CpuStats::sample(const String8 &title
354#ifndef DEBUG_CPU_USAGE
355 __unused
356#endif
357 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800358#ifdef DEBUG_CPU_USAGE
359 // get current thread's delta CPU time in wall clock ns
360 double wcNs;
361 bool valid = mCpuUsage.sampleAndEnable(wcNs);
362
363 // record sample for wall clock statistics
364 if (valid) {
365 mWcStats.sample(wcNs);
366 }
367
368 // get the current CPU number
369 int cpuNum = sched_getcpu();
370
371 // get the current CPU frequency in kHz
372 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
373
374 // check if either CPU number or frequency changed
375 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
376 mCpuNum = cpuNum;
377 mCpukHz = cpukHz;
378 // ignore sample for purposes of cycles
379 valid = false;
380 }
381
382 // if no change in CPU number or frequency, then record sample for cycle statistics
383 if (valid && mCpukHz > 0) {
384 double cycles = wcNs * cpukHz * 0.000001;
385 mHzStats.sample(cycles);
386 }
387
388 unsigned n = mWcStats.n();
389 // mCpuUsage.elapsed() is expensive, so don't call it every loop
390 if ((n & 127) == 1) {
391 long long elapsed = mCpuUsage.elapsed();
392 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
393 double perLoop = elapsed / (double) n;
394 double perLoop100 = perLoop * 0.01;
395 double perLoop1k = perLoop * 0.001;
396 double mean = mWcStats.mean();
397 double stddev = mWcStats.stddev();
398 double minimum = mWcStats.minimum();
399 double maximum = mWcStats.maximum();
400 double meanCycles = mHzStats.mean();
401 double stddevCycles = mHzStats.stddev();
402 double minCycles = mHzStats.minimum();
403 double maxCycles = mHzStats.maximum();
404 mCpuUsage.resetElapsed();
405 mWcStats.reset();
406 mHzStats.reset();
407 ALOGD("CPU usage for %s over past %.1f secs\n"
408 " (%u mixer loops at %.1f mean ms per loop):\n"
409 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
410 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
411 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
412 title.string(),
413 elapsed * .000000001, n, perLoop * .000001,
414 mean * .001,
415 stddev * .001,
416 minimum * .001,
417 maximum * .001,
418 mean / perLoop100,
419 stddev / perLoop100,
420 minimum / perLoop100,
421 maximum / perLoop100,
422 meanCycles / perLoop1k,
423 stddevCycles / perLoop1k,
424 minCycles / perLoop1k,
425 maxCycles / perLoop1k);
426
427 }
428 }
429#endif
430};
431
432// ----------------------------------------------------------------------------
433// ThreadBase
434// ----------------------------------------------------------------------------
435
Glenn Kasten97b7b752014-09-28 13:04:24 -0700436// static
437const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
438{
439 switch (type) {
440 case MIXER:
441 return "MIXER";
442 case DIRECT:
443 return "DIRECT";
444 case DUPLICATING:
445 return "DUPLICATING";
446 case RECORD:
447 return "RECORD";
448 case OFFLOAD:
449 return "OFFLOAD";
450 default:
451 return "unknown";
452 }
453}
454
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700461 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800462 }
463 return result;
464}
465
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800467{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700468 std::string result;
469 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800470 return result;
471}
472
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700474{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700475 std::string result;
476 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477 return result;
478}
479
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800480const char *sourceToString(audio_source_t source)
481{
482 switch (source) {
483 case AUDIO_SOURCE_DEFAULT: return "default";
484 case AUDIO_SOURCE_MIC: return "mic";
485 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
486 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
487 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
488 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
489 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
490 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
491 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800492 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800493 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
494 case AUDIO_SOURCE_HOTWORD: return "hotword";
495 default: return "unknown";
496 }
497}
498
Eric Laurent81784c32012-11-19 14:55:58 -0800499AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700500 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800501 : Thread(false /*canCallJava*/),
502 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700503 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700504 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800505 // are set by PlaybackThread::readOutputParameters_l() or
506 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700507 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800508 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700509 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
510 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800511 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700512 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800513 mSystemReady(systemReady),
514 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800515{
Eric Laurent296fb132015-05-01 11:38:42 -0700516 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800517}
518
519AudioFlinger::ThreadBase::~ThreadBase()
520{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700521 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700522 mConfigEvents.clear();
523
Eric Laurent81784c32012-11-19 14:55:58 -0800524 // do not lock the mutex in destructor
525 releaseWakeLock_l();
526 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800527 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800528 binder->unlinkToDeath(mDeathRecipient);
529 }
530}
531
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700532status_t AudioFlinger::ThreadBase::readyToRun()
533{
534 status_t status = initCheck();
535 if (status == NO_ERROR) {
536 ALOGI("AudioFlinger's thread %p ready to run", this);
537 } else {
538 ALOGE("No working audio driver found.");
539 }
540 return status;
541}
542
Eric Laurent81784c32012-11-19 14:55:58 -0800543void AudioFlinger::ThreadBase::exit()
544{
545 ALOGV("ThreadBase::exit");
546 // do any cleanup required for exit to succeed
547 preExit();
548 {
549 // This lock prevents the following race in thread (uniprocessor for illustration):
550 // if (!exitPending()) {
551 // // context switch from here to exit()
552 // // exit() calls requestExit(), what exitPending() observes
553 // // exit() calls signal(), which is dropped since no waiters
554 // // context switch back from exit() to here
555 // mWaitWorkCV.wait(...);
556 // // now thread is hung
557 // }
558 AutoMutex lock(mLock);
559 requestExit();
560 mWaitWorkCV.broadcast();
561 }
562 // When Thread::requestExitAndWait is made virtual and this method is renamed to
563 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
564 requestExitAndWait();
565}
566
567status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
568{
Eric Laurent81784c32012-11-19 14:55:58 -0800569 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
570 Mutex::Autolock _l(mLock);
571
Eric Laurent10351942014-05-08 18:49:52 -0700572 return sendSetParameterConfigEvent_l(keyValuePairs);
573}
574
575// sendConfigEvent_l() must be called with ThreadBase::mLock held
576// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
577status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
578{
579 status_t status = NO_ERROR;
580
Eric Laurent72e3f392015-05-20 14:43:50 -0700581 if (event->mRequiresSystemReady && !mSystemReady) {
582 event->mWaitStatus = false;
583 mPendingConfigEvents.add(event);
584 return status;
585 }
Eric Laurent10351942014-05-08 18:49:52 -0700586 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700587 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800588 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700589 mLock.unlock();
590 {
591 Mutex::Autolock _l(event->mLock);
592 while (event->mWaitStatus) {
593 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
594 event->mStatus = TIMED_OUT;
595 event->mWaitStatus = false;
596 }
597 }
598 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800599 }
Eric Laurent10351942014-05-08 18:49:52 -0700600 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800601 return status;
602}
603
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700604void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800605{
606 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700607 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800608}
609
610// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800612{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700613 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700614 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800615}
616
Mikhail Naganov83f04272017-02-07 10:45:09 -0800617void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700618{
619 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800620 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700621}
622
Eric Laurent81784c32012-11-19 14:55:58 -0800623// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800624void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
625 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800626{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800627 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700628 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800629}
630
Eric Laurent10351942014-05-08 18:49:52 -0700631// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
632status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800633{
Andy Hung2ddee192015-12-18 17:34:44 -0800634 sp<ConfigEvent> configEvent;
635 AudioParameter param(keyValuePair);
636 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700637 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800638 setMasterMono_l(value != 0);
639 if (param.size() == 1) {
640 return NO_ERROR; // should be a solo parameter - we don't pass down
641 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700642 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800643 configEvent = new SetParameterConfigEvent(param.toString());
644 } else {
645 configEvent = new SetParameterConfigEvent(keyValuePair);
646 }
Eric Laurent10351942014-05-08 18:49:52 -0700647 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700648}
649
Eric Laurent1c333e22014-05-20 10:48:17 -0700650status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
651 const struct audio_patch *patch,
652 audio_patch_handle_t *handle)
653{
654 Mutex::Autolock _l(mLock);
655 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
656 status_t status = sendConfigEvent_l(configEvent);
657 if (status == NO_ERROR) {
658 CreateAudioPatchConfigEventData *data =
659 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
660 *handle = data->mHandle;
661 }
662 return status;
663}
664
665status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
666 const audio_patch_handle_t handle)
667{
668 Mutex::Autolock _l(mLock);
669 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
670 return sendConfigEvent_l(configEvent);
671}
672
673
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700674// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700675void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700676{
Eric Laurent10351942014-05-08 18:49:52 -0700677 bool configChanged = false;
678
Eric Laurent81784c32012-11-19 14:55:58 -0800679 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700680 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700681 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800682 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700683 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700684 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700685 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
686 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800687 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700688 true /*asynchronous*/);
689 if (err != 0) {
690 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700691 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700692 }
693 } break;
694 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700695 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700696 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700697 } break;
698 case CFG_EVENT_SET_PARAMETER: {
699 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
700 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
701 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700702 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700704 case CFG_EVENT_CREATE_AUDIO_PATCH: {
705 CreateAudioPatchConfigEventData *data =
706 (CreateAudioPatchConfigEventData *)event->mData.get();
707 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
708 } break;
709 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
710 ReleaseAudioPatchConfigEventData *data =
711 (ReleaseAudioPatchConfigEventData *)event->mData.get();
712 event->mStatus = releaseAudioPatch_l(data->mHandle);
713 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700714 default:
Eric Laurent10351942014-05-08 18:49:52 -0700715 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700716 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800717 }
Eric Laurent10351942014-05-08 18:49:52 -0700718 {
719 Mutex::Autolock _l(event->mLock);
720 if (event->mWaitStatus) {
721 event->mWaitStatus = false;
722 event->mCond.signal();
723 }
724 }
725 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
726 }
727
728 if (configChanged) {
729 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800730 }
Eric Laurent81784c32012-11-19 14:55:58 -0800731}
732
Marco Nelissenb2208842014-02-07 14:00:50 -0800733String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
734 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700735 const audio_channel_representation_t representation =
736 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700737
738 switch (representation) {
739 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
740 if (output) {
741 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
742 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
743 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
744 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
745 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
746 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
747 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
748 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
749 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
750 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
751 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
753 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
754 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
755 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
756 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
757 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
758 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
759 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
760 } else {
761 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
762 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
763 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
764 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
765 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
766 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
767 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
768 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
769 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
770 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
771 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
772 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
773 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
774 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
775 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
776 }
777 const int len = s.length();
778 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700779 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700780 s.unlockBuffer(len - 2); // remove trailing ", "
781 }
782 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800783 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700784 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
785 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
786 return s;
787 default:
788 s.appendFormat("unknown mask, representation:%d bits:%#x",
789 representation, audio_channel_mask_get_bits(mask));
790 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800791 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800792}
793
Glenn Kasten0f11b512014-01-31 16:18:54 -0800794void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800795{
796 const size_t SIZE = 256;
797 char buffer[SIZE];
798 String8 result;
799
800 bool locked = AudioFlinger::dumpTryLock(mLock);
801 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700802 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800803 }
804
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800805 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700806 dprintf(fd, " I/O handle: %d\n", mId);
807 dprintf(fd, " TID: %d\n", getTid());
808 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700809 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700810 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700811 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700812 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700813 dprintf(fd, " Channel count: %u\n", mChannelCount);
814 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800815 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700816 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700817 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800819 size_t numConfig = mConfigEvents.size();
820 if (numConfig) {
821 for (size_t i = 0; i < numConfig; i++) {
822 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800824 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700825 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800826 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700827 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800828 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700829 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
830 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800831 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800832
833 if (locked) {
834 mLock.unlock();
835 }
836}
837
838void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
839{
840 const size_t SIZE = 256;
841 char buffer[SIZE];
842 String8 result;
843
Marco Nelissenb2208842014-02-07 14:00:50 -0800844 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000845 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800846 write(fd, buffer, strlen(buffer));
847
Marco Nelissenb2208842014-02-07 14:00:50 -0800848 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800849 sp<EffectChain> chain = mEffectChains[i];
850 if (chain != 0) {
851 chain->dump(fd, args);
852 }
853 }
854}
855
Andy Hungdae27702016-10-31 14:01:16 -0700856void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800857{
858 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700859 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800860}
861
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100862String16 AudioFlinger::ThreadBase::getWakeLockTag()
863{
864 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800865 case MIXER:
866 return String16("AudioMix");
867 case DIRECT:
868 return String16("AudioDirectOut");
869 case DUPLICATING:
870 return String16("AudioDup");
871 case RECORD:
872 return String16("AudioIn");
873 case OFFLOAD:
874 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800875 case MMAP:
876 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800877 default:
878 ALOG_ASSERT(false);
879 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100880 }
881}
882
Andy Hungdae27702016-10-31 14:01:16 -0700883void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800884{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800885 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800886 if (mPowerManager != 0) {
887 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700888 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
889 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700890 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100891 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700892 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700893 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800894 if (status == NO_ERROR) {
895 mWakeLockToken = binder;
896 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800897 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800898 }
Wei Jia3f273d12015-11-24 09:06:49 -0800899
Andy Hung3f0c9022016-01-15 17:49:46 -0800900 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800901 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
902 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800903}
904
905void AudioFlinger::ThreadBase::releaseWakeLock()
906{
907 Mutex::Autolock _l(mLock);
908 releaseWakeLock_l();
909}
910
911void AudioFlinger::ThreadBase::releaseWakeLock_l()
912{
Andy Hung3f0c9022016-01-15 17:49:46 -0800913 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800914 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800915 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800916 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700917 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
918 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800919 }
920 mWakeLockToken.clear();
921 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800922}
923
924void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700925 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800926 // use checkService() to avoid blocking if power service is not up yet
927 sp<IBinder> binder =
928 defaultServiceManager()->checkService(String16("power"));
929 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800930 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800931 } else {
932 mPowerManager = interface_cast<IPowerManager>(binder);
933 binder->linkToDeath(mDeathRecipient);
934 }
935 }
936}
937
Andy Hungd01b0f12016-11-07 16:10:30 -0800938void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800939 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700940
941#if !LOG_NDEBUG
942 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800943 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700944 s << uid << " ";
945 }
946 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
947#endif
948
Andy Hung438e7572015-12-14 15:51:17 -0800949 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
950 if (mSystemReady) {
951 ALOGE("no wake lock to update, but system ready!");
952 } else {
953 ALOGW("no wake lock to update, system not ready yet");
954 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800955 return;
956 }
957 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800958 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
959 status_t status = mPowerManager->updateWakeLockUids(
960 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
961 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800962 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800963 }
964}
965
Eric Laurent81784c32012-11-19 14:55:58 -0800966void AudioFlinger::ThreadBase::clearPowerManager()
967{
968 Mutex::Autolock _l(mLock);
969 releaseWakeLock_l();
970 mPowerManager.clear();
971}
972
Glenn Kasten0f11b512014-01-31 16:18:54 -0800973void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800974{
975 sp<ThreadBase> thread = mThread.promote();
976 if (thread != 0) {
977 thread->clearPowerManager();
978 }
979 ALOGW("power manager service died !!!");
980}
981
982void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800983 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800984{
985 Mutex::Autolock _l(mLock);
986 setEffectSuspended_l(type, suspend, sessionId);
987}
988
989void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800990 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800991{
992 sp<EffectChain> chain = getEffectChain_l(sessionId);
993 if (chain != 0) {
994 if (type != NULL) {
995 chain->setEffectSuspended_l(type, suspend);
996 } else {
997 chain->setEffectSuspendedAll_l(suspend);
998 }
999 }
1000
1001 updateSuspendedSessions_l(type, suspend, sessionId);
1002}
1003
1004void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1005{
1006 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1007 if (index < 0) {
1008 return;
1009 }
1010
1011 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1012 mSuspendedSessions.valueAt(index);
1013
1014 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001015 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001016 for (int j = 0; j < desc->mRefCount; j++) {
1017 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1018 chain->setEffectSuspendedAll_l(true);
1019 } else {
1020 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1021 desc->mType.timeLow);
1022 chain->setEffectSuspended_l(&desc->mType, true);
1023 }
1024 }
1025 }
1026}
1027
1028void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1029 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001030 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001031{
1032 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1033
1034 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1035
1036 if (suspend) {
1037 if (index >= 0) {
1038 sessionEffects = mSuspendedSessions.valueAt(index);
1039 } else {
1040 mSuspendedSessions.add(sessionId, sessionEffects);
1041 }
1042 } else {
1043 if (index < 0) {
1044 return;
1045 }
1046 sessionEffects = mSuspendedSessions.valueAt(index);
1047 }
1048
1049
1050 int key = EffectChain::kKeyForSuspendAll;
1051 if (type != NULL) {
1052 key = type->timeLow;
1053 }
1054 index = sessionEffects.indexOfKey(key);
1055
1056 sp<SuspendedSessionDesc> desc;
1057 if (suspend) {
1058 if (index >= 0) {
1059 desc = sessionEffects.valueAt(index);
1060 } else {
1061 desc = new SuspendedSessionDesc();
1062 if (type != NULL) {
1063 desc->mType = *type;
1064 }
1065 sessionEffects.add(key, desc);
1066 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1067 }
1068 desc->mRefCount++;
1069 } else {
1070 if (index < 0) {
1071 return;
1072 }
1073 desc = sessionEffects.valueAt(index);
1074 if (--desc->mRefCount == 0) {
1075 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1076 sessionEffects.removeItemsAt(index);
1077 if (sessionEffects.isEmpty()) {
1078 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1079 sessionId);
1080 mSuspendedSessions.removeItem(sessionId);
1081 }
1082 }
1083 }
1084 if (!sessionEffects.isEmpty()) {
1085 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1086 }
1087}
1088
1089void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1090 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001091 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001092{
1093 Mutex::Autolock _l(mLock);
1094 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1095}
1096
1097void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1098 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001099 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001100{
1101 if (mType != RECORD) {
1102 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1103 // another session. This gives the priority to well behaved effect control panels
1104 // and applications not using global effects.
1105 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1106 // global effects
1107 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1108 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1109 }
1110 }
1111
1112 sp<EffectChain> chain = getEffectChain_l(sessionId);
1113 if (chain != 0) {
1114 chain->checkSuspendOnEffectEnabled(effect, enabled);
1115 }
1116}
1117
Eric Laurent4c415062016-06-17 16:14:16 -07001118// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1119status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1120 const effect_descriptor_t *desc, audio_session_t sessionId)
1121{
1122 // No global effect sessions on record threads
1123 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1124 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1125 desc->name, mThreadName);
1126 return BAD_VALUE;
1127 }
1128 // only pre processing effects on record thread
1129 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1130 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1131 desc->name, mThreadName);
1132 return BAD_VALUE;
1133 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001134
1135 // always allow effects without processing load or latency
1136 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1137 return NO_ERROR;
1138 }
1139
Eric Laurent4c415062016-06-17 16:14:16 -07001140 audio_input_flags_t flags = mInput->flags;
1141 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1142 if (flags & AUDIO_INPUT_FLAG_RAW) {
1143 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1144 desc->name, mThreadName);
1145 return BAD_VALUE;
1146 }
1147 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1148 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1149 desc->name, mThreadName);
1150 return BAD_VALUE;
1151 }
1152 }
1153 return NO_ERROR;
1154}
1155
1156// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1157status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1158 const effect_descriptor_t *desc, audio_session_t sessionId)
1159{
1160 // no preprocessing on playback threads
1161 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1162 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1163 " thread %s", desc->name, mThreadName);
1164 return BAD_VALUE;
1165 }
1166
1167 switch (mType) {
1168 case MIXER: {
1169 // Reject any effect on mixer multichannel sinks.
1170 // TODO: fix both format and multichannel issues with effects.
1171 if (mChannelCount != FCC_2) {
1172 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1173 " thread %s", desc->name, mChannelCount, mThreadName);
1174 return BAD_VALUE;
1175 }
1176 audio_output_flags_t flags = mOutput->flags;
1177 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1178 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1179 // global effects are applied only to non fast tracks if they are SW
1180 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1181 break;
1182 }
1183 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1184 // only post processing on output stage session
1185 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1186 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1187 " on output stage session", desc->name);
1188 return BAD_VALUE;
1189 }
1190 } else {
1191 // no restriction on effects applied on non fast tracks
1192 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1193 break;
1194 }
1195 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001196
1197 // always allow effects without processing load or latency
1198 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1199 break;
1200 }
Eric Laurent4c415062016-06-17 16:14:16 -07001201 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1202 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1203 desc->name);
1204 return BAD_VALUE;
1205 }
1206 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1207 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1208 " in fast mode", desc->name);
1209 return BAD_VALUE;
1210 }
1211 }
1212 } break;
1213 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001214 // nothing actionable on offload threads, if the effect:
1215 // - is offloadable: the effect can be created
1216 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1217 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001218 break;
1219 case DIRECT:
1220 // Reject any effect on Direct output threads for now, since the format of
1221 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1222 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1223 desc->name, mThreadName);
1224 return BAD_VALUE;
1225 case DUPLICATING:
1226 // Reject any effect on mixer multichannel sinks.
1227 // TODO: fix both format and multichannel issues with effects.
1228 if (mChannelCount != FCC_2) {
1229 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1230 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1231 return BAD_VALUE;
1232 }
1233 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1234 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1235 " thread %s", desc->name, mThreadName);
1236 return BAD_VALUE;
1237 }
1238 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1239 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1240 " DUPLICATING thread %s", desc->name, mThreadName);
1241 return BAD_VALUE;
1242 }
1243 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1244 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1245 " DUPLICATING thread %s", desc->name, mThreadName);
1246 return BAD_VALUE;
1247 }
1248 break;
1249 default:
1250 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1251 }
1252
1253 return NO_ERROR;
1254}
1255
Eric Laurent81784c32012-11-19 14:55:58 -08001256// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1257sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1258 const sp<AudioFlinger::Client>& client,
1259 const sp<IEffectClient>& effectClient,
1260 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001261 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001262 effect_descriptor_t *desc,
1263 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001264 status_t *status,
1265 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001266{
1267 sp<EffectModule> effect;
1268 sp<EffectHandle> handle;
1269 status_t lStatus;
1270 sp<EffectChain> chain;
1271 bool chainCreated = false;
1272 bool effectCreated = false;
1273 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001274 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001275
1276 lStatus = initCheck();
1277 if (lStatus != NO_ERROR) {
1278 ALOGW("createEffect_l() Audio driver not initialized.");
1279 goto Exit;
1280 }
1281
Eric Laurent81784c32012-11-19 14:55:58 -08001282 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1283
1284 { // scope for mLock
1285 Mutex::Autolock _l(mLock);
1286
Eric Laurent4c415062016-06-17 16:14:16 -07001287 lStatus = checkEffectCompatibility_l(desc, sessionId);
1288 if (lStatus != NO_ERROR) {
1289 goto Exit;
1290 }
1291
Eric Laurent81784c32012-11-19 14:55:58 -08001292 // check for existing effect chain with the requested audio session
1293 chain = getEffectChain_l(sessionId);
1294 if (chain == 0) {
1295 // create a new chain for this session
1296 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1297 chain = new EffectChain(this, sessionId);
1298 addEffectChain_l(chain);
1299 chain->setStrategy(getStrategyForSession_l(sessionId));
1300 chainCreated = true;
1301 } else {
1302 effect = chain->getEffectFromDesc_l(desc);
1303 }
1304
1305 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1306
1307 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001308 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001309 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001310 lStatus = AudioSystem::registerEffect(
1311 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001312 if (lStatus != NO_ERROR) {
1313 goto Exit;
1314 }
1315 effectRegistered = true;
1316 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001317 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001318 if (lStatus != NO_ERROR) {
1319 goto Exit;
1320 }
1321 effectCreated = true;
1322
1323 effect->setDevice(mOutDevice);
1324 effect->setDevice(mInDevice);
1325 effect->setMode(mAudioFlinger->getMode());
1326 effect->setAudioSource(mAudioSource);
1327 }
1328 // create effect handle and connect it to effect module
1329 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001330 lStatus = handle->initCheck();
1331 if (lStatus == OK) {
1332 lStatus = effect->addHandle(handle.get());
1333 }
Eric Laurent81784c32012-11-19 14:55:58 -08001334 if (enabled != NULL) {
1335 *enabled = (int)effect->isEnabled();
1336 }
1337 }
1338
1339Exit:
1340 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1341 Mutex::Autolock _l(mLock);
1342 if (effectCreated) {
1343 chain->removeEffect_l(effect);
1344 }
1345 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001346 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001347 }
1348 if (chainCreated) {
1349 removeEffectChain_l(chain);
1350 }
1351 handle.clear();
1352 }
1353
Glenn Kasten9156ef32013-08-06 15:39:08 -07001354 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001355 return handle;
1356}
1357
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001358void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1359 bool unpinIfLast)
1360{
1361 bool remove = false;
1362 sp<EffectModule> effect;
1363 {
1364 Mutex::Autolock _l(mLock);
1365
1366 effect = handle->effect().promote();
1367 if (effect == 0) {
1368 return;
1369 }
1370 // restore suspended effects if the disconnected handle was enabled and the last one.
1371 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1372 if (remove) {
1373 removeEffect_l(effect, true);
1374 }
1375 }
1376 if (remove) {
1377 mAudioFlinger->updateOrphanEffectChains(effect);
1378 AudioSystem::unregisterEffect(effect->id());
1379 if (handle->enabled()) {
1380 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1381 }
1382 }
1383}
1384
Glenn Kastend848eb42016-03-08 13:42:11 -08001385sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1386 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001387{
1388 Mutex::Autolock _l(mLock);
1389 return getEffect_l(sessionId, effectId);
1390}
1391
Glenn Kastend848eb42016-03-08 13:42:11 -08001392sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1393 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001394{
1395 sp<EffectChain> chain = getEffectChain_l(sessionId);
1396 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1397}
1398
1399// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1400// PlaybackThread::mLock held
1401status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1402{
1403 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001404 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001405 sp<EffectChain> chain = getEffectChain_l(sessionId);
1406 bool chainCreated = false;
1407
Eric Laurent5baf2af2013-09-12 17:37:00 -07001408 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1409 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1410 this, effect->desc().name, effect->desc().flags);
1411
Eric Laurent81784c32012-11-19 14:55:58 -08001412 if (chain == 0) {
1413 // create a new chain for this session
1414 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1415 chain = new EffectChain(this, sessionId);
1416 addEffectChain_l(chain);
1417 chain->setStrategy(getStrategyForSession_l(sessionId));
1418 chainCreated = true;
1419 }
1420 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1421
1422 if (chain->getEffectFromId_l(effect->id()) != 0) {
1423 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1424 this, effect->desc().name, chain.get());
1425 return BAD_VALUE;
1426 }
1427
Eric Laurent5baf2af2013-09-12 17:37:00 -07001428 effect->setOffloaded(mType == OFFLOAD, mId);
1429
Eric Laurent81784c32012-11-19 14:55:58 -08001430 status_t status = chain->addEffect_l(effect);
1431 if (status != NO_ERROR) {
1432 if (chainCreated) {
1433 removeEffectChain_l(chain);
1434 }
1435 return status;
1436 }
1437
1438 effect->setDevice(mOutDevice);
1439 effect->setDevice(mInDevice);
1440 effect->setMode(mAudioFlinger->getMode());
1441 effect->setAudioSource(mAudioSource);
1442 return NO_ERROR;
1443}
1444
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001445void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001446
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001447 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001448 effect_descriptor_t desc = effect->desc();
1449 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1450 detachAuxEffect_l(effect->id());
1451 }
1452
1453 sp<EffectChain> chain = effect->chain().promote();
1454 if (chain != 0) {
1455 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001456 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001457 removeEffectChain_l(chain);
1458 }
1459 } else {
1460 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1461 }
1462}
1463
1464void AudioFlinger::ThreadBase::lockEffectChains_l(
1465 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1466{
1467 effectChains = mEffectChains;
1468 for (size_t i = 0; i < mEffectChains.size(); i++) {
1469 mEffectChains[i]->lock();
1470 }
1471}
1472
1473void AudioFlinger::ThreadBase::unlockEffectChains(
1474 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1475{
1476 for (size_t i = 0; i < effectChains.size(); i++) {
1477 effectChains[i]->unlock();
1478 }
1479}
1480
Glenn Kastend848eb42016-03-08 13:42:11 -08001481sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001482{
1483 Mutex::Autolock _l(mLock);
1484 return getEffectChain_l(sessionId);
1485}
1486
Glenn Kastend848eb42016-03-08 13:42:11 -08001487sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1488 const
Eric Laurent81784c32012-11-19 14:55:58 -08001489{
1490 size_t size = mEffectChains.size();
1491 for (size_t i = 0; i < size; i++) {
1492 if (mEffectChains[i]->sessionId() == sessionId) {
1493 return mEffectChains[i];
1494 }
1495 }
1496 return 0;
1497}
1498
1499void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1500{
1501 Mutex::Autolock _l(mLock);
1502 size_t size = mEffectChains.size();
1503 for (size_t i = 0; i < size; i++) {
1504 mEffectChains[i]->setMode_l(mode);
1505 }
1506}
1507
Eric Laurent83b88082014-06-20 18:31:16 -07001508void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1509{
1510 config->type = AUDIO_PORT_TYPE_MIX;
1511 config->ext.mix.handle = mId;
1512 config->sample_rate = mSampleRate;
1513 config->format = mFormat;
1514 config->channel_mask = mChannelMask;
1515 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1516 AUDIO_PORT_CONFIG_FORMAT;
1517}
1518
Eric Laurent72e3f392015-05-20 14:43:50 -07001519void AudioFlinger::ThreadBase::systemReady()
1520{
1521 Mutex::Autolock _l(mLock);
1522 if (mSystemReady) {
1523 return;
1524 }
1525 mSystemReady = true;
1526
1527 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1528 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1529 }
1530 mPendingConfigEvents.clear();
1531}
1532
Andy Hungdae27702016-10-31 14:01:16 -07001533template <typename T>
1534ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1535 ssize_t index = mActiveTracks.indexOf(track);
1536 if (index >= 0) {
1537 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1538 return index;
1539 }
1540 mActiveTracksGeneration++;
1541 mLatestActiveTrack = track;
1542 ++mBatteryCounter[track->uid()].second;
1543 return mActiveTracks.add(track);
1544}
1545
1546template <typename T>
1547ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1548 ssize_t index = mActiveTracks.remove(track);
1549 if (index < 0) {
1550 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1551 return index;
1552 }
1553 mActiveTracksGeneration++;
1554 --mBatteryCounter[track->uid()].second;
1555 // mLatestActiveTrack is not cleared even if is the same as track.
1556 return index;
1557}
1558
1559template <typename T>
1560void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1561 for (const sp<T> &track : mActiveTracks) {
1562 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1563 }
1564 mLastActiveTracksGeneration = mActiveTracksGeneration;
1565 mActiveTracks.clear();
1566 mLatestActiveTrack.clear();
1567 mBatteryCounter.clear();
1568}
1569
1570template <typename T>
1571void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1572 sp<ThreadBase> thread, bool force) {
1573 // Updates ActiveTracks client uids to the thread wakelock.
1574 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1575 thread->updateWakeLockUids_l(getWakeLockUids());
1576 mLastActiveTracksGeneration = mActiveTracksGeneration;
1577 }
1578
1579 // Updates BatteryNotifier uids
1580 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1581 const uid_t uid = it->first;
1582 ssize_t &previous = it->second.first;
1583 ssize_t &current = it->second.second;
1584 if (current > 0) {
1585 if (previous == 0) {
1586 BatteryNotifier::getInstance().noteStartAudio(uid);
1587 }
1588 previous = current;
1589 ++it;
1590 } else if (current == 0) {
1591 if (previous > 0) {
1592 BatteryNotifier::getInstance().noteStopAudio(uid);
1593 }
1594 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1595 } else /* (current < 0) */ {
1596 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1597 }
1598 }
1599}
Eric Laurent83b88082014-06-20 18:31:16 -07001600
Eric Laurent6acd1d42017-01-04 14:23:29 -08001601void AudioFlinger::ThreadBase::broadcast_l()
1602{
1603 // Thread could be blocked waiting for async
1604 // so signal it to handle state changes immediately
1605 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1606 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1607 mSignalPending = true;
1608 mWaitWorkCV.broadcast();
1609}
1610
Eric Laurent81784c32012-11-19 14:55:58 -08001611// ----------------------------------------------------------------------------
1612// Playback
1613// ----------------------------------------------------------------------------
1614
1615AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1616 AudioStreamOut* output,
1617 audio_io_handle_t id,
1618 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001619 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001620 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001621 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001622 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001623 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001624 mMixerBuffer(NULL),
1625 mMixerBufferSize(0),
1626 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1627 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001628 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001629 mEffectBuffer(NULL),
1630 mEffectBufferSize(0),
1631 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1632 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001633 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001634 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001635 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001636 // mStreamTypes[] initialized in constructor body
1637 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001638 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001639 mMixerStatus(MIXER_IDLE),
1640 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001641 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001642 mBytesRemaining(0),
1643 mCurrentWriteLength(0),
1644 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001645 mWriteAckSequence(0),
1646 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001647 mScreenState(AudioFlinger::mScreenState),
1648 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001649 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001650 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001651{
Glenn Kastend7dca052015-03-05 16:05:54 -08001652 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1653 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001654
1655 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1656 // it would be safer to explicitly pass initial masterVolume/masterMute as
1657 // parameter.
1658 //
1659 // If the HAL we are using has support for master volume or master mute,
1660 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1661 // and the mute set to false).
1662 mMasterVolume = audioFlinger->masterVolume_l();
1663 mMasterMute = audioFlinger->masterMute_l();
1664 if (mOutput && mOutput->audioHwDev) {
1665 if (mOutput->audioHwDev->canSetMasterVolume()) {
1666 mMasterVolume = 1.0;
1667 }
1668
1669 if (mOutput->audioHwDev->canSetMasterMute()) {
1670 mMasterMute = false;
1671 }
1672 }
1673
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001674 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001675
Eric Laurent223fd5c2014-11-11 13:43:36 -08001676 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001677 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001678 stream = (audio_stream_type_t) (stream + 1)) {
1679 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1680 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1681 }
Eric Laurent81784c32012-11-19 14:55:58 -08001682}
1683
1684AudioFlinger::PlaybackThread::~PlaybackThread()
1685{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001686 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001687 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001688 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001689 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001690}
1691
1692void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1693{
1694 dumpInternals(fd, args);
1695 dumpTracks(fd, args);
1696 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001697 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001698}
1699
Glenn Kasten0f11b512014-01-31 16:18:54 -08001700void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001701{
1702 const size_t SIZE = 256;
1703 char buffer[SIZE];
1704 String8 result;
1705
Marco Nelissenb2208842014-02-07 14:00:50 -08001706 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001707 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1708 const stream_type_t *st = &mStreamTypes[i];
1709 if (i > 0) {
1710 result.appendFormat(", ");
1711 }
1712 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1713 if (st->mute) {
1714 result.append("M");
1715 }
1716 }
1717 result.append("\n");
1718 write(fd, result.string(), result.length());
1719 result.clear();
1720
Eric Laurent81784c32012-11-19 14:55:58 -08001721 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1722 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001723 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001724 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001725
1726 size_t numtracks = mTracks.size();
1727 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001728 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001729 size_t numactiveseen = 0;
1730 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001731 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001732 Track::appendDumpHeader(result);
1733 for (size_t i = 0; i < numtracks; ++i) {
1734 sp<Track> track = mTracks[i];
1735 if (track != 0) {
1736 bool active = mActiveTracks.indexOf(track) >= 0;
1737 if (active) {
1738 numactiveseen++;
1739 }
1740 track->dump(buffer, SIZE, active);
1741 result.append(buffer);
1742 }
1743 }
1744 } else {
1745 result.append("\n");
1746 }
1747 if (numactiveseen != numactive) {
1748 // some tracks in the active list were not in the tracks list
1749 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1750 " not in the track list\n");
1751 result.append(buffer);
1752 Track::appendDumpHeader(result);
1753 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001754 sp<Track> track = mActiveTracks[i];
1755 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001756 track->dump(buffer, SIZE, true);
1757 result.append(buffer);
1758 }
1759 }
1760 }
1761
1762 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001763}
1764
1765void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1766{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001767 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001768
1769 dumpBase(fd, args);
1770
Elliott Hughes87cebad2014-05-22 10:14:43 -07001771 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001772 dprintf(fd, " Last write occurred (msecs): %llu\n",
1773 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001774 dprintf(fd, " Total writes: %d\n", mNumWrites);
1775 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1776 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1777 dprintf(fd, " Suspend count: %d\n", mSuspended);
1778 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1779 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1780 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1781 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001782 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001783 AudioStreamOut *output = mOutput;
1784 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001785 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1786 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001787 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1788 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1789 if (mPipeSink.get() != nullptr) {
1790 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1791 }
1792 if (output != nullptr) {
1793 dprintf(fd, " Hal stream dump:\n");
1794 (void)output->stream->dump(fd);
1795 }
Eric Laurent81784c32012-11-19 14:55:58 -08001796}
1797
1798// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001799
1800void AudioFlinger::PlaybackThread::onFirstRef()
1801{
Glenn Kastend7dca052015-03-05 16:05:54 -08001802 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001803}
1804
1805// ThreadBase virtuals
1806void AudioFlinger::PlaybackThread::preExit()
1807{
1808 ALOGV(" preExit()");
1809 // FIXME this is using hard-coded strings but in the future, this functionality will be
1810 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001811 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1812 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001813}
1814
1815// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1816sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1817 const sp<AudioFlinger::Client>& client,
1818 audio_stream_type_t streamType,
1819 uint32_t sampleRate,
1820 audio_format_t format,
1821 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001822 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001823 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001824 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001825 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001826 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001827 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001828 status_t *status,
1829 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001830{
Glenn Kasten74935e42013-12-19 08:56:45 -08001831 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001832 sp<Track> track;
1833 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001834 audio_output_flags_t outputFlags = mOutput->flags;
1835
1836 // special case for FAST flag considered OK if fast mixer is present
1837 if (hasFastMixer()) {
1838 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1839 }
1840
1841 // Check if requested flags are compatible with output stream flags
1842 if ((*flags & outputFlags) != *flags) {
1843 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1844 *flags, outputFlags);
1845 *flags = (audio_output_flags_t)(*flags & outputFlags);
1846 }
Eric Laurent81784c32012-11-19 14:55:58 -08001847
Eric Laurent81784c32012-11-19 14:55:58 -08001848 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001849 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001850 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001851 // PCM data
1852 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001853 // TODO: extract as a data library function that checks that a computationally
1854 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001855 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001856 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1857 (channelMask == AUDIO_CHANNEL_OUT_MONO
1858 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001859 // hardware sample rate
1860 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001861 // normal mixer has an associated fast mixer
1862 hasFastMixer() &&
1863 // there are sufficient fast track slots available
1864 (mFastTrackAvailMask != 0)
1865 // FIXME test that MixerThread for this fast track has a capable output HAL
1866 // FIXME add a permission test also?
1867 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001868 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1869 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001870 // read the fast track multiplier property the first time it is needed
1871 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1872 if (ok != 0) {
1873 ALOGE("%s pthread_once failed: %d", __func__, ok);
1874 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001875 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001876 }
Eric Laurent4c415062016-06-17 16:14:16 -07001877
1878 // check compatibility with audio effects.
1879 { // scope for mLock
1880 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001881 for (audio_session_t session : {
1882 AUDIO_SESSION_OUTPUT_STAGE,
1883 AUDIO_SESSION_OUTPUT_MIX,
1884 sessionId,
1885 }) {
1886 sp<EffectChain> chain = getEffectChain_l(session);
1887 if (chain.get() != nullptr) {
1888 audio_output_flags_t old = *flags;
1889 chain->checkOutputFlagCompatibility(flags);
1890 if (old != *flags) {
1891 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1892 (int)session, (int)old, (int)*flags);
1893 }
Eric Laurent4c415062016-06-17 16:14:16 -07001894 }
1895 }
1896 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001897 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001898 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1899 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001900 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001901 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1902 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001903 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001904 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001905 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001906 audio_is_linear_pcm(format),
1907 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001908 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001909 }
1910 }
1911 // For normal PCM streaming tracks, update minimum frame count.
1912 // For compatibility with AudioTrack calculation, buffer depth is forced
1913 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1914 // This is probably too conservative, but legacy application code may depend on it.
1915 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001916 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001917 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001918 // this must match AudioTrack.cpp calculateMinFrameCount().
1919 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001920 uint32_t latencyMs = 0;
1921 lStatus = mOutput->stream->getLatency(&latencyMs);
1922 if (lStatus != OK) {
1923 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1924 goto Exit;
1925 }
Eric Laurent81784c32012-11-19 14:55:58 -08001926 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1927 if (minBufCount < 2) {
1928 minBufCount = 2;
1929 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001930 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1931 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001932 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001933 minBufCount * sourceFramesNeededWithTimestretch(
1934 sampleRate, mNormalFrameCount,
1935 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001936 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001937 frameCount = minFrameCount;
1938 }
Eric Laurent81784c32012-11-19 14:55:58 -08001939 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001940 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001941
Glenn Kastenc3df8382014-03-13 15:05:25 -07001942 switch (mType) {
1943
1944 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001945 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001946 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001947 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1948 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001949 sampleRate, format, channelMask, mOutput, mFormat);
1950 lStatus = BAD_VALUE;
1951 goto Exit;
1952 }
1953 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001954 break;
1955
1956 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001957 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001958 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1959 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001960 sampleRate, format, channelMask, mOutput, mFormat);
1961 lStatus = BAD_VALUE;
1962 goto Exit;
1963 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001964 break;
1965
1966 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001967 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001968 ALOGE("createTrack_l() Bad parameter: format %#x \""
1969 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970 format, mOutput, mFormat);
1971 lStatus = BAD_VALUE;
1972 goto Exit;
1973 }
Andy Hungcd044842014-08-07 11:04:34 -07001974 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001975 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1976 lStatus = BAD_VALUE;
1977 goto Exit;
1978 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001979 break;
1980
Eric Laurent81784c32012-11-19 14:55:58 -08001981 }
1982
1983 lStatus = initCheck();
1984 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001985 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001986 goto Exit;
1987 }
1988
1989 { // scope for mLock
1990 Mutex::Autolock _l(mLock);
1991
1992 // all tracks in same audio session must share the same routing strategy otherwise
1993 // conflicts will happen when tracks are moved from one output to another by audio policy
1994 // manager
1995 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1996 for (size_t i = 0; i < mTracks.size(); ++i) {
1997 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001998 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001999 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2000 if (sessionId == t->sessionId() && strategy != actual) {
2001 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2002 strategy, actual);
2003 lStatus = BAD_VALUE;
2004 goto Exit;
2005 }
2006 }
2007 }
2008
Glenn Kastend79072e2016-01-06 08:41:20 -08002009 track = new Track(this, client, streamType, sampleRate, format,
2010 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002011 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002012
Glenn Kasten03003332013-08-06 15:40:54 -07002013 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2014 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002015 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002016 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002017 goto Exit;
2018 }
2019 mTracks.add(track);
2020
2021 sp<EffectChain> chain = getEffectChain_l(sessionId);
2022 if (chain != 0) {
2023 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2024 track->setMainBuffer(chain->inBuffer());
2025 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2026 chain->incTrackCnt();
2027 }
2028
Eric Laurent05067782016-06-01 18:27:28 -07002029 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002030 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2031 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2032 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08002033 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*isForApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002034 }
2035 }
2036
2037 lStatus = NO_ERROR;
2038
2039Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002040 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002041 return track;
2042}
2043
2044uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2045{
2046 return latency;
2047}
2048
2049uint32_t AudioFlinger::PlaybackThread::latency() const
2050{
2051 Mutex::Autolock _l(mLock);
2052 return latency_l();
2053}
2054uint32_t AudioFlinger::PlaybackThread::latency_l() const
2055{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002056 uint32_t latency;
2057 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2058 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002059 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002060 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002061}
2062
2063void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2064{
2065 Mutex::Autolock _l(mLock);
2066 // Don't apply master volume in SW if our HAL can do it for us.
2067 if (mOutput && mOutput->audioHwDev &&
2068 mOutput->audioHwDev->canSetMasterVolume()) {
2069 mMasterVolume = 1.0;
2070 } else {
2071 mMasterVolume = value;
2072 }
2073}
2074
2075void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2076{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002077 if (isDuplicating()) {
2078 return;
2079 }
Eric Laurent81784c32012-11-19 14:55:58 -08002080 Mutex::Autolock _l(mLock);
2081 // Don't apply master mute in SW if our HAL can do it for us.
2082 if (mOutput && mOutput->audioHwDev &&
2083 mOutput->audioHwDev->canSetMasterMute()) {
2084 mMasterMute = false;
2085 } else {
2086 mMasterMute = muted;
2087 }
2088}
2089
2090void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2091{
2092 Mutex::Autolock _l(mLock);
2093 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002094 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002095}
2096
2097void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2098{
2099 Mutex::Autolock _l(mLock);
2100 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002101 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002102}
2103
2104float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2105{
2106 Mutex::Autolock _l(mLock);
2107 return mStreamTypes[stream].volume;
2108}
2109
2110// addTrack_l() must be called with ThreadBase::mLock held
2111status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2112{
2113 status_t status = ALREADY_EXISTS;
2114
Eric Laurent81784c32012-11-19 14:55:58 -08002115 if (mActiveTracks.indexOf(track) < 0) {
2116 // the track is newly added, make sure it fills up all its
2117 // buffers before playing. This is to ensure the client will
2118 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002119 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002120 TrackBase::track_state state = track->mState;
2121 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002122 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002123 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002124 mLock.lock();
2125 // abort track was stopped/paused while we released the lock
2126 if (state != track->mState) {
2127 if (status == NO_ERROR) {
2128 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002129 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002130 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002131 mLock.lock();
2132 }
2133 return INVALID_OPERATION;
2134 }
2135 // abort if start is rejected by audio policy manager
2136 if (status != NO_ERROR) {
2137 return PERMISSION_DENIED;
2138 }
2139#ifdef ADD_BATTERY_DATA
2140 // to track the speaker usage
2141 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2142#endif
2143 }
2144
Eric Laurent51716182016-02-29 18:00:56 -08002145 // set retry count for buffer fill
2146 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002147 if (track->isStopping_1()) {
2148 track->mRetryCount = kMaxTrackStopRetriesOffload;
2149 } else {
2150 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2151 }
2152 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002153 } else {
2154 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002155 track->mFillingUpStatus =
2156 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002157 }
2158
Eric Laurent81784c32012-11-19 14:55:58 -08002159 track->mResetDone = false;
2160 track->mPresentationCompleteFrames = 0;
2161 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002162 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2163 if (chain != 0) {
2164 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2165 track->sessionId());
2166 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002167 }
2168
Andy Hung2148bf02016-11-28 19:01:02 -08002169 char buffer[256];
2170 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2171 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2172
Eric Laurent81784c32012-11-19 14:55:58 -08002173 status = NO_ERROR;
2174 }
2175
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002176 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002177 return status;
2178}
2179
Eric Laurentbfb1b832013-01-07 09:53:42 -08002180bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002181{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002182 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002183 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002184 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2185 track->mState = TrackBase::STOPPED;
2186 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002187 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002188 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002189 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002190 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002191
2192 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002193}
2194
2195void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2196{
2197 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002198
2199 char buffer[256];
2200 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2201 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2202
Eric Laurent81784c32012-11-19 14:55:58 -08002203 mTracks.remove(track);
2204 deleteTrackName_l(track->name());
2205 // redundant as track is about to be destroyed, for dumpsys only
2206 track->mName = -1;
2207 if (track->isFastTrack()) {
2208 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002209 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002210 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2211 mFastTrackAvailMask |= 1 << index;
2212 // redundant as track is about to be destroyed, for dumpsys only
2213 track->mFastIndex = -1;
2214 }
2215 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2216 if (chain != 0) {
2217 chain->decTrackCnt();
2218 }
2219}
2220
2221String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2222{
Eric Laurent81784c32012-11-19 14:55:58 -08002223 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002224 String8 out_s8;
2225 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2226 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002227 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002228 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002229}
2230
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002231void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002232 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2233 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002234
Eric Laurent73e26b62015-04-27 16:55:58 -07002235 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002236
2237 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002238 case AUDIO_OUTPUT_OPENED:
2239 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002240 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002241 desc->mChannelMask = mChannelMask;
2242 desc->mSamplingRate = mSampleRate;
2243 desc->mFormat = mFormat;
2244 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002245 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002246 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002247 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002248 break;
2249
Eric Laurent73e26b62015-04-27 16:55:58 -07002250 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002251 default:
2252 break;
2253 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002254 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002255}
2256
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002257void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002258{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002259 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002260}
2261
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002262void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002263{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002264 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002265}
2266
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002267void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002268{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002269 mCallbackThread->setAsyncError();
2270}
2271
Eric Laurent3b4529e2013-09-05 18:09:19 -07002272void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273{
2274 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002275 // reject out of sequence requests
2276 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2277 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278 mWaitWorkCV.signal();
2279 }
2280}
2281
Eric Laurent3b4529e2013-09-05 18:09:19 -07002282void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002283{
2284 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002285 // reject out of sequence requests
2286 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2287 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288 mWaitWorkCV.signal();
2289 }
2290}
2291
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002292void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002293{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002294 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002295 mSampleRate = mOutput->getSampleRate();
2296 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002297 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002298 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002299 }
Andy Hung9a592762014-07-21 21:56:01 -07002300 if ((mType == MIXER || mType == DUPLICATING)
2301 && !isValidPcmSinkChannelMask(mChannelMask)) {
2302 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2303 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002304 }
Andy Hunge5412692014-05-16 11:25:07 -07002305 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002306
2307 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002308 status_t result = mOutput->stream->getFormat(&mHALFormat);
2309 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002310 // Get format from the shim, which will be different than the HAL format
2311 // if playing compressed audio over HDMI passthrough.
2312 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002313 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002314 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002315 }
Andy Hung6146c082014-03-18 11:56:15 -07002316 if ((mType == MIXER || mType == DUPLICATING)
2317 && !isValidPcmSinkFormat(mFormat)) {
2318 LOG_FATAL("HAL format %#x not supported for mixed output",
2319 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002320 }
Phil Burk062e67a2015-02-11 13:40:50 -08002321 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002322 result = mOutput->stream->getBufferSize(&mBufferSize);
2323 LOG_ALWAYS_FATAL_IF(result != OK,
2324 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002325 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002326 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002327 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002328 mFrameCount);
2329 }
2330
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002331 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2332 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002333 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002334 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002335 }
2336 }
2337
Eric Laurentd1f69b02014-12-15 14:33:13 -08002338 mHwSupportsPause = false;
2339 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002340 bool supportsPause = false, supportsResume = false;
2341 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2342 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002343 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002344 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002345 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002346 } else if (supportsResume) {
2347 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002348 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002349 }
2350 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002351 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2352 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2353 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002354
Andy Hungfbfc3952015-01-15 13:33:51 -08002355 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2356 // For best precision, we use float instead of the associated output
2357 // device format (typically PCM 16 bit).
2358
2359 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2360 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2361 mBufferSize = mFrameSize * mFrameCount;
2362
2363 // TODO: We currently use the associated output device channel mask and sample rate.
2364 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2365 // (if a valid mask) to avoid premature downmix.
2366 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2367 // instead of the output device sample rate to avoid loss of high frequency information.
2368 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2369 }
2370
Andy Hung09a50072014-02-27 14:30:47 -08002371 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002372 double multiplier = 1.0;
2373 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2374 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002375 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2376 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002377
Eric Laurent81784c32012-11-19 14:55:58 -08002378 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2379 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2380 maxNormalFrameCount = maxNormalFrameCount & ~15;
2381 if (maxNormalFrameCount < minNormalFrameCount) {
2382 maxNormalFrameCount = minNormalFrameCount;
2383 }
2384 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2385 if (multiplier <= 1.0) {
2386 multiplier = 1.0;
2387 } else if (multiplier <= 2.0) {
2388 if (2 * mFrameCount <= maxNormalFrameCount) {
2389 multiplier = 2.0;
2390 } else {
2391 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2392 }
2393 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002394 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002395 }
2396 }
2397 mNormalFrameCount = multiplier * mFrameCount;
2398 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002399 if (mType == MIXER || mType == DUPLICATING) {
2400 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2401 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002402 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002403 mNormalFrameCount);
2404
Andy Hung08fb1742015-05-31 23:22:10 -07002405 // Check if we want to throttle the processing to no more than 2x normal rate
2406 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002407 mThreadThrottleTimeMs = 0;
2408 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002409 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2410
Andy Hung010a1a12014-03-13 13:57:33 -07002411 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2412 // Originally this was int16_t[] array, need to remove legacy implications.
2413 free(mSinkBuffer);
2414 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002415 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2416 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2417 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002418 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002419
Andy Hung69aed5f2014-02-25 17:24:40 -08002420 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2421 // drives the output.
2422 free(mMixerBuffer);
2423 mMixerBuffer = NULL;
2424 if (mMixerBufferEnabled) {
2425 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2426 mMixerBufferSize = mNormalFrameCount * mChannelCount
2427 * audio_bytes_per_sample(mMixerBufferFormat);
2428 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2429 }
Andy Hung98ef9782014-03-04 14:46:50 -08002430 free(mEffectBuffer);
2431 mEffectBuffer = NULL;
2432 if (mEffectBufferEnabled) {
2433 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2434 mEffectBufferSize = mNormalFrameCount * mChannelCount
2435 * audio_bytes_per_sample(mEffectBufferFormat);
2436 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2437 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002438
Eric Laurent81784c32012-11-19 14:55:58 -08002439 // force reconfiguration of effect chains and engines to take new buffer size and audio
2440 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002441 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002442 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2443 // matter.
2444 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2445 Vector< sp<EffectChain> > effectChains = mEffectChains;
2446 for (size_t i = 0; i < effectChains.size(); i ++) {
2447 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2448 }
2449}
2450
2451
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002452status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002453{
2454 if (halFrames == NULL || dspFrames == NULL) {
2455 return BAD_VALUE;
2456 }
2457 Mutex::Autolock _l(mLock);
2458 if (initCheck() != NO_ERROR) {
2459 return INVALID_OPERATION;
2460 }
Andy Hung818e7a32016-02-16 18:08:07 -08002461 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002462 *halFrames = framesWritten;
2463
2464 if (isSuspended()) {
2465 // return an estimation of rendered frames when the output is suspended
2466 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002467 *dspFrames = (uint32_t)
2468 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002469 return NO_ERROR;
2470 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002471 status_t status;
2472 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002473 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002474 *dspFrames = (size_t)frames;
2475 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002476 }
2477}
2478
Eric Laurent4c415062016-06-17 16:14:16 -07002479// hasAudioSession_l() must be called with ThreadBase::mLock held
2480uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002481{
Eric Laurent81784c32012-11-19 14:55:58 -08002482 uint32_t result = 0;
2483 if (getEffectChain_l(sessionId) != 0) {
2484 result = EFFECT_SESSION;
2485 }
2486
2487 for (size_t i = 0; i < mTracks.size(); ++i) {
2488 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002489 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002490 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002491 if (track->isFastTrack()) {
2492 result |= FAST_SESSION;
2493 }
Eric Laurent81784c32012-11-19 14:55:58 -08002494 break;
2495 }
2496 }
2497
2498 return result;
2499}
2500
Glenn Kastend848eb42016-03-08 13:42:11 -08002501uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002502{
2503 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2504 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2505 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2506 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2507 }
2508 for (size_t i = 0; i < mTracks.size(); i++) {
2509 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002510 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002511 return AudioSystem::getStrategyForStream(track->streamType());
2512 }
2513 }
2514 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2515}
2516
2517
Phil Burk062e67a2015-02-11 13:40:50 -08002518AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002519{
2520 Mutex::Autolock _l(mLock);
2521 return mOutput;
2522}
2523
Phil Burk062e67a2015-02-11 13:40:50 -08002524AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002525{
2526 Mutex::Autolock _l(mLock);
2527 AudioStreamOut *output = mOutput;
2528 mOutput = NULL;
2529 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2530 // must push a NULL and wait for ack
2531 mOutputSink.clear();
2532 mPipeSink.clear();
2533 mNormalSink.clear();
2534 return output;
2535}
2536
2537// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002538sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002539{
2540 if (mOutput == NULL) {
2541 return NULL;
2542 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002543 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002544}
2545
2546uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2547{
2548 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2549}
2550
2551status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2552{
2553 if (!isValidSyncEvent(event)) {
2554 return BAD_VALUE;
2555 }
2556
2557 Mutex::Autolock _l(mLock);
2558
2559 for (size_t i = 0; i < mTracks.size(); ++i) {
2560 sp<Track> track = mTracks[i];
2561 if (event->triggerSession() == track->sessionId()) {
2562 (void) track->setSyncEvent(event);
2563 return NO_ERROR;
2564 }
2565 }
2566
2567 return NAME_NOT_FOUND;
2568}
2569
2570bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2571{
2572 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2573}
2574
2575void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2576 const Vector< sp<Track> >& tracksToRemove)
2577{
2578 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002579 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002580 for (size_t i = 0 ; i < count ; i++) {
2581 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002582 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002583 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002584 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585#ifdef ADD_BATTERY_DATA
2586 // to track the speaker usage
2587 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2588#endif
2589 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002590 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002591 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002592 }
Eric Laurent81784c32012-11-19 14:55:58 -08002593 }
2594 }
2595 }
Eric Laurent81784c32012-11-19 14:55:58 -08002596}
2597
2598void AudioFlinger::PlaybackThread::checkSilentMode_l()
2599{
2600 if (!mMasterMute) {
2601 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002602 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2603 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2604 return;
2605 }
Eric Laurent81784c32012-11-19 14:55:58 -08002606 if (property_get("ro.audio.silent", value, "0") > 0) {
2607 char *endptr;
2608 unsigned long ul = strtoul(value, &endptr, 0);
2609 if (*endptr == '\0' && ul != 0) {
2610 ALOGD("Silence is golden");
2611 // The setprop command will not allow a property to be changed after
2612 // the first time it is set, so we don't have to worry about un-muting.
2613 setMasterMute_l(true);
2614 }
2615 }
2616 }
2617}
2618
2619// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002620ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002621{
Eric Laurent81784c32012-11-19 14:55:58 -08002622 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002623 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002624 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002625
2626 // If an NBAIO sink is present, use it to write the normal mixer's submix
2627 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002628
Andy Hung010a1a12014-03-13 13:57:33 -07002629 const size_t count = mBytesRemaining / mFrameSize;
2630
Simon Wilson2d590962012-11-29 15:18:50 -08002631 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002632 // update the setpoint when AudioFlinger::mScreenState changes
2633 uint32_t screenState = AudioFlinger::mScreenState;
2634 if (screenState != mScreenState) {
2635 mScreenState = screenState;
2636 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2637 if (pipe != NULL) {
2638 pipe->setAvgFrames((mScreenState & 1) ?
2639 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2640 }
2641 }
Andy Hung010a1a12014-03-13 13:57:33 -07002642 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002643 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002644 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002645 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002646 } else {
2647 bytesWritten = framesWritten;
2648 }
2649 // otherwise use the HAL / AudioStreamOut directly
2650 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002652
Eric Laurentbfb1b832013-01-07 09:53:42 -08002653 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002654 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2655 mWriteAckSequence += 2;
2656 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002658 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002660 // FIXME We should have an implementation of timestamps for direct output threads.
2661 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002662 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002663
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 if (mUseAsyncWrite &&
2665 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2666 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002667 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002668 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002669 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002670 }
Eric Laurent81784c32012-11-19 14:55:58 -08002671 }
2672
Eric Laurent81784c32012-11-19 14:55:58 -08002673 mNumWrites++;
2674 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002675 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002676 return bytesWritten;
2677}
2678
2679void AudioFlinger::PlaybackThread::threadLoop_drain()
2680{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002681 bool supportsDrain = false;
2682 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002683 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2684 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002685 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2686 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002688 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002689 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002690 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002691 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002692 }
2693}
2694
2695void AudioFlinger::PlaybackThread::threadLoop_exit()
2696{
Eric Laurent275e8e92014-11-30 15:14:47 -08002697 {
2698 Mutex::Autolock _l(mLock);
2699 for (size_t i = 0; i < mTracks.size(); i++) {
2700 sp<Track> track = mTracks[i];
2701 track->invalidate();
2702 }
Andy Hungdae27702016-10-31 14:01:16 -07002703 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2704 // After we exit there are no more track changes sent to BatteryNotifier
2705 // because that requires an active threadLoop.
2706 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2707 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002708 }
Eric Laurent81784c32012-11-19 14:55:58 -08002709}
2710
2711/*
2712The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002713 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002714 - mActiveSleepTimeUs from activeSleepTimeUs()
2715 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002716 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2717 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002718 - maxPeriod from frame count and sample rate (MIXER only)
2719
2720The parameters that affect these derived values are:
2721 - frame count
2722 - frame size
2723 - sample rate
2724 - device type: A2DP or not
2725 - device latency
2726 - format: PCM or not
2727 - active sleep time
2728 - idle sleep time
2729*/
2730
2731void AudioFlinger::PlaybackThread::cacheParameters_l()
2732{
Andy Hung25c2dac2014-02-27 14:56:00 -08002733 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002734 mActiveSleepTimeUs = activeSleepTimeUs();
2735 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002736
2737 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2738 // truncating audio when going to standby.
2739 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2740 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2741 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2742 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2743 }
2744 }
Eric Laurent81784c32012-11-19 14:55:58 -08002745}
2746
Eric Laurent13084622016-05-17 10:51:49 -07002747bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002748{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002749 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002750 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002751 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002752 size_t size = mTracks.size();
2753 for (size_t i = 0; i < size; i++) {
2754 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002755 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002756 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002757 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002758 }
2759 }
Eric Laurent13084622016-05-17 10:51:49 -07002760 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002761}
2762
Haynes Mathew George05317d22016-05-03 16:34:26 -07002763void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2764{
2765 Mutex::Autolock _l(mLock);
2766 invalidateTracks_l(streamType);
2767}
2768
Eric Laurent81784c32012-11-19 14:55:58 -08002769status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2770{
Glenn Kastend848eb42016-03-08 13:42:11 -08002771 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002772 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2773 status_t result = EffectBufferHalInterface::mirror(
2774 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2775 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2776 &halInBuffer);
2777 if (result != OK) return result;
2778 halOutBuffer = halInBuffer;
2779 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002780
2781 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002782 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002783 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002784 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002785 if (mType != DIRECT) {
2786 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002787 status_t result = EffectBufferHalInterface::allocate(
2788 numSamples * sizeof(int16_t),
2789 &halInBuffer);
2790 if (result != OK) return result;
2791 buffer = halInBuffer->audioBuffer()->s16;
2792 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2793 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002794 }
2795
2796 // Attach all tracks with same session ID to this chain.
2797 for (size_t i = 0; i < mTracks.size(); ++i) {
2798 sp<Track> track = mTracks[i];
2799 if (session == track->sessionId()) {
2800 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2801 buffer);
2802 track->setMainBuffer(buffer);
2803 chain->incTrackCnt();
2804 }
2805 }
2806
2807 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002808 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002809 if (session == track->sessionId()) {
2810 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2811 chain->incActiveTrackCnt();
2812 }
2813 }
2814 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002815 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002816 chain->setInBuffer(halInBuffer);
2817 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002818 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002819 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002820 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2821 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002822 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002823 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002824 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002825 // Effect chain for other sessions are inserted at beginning of effect
2826 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002827 // sessions is not important.
2828 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2829 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2830 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002831 size_t size = mEffectChains.size();
2832 size_t i = 0;
2833 for (i = 0; i < size; i++) {
2834 if (mEffectChains[i]->sessionId() < session) {
2835 break;
2836 }
2837 }
2838 mEffectChains.insertAt(chain, i);
2839 checkSuspendOnAddEffectChain_l(chain);
2840
2841 return NO_ERROR;
2842}
2843
2844size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2845{
Glenn Kastend848eb42016-03-08 13:42:11 -08002846 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002847
2848 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2849
2850 for (size_t i = 0; i < mEffectChains.size(); i++) {
2851 if (chain == mEffectChains[i]) {
2852 mEffectChains.removeAt(i);
2853 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002854 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002855 if (session == track->sessionId()) {
2856 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2857 chain.get(), session);
2858 chain->decActiveTrackCnt();
2859 }
2860 }
2861
2862 // detach all tracks with same session ID from this chain
2863 for (size_t i = 0; i < mTracks.size(); ++i) {
2864 sp<Track> track = mTracks[i];
2865 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002866 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002867 chain->decTrackCnt();
2868 }
2869 }
2870 break;
2871 }
2872 }
2873 return mEffectChains.size();
2874}
2875
2876status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002877 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002878{
2879 Mutex::Autolock _l(mLock);
2880 return attachAuxEffect_l(track, EffectId);
2881}
2882
2883status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002884 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002885{
2886 status_t status = NO_ERROR;
2887
2888 if (EffectId == 0) {
2889 track->setAuxBuffer(0, NULL);
2890 } else {
2891 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2892 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2893 if (effect != 0) {
2894 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2895 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2896 } else {
2897 status = INVALID_OPERATION;
2898 }
2899 } else {
2900 status = BAD_VALUE;
2901 }
2902 }
2903 return status;
2904}
2905
2906void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2907{
2908 for (size_t i = 0; i < mTracks.size(); ++i) {
2909 sp<Track> track = mTracks[i];
2910 if (track->auxEffectId() == effectId) {
2911 attachAuxEffect_l(track, 0);
2912 }
2913 }
2914}
2915
2916bool AudioFlinger::PlaybackThread::threadLoop()
2917{
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002918 logWriterTLS = mNBLogWriter.get();
2919
Eric Laurent81784c32012-11-19 14:55:58 -08002920 Vector< sp<Track> > tracksToRemove;
2921
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002922 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002923 nsecs_t lastWriteFinished = -1; // time last server write completed
2924 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002925
2926 // MIXER
2927 nsecs_t lastWarning = 0;
2928
2929 // DUPLICATING
2930 // FIXME could this be made local to while loop?
2931 writeFrames = 0;
2932
2933 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002934 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002935
2936 if (mType == MIXER) {
2937 sleepTimeShift = 0;
2938 }
2939
2940 CpuStats cpuStats;
2941 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2942
2943 acquireWakeLock();
2944
Glenn Kasten9e58b552013-01-18 15:09:48 -08002945 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2946 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2947 // and then that string will be logged at the next convenient opportunity.
2948 const char *logString = NULL;
2949
Eric Laurent664539d2013-09-23 18:24:31 -07002950 checkSilentMode_l();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002951#if 0
2952 int z = 0; // used in logFormat example
2953#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002954 while (!exitPending())
2955 {
2956 cpuStats.sample(myName);
2957
2958 Vector< sp<EffectChain> > effectChains;
2959
Eric Laurent81784c32012-11-19 14:55:58 -08002960 { // scope for mLock
2961
2962 Mutex::Autolock _l(mLock);
2963
Eric Laurent021cf962014-05-13 10:18:14 -07002964 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002965
Glenn Kasten9e58b552013-01-18 15:09:48 -08002966 if (logString != NULL) {
2967 mNBLogWriter->logTimestamp();
2968 mNBLogWriter->log(logString);
2969 logString = NULL;
2970 }
2971
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002972 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002973 // and associate with the sink frames written out. We need
2974 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002975 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002976 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002977 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002978 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002979 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002980 ExtendedTimestamp timestamp; // use private copy to fetch
2981 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002982
2983 // We keep track of the last valid kernel position in case we are in underrun
2984 // and the normal mixer period is the same as the fast mixer period, or there
2985 // is some error from the HAL.
2986 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2987 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2988 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2989 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2990 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2991
2992 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2993 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2994 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2995 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002996 }
2997
2998 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2999 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003000 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003001 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003002 }
3003
Andy Hung818e7a32016-02-16 18:08:07 -08003004 // copy over kernel info
3005 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003006 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3007 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003008 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3009 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003010 }
3011 // mFramesWritten for non-offloaded tracks are contiguous
3012 // even after standby() is called. This is useful for the track frame
3013 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003014 bool serverLocationUpdate = false;
3015 if (mFramesWritten != lastFramesWritten) {
3016 serverLocationUpdate = true;
3017 lastFramesWritten = mFramesWritten;
3018 }
3019 // Only update timestamps if there is a meaningful change.
3020 // Either the kernel timestamp must be valid or we have written something.
3021 if (kernelLocationUpdate || serverLocationUpdate) {
3022 if (serverLocationUpdate) {
3023 // use the time before we called the HAL write - it is a bit more accurate
3024 // to when the server last read data than the current time here.
3025 //
3026 // If we haven't written anything, mLastWriteTime will be -1
3027 // and we use systemTime().
3028 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3029 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3030 ? systemTime() : mLastWriteTime;
3031 }
Andy Hungdae27702016-10-31 14:01:16 -07003032
3033 for (const sp<Track> &t : mActiveTracks) {
3034 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003035 t->updateTrackFrameInfo(
3036 t->mAudioTrackServerProxy->framesReleased(),
3037 mFramesWritten,
3038 mTimestamp);
3039 }
Andy Hunge10393e2015-06-12 13:59:33 -07003040 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003041 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003042#if 0
3043 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003044 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003045 timespec ts;
3046 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003047 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003048 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003049 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003050 }
3051 ++z;
3052#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003053 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003054 if (mSignalPending) {
3055 // A signal was raised while we were unlocked
3056 mSignalPending = false;
3057 } else if (waitingAsyncCallback_l()) {
3058 if (exitPending()) {
3059 break;
3060 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003061 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003062 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003063 releaseWakeLock_l();
3064 released = true;
3065 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003066 ALOGV("wait async completion");
3067 mWaitWorkCV.wait(mLock);
3068 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003069 if (released) {
3070 acquireWakeLock_l();
3071 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003072 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3073 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003074
3075 continue;
3076 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003077 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003078 isSuspended()) {
3079 // put audio hardware into standby after short delay
3080 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003081
3082 threadLoop_standby();
3083
3084 mStandby = true;
3085 }
3086
3087 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3088 // we're about to wait, flush the binder command buffer
3089 IPCThreadState::self()->flushCommands();
3090
3091 clearOutputTracks();
3092
3093 if (exitPending()) {
3094 break;
3095 }
3096
3097 releaseWakeLock_l();
3098 // wait until we have something to do...
3099 ALOGV("%s going to sleep", myName.string());
3100 mWaitWorkCV.wait(mLock);
3101 ALOGV("%s waking up", myName.string());
3102 acquireWakeLock_l();
3103
3104 mMixerStatus = MIXER_IDLE;
3105 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3106 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003108 checkSilentMode_l();
3109
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003110 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3111 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003112 if (mType == MIXER) {
3113 sleepTimeShift = 0;
3114 }
3115
3116 continue;
3117 }
3118 }
Eric Laurent81784c32012-11-19 14:55:58 -08003119 // mMixerStatusIgnoringFastTracks is also updated internally
3120 mMixerStatus = prepareTracks_l(&tracksToRemove);
3121
Andy Hungdae27702016-10-31 14:01:16 -07003122 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003123
Eric Laurent81784c32012-11-19 14:55:58 -08003124 // prevent any changes in effect chain list and in each effect chain
3125 // during mixing and effect process as the audio buffers could be deleted
3126 // or modified if an effect is created or deleted
3127 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003128 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003129
Eric Laurentbfb1b832013-01-07 09:53:42 -08003130 if (mBytesRemaining == 0) {
3131 mCurrentWriteLength = 0;
3132 if (mMixerStatus == MIXER_TRACKS_READY) {
3133 // threadLoop_mix() sets mCurrentWriteLength
3134 threadLoop_mix();
3135 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3136 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003137 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003138 // must be written to HAL
3139 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003140 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003141 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003142 }
3143 }
Andy Hung98ef9782014-03-04 14:46:50 -08003144 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003145 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003146 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3147 // or mSinkBuffer (if there are no effects).
3148 //
3149 // This is done pre-effects computation; if effects change to
3150 // support higher precision, this needs to move.
3151 //
3152 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003153 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003154 if (mMixerBufferValid) {
3155 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3156 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3157
Andy Hung2ddee192015-12-18 17:34:44 -08003158 // mono blend occurs for mixer threads only (not direct or offloaded)
3159 // and is handled here if we're going directly to the sink.
3160 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003161 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3162 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003163 }
3164
Andy Hung98ef9782014-03-04 14:46:50 -08003165 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3166 mNormalFrameCount * mChannelCount);
3167 }
3168
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169 mBytesRemaining = mCurrentWriteLength;
3170 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003171 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3172 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3173 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3174 mBytesWritten += mBytesRemaining;
3175 mFramesWritten += framesRemaining;
3176 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003177 mBytesRemaining = 0;
3178 }
Eric Laurent81784c32012-11-19 14:55:58 -08003179
Eric Laurentbfb1b832013-01-07 09:53:42 -08003180 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003181 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003182 for (size_t i = 0; i < effectChains.size(); i ++) {
3183 effectChains[i]->process_l();
3184 }
Eric Laurent81784c32012-11-19 14:55:58 -08003185 }
3186 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003187 // Process effect chains for offloaded thread even if no audio
3188 // was read from audio track: process only updates effect state
3189 // and thus does have to be synchronized with audio writes but may have
3190 // to be called while waiting for async write callback
3191 if (mType == OFFLOAD) {
3192 for (size_t i = 0; i < effectChains.size(); i ++) {
3193 effectChains[i]->process_l();
3194 }
3195 }
Eric Laurent81784c32012-11-19 14:55:58 -08003196
Andy Hung98ef9782014-03-04 14:46:50 -08003197 // Only if the Effects buffer is enabled and there is data in the
3198 // Effects buffer (buffer valid), we need to
3199 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003200 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003201 if (mEffectBufferValid) {
3202 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003203
3204 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003205 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3206 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003207 }
3208
Andy Hung98ef9782014-03-04 14:46:50 -08003209 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3210 mNormalFrameCount * mChannelCount);
3211 }
3212
Eric Laurent81784c32012-11-19 14:55:58 -08003213 // enable changes in effect chain
3214 unlockEffectChains(effectChains);
3215
Eric Laurentbfb1b832013-01-07 09:53:42 -08003216 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003217 // mSleepTimeUs == 0 means we must write to audio hardware
3218 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003219 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003220 // We save lastWriteFinished here, as previousLastWriteFinished,
3221 // for throttling. On thread start, previousLastWriteFinished will be
3222 // set to -1, which properly results in no throttling after the first write.
3223 nsecs_t previousLastWriteFinished = lastWriteFinished;
3224 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003225 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003226 // FIXME rewrite to reduce number of system calls
3227 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003228 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003229 lastWriteFinished = systemTime();
3230 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003231 if (ret < 0) {
3232 mBytesRemaining = 0;
3233 } else {
3234 mBytesWritten += ret;
3235 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003236 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003237 }
3238 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3239 (mMixerStatus == MIXER_DRAIN_ALL)) {
3240 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003241 }
Andy Hung08fb1742015-05-31 23:22:10 -07003242 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003243 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003244 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003245 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003246 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003247 ATRACE_NAME("underrun");
3248 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003249 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003250 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003251 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003252 }
Andy Hung08fb1742015-05-31 23:22:10 -07003253
3254 if (mThreadThrottle
3255 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3256 && ret > 0) { // we wrote something
3257 // Limit MixerThread data processing to no more than twice the
3258 // expected processing rate.
3259 //
3260 // This helps prevent underruns with NuPlayer and other applications
3261 // which may set up buffers that are close to the minimum size, or use
3262 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3263 //
3264 // The throttle smooths out sudden large data drains from the device,
3265 // e.g. when it comes out of standby, which often causes problems with
3266 // (1) mixer threads without a fast mixer (which has its own warm-up)
3267 // (2) minimum buffer sized tracks (even if the track is full,
3268 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003269 //
3270 // Total time spent in last processing cycle equals time spent in
3271 // 1. threadLoop_write, as well as time spent in
3272 // 2. threadLoop_mix (significant for heavy mixing, especially
3273 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003274
Andy Hung69488c42016-05-16 18:43:33 -07003275 // it's OK if deltaMs is an overestimate.
3276 const int32_t deltaMs =
3277 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003278 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3279 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3280 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003281 // notify of throttle start on verbose log
3282 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3283 "mixer(%p) throttle begin:"
3284 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003285 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003286 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003287 // Throttle must be attributed to the previous mixer loop's write time
3288 // to allow back-to-back throttling.
3289 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003290 } else {
3291 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3292 if (diff > 0) {
3293 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003294 // but prevent spamming for bluetooth
3295 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3296 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003297 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3298 }
Andy Hung08fb1742015-05-31 23:22:10 -07003299 }
3300 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003301 }
Eric Laurent81784c32012-11-19 14:55:58 -08003302
Eric Laurentbfb1b832013-01-07 09:53:42 -08003303 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003304 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003305 Mutex::Autolock _l(mLock);
3306 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3307 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003308 }
Glenn Kastene7754022014-10-31 12:11:26 -07003309 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003310 }
Eric Laurent81784c32012-11-19 14:55:58 -08003311 }
3312
3313 // Finally let go of removed track(s), without the lock held
3314 // since we can't guarantee the destructors won't acquire that
3315 // same lock. This will also mutate and push a new fast mixer state.
3316 threadLoop_removeTracks(tracksToRemove);
3317 tracksToRemove.clear();
3318
3319 // FIXME I don't understand the need for this here;
3320 // it was in the original code but maybe the
3321 // assignment in saveOutputTracks() makes this unnecessary?
3322 clearOutputTracks();
3323
3324 // Effect chains will be actually deleted here if they were removed from
3325 // mEffectChains list during mixing or effects processing
3326 effectChains.clear();
3327
3328 // FIXME Note that the above .clear() is no longer necessary since effectChains
3329 // is now local to this block, but will keep it for now (at least until merge done).
3330 }
3331
Eric Laurentbfb1b832013-01-07 09:53:42 -08003332 threadLoop_exit();
3333
Eric Laurentcf817a22014-08-04 20:36:31 -07003334 if (!mStandby) {
3335 threadLoop_standby();
3336 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003337 }
3338
3339 releaseWakeLock();
3340
3341 ALOGV("Thread %p type %d exiting", this, mType);
3342 return false;
3343}
3344
Eric Laurentbfb1b832013-01-07 09:53:42 -08003345// removeTracks_l() must be called with ThreadBase::mLock held
3346void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3347{
3348 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003349 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003350 for (size_t i=0 ; i<count ; i++) {
3351 const sp<Track>& track = tracksToRemove.itemAt(i);
3352 mActiveTracks.remove(track);
3353 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3354 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3355 if (chain != 0) {
3356 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3357 track->sessionId());
3358 chain->decActiveTrackCnt();
3359 }
3360 if (track->isTerminated()) {
3361 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003362 } else { // inactive but not terminated
3363 char buffer[256];
3364 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3365 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003366 }
3367 }
3368 }
3369
3370}
Eric Laurent81784c32012-11-19 14:55:58 -08003371
Eric Laurentaccc1472013-09-20 09:36:34 -07003372status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3373{
3374 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003375 ExtendedTimestamp ets;
3376 status_t status = mNormalSink->getTimestamp(ets);
3377 if (status == NO_ERROR) {
3378 status = ets.getBestTimestamp(&timestamp);
3379 }
3380 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003381 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003382 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003383 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003384 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003385 timestamp.mPosition = (uint32_t)position64;
3386 return NO_ERROR;
3387 }
3388 }
3389 return INVALID_OPERATION;
3390}
Eric Laurent1c333e22014-05-20 10:48:17 -07003391
Eric Laurent054d9d32015-04-24 08:48:48 -07003392status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3393 audio_patch_handle_t *handle)
3394{
Andy Hungf60abce2016-08-26 11:37:54 -07003395 status_t status;
3396 if (property_get_bool("af.patch_park", false /* default_value */)) {
3397 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3398 // or if HAL does not properly lock against access.
3399 AutoPark<FastMixer> park(mFastMixer);
3400 status = PlaybackThread::createAudioPatch_l(patch, handle);
3401 } else {
3402 status = PlaybackThread::createAudioPatch_l(patch, handle);
3403 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003404 return status;
3405}
3406
Eric Laurent1c333e22014-05-20 10:48:17 -07003407status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3408 audio_patch_handle_t *handle)
3409{
3410 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003411
3412 // store new device and send to effects
3413 audio_devices_t type = AUDIO_DEVICE_NONE;
3414 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3415 type |= patch->sinks[i].ext.device.type;
3416 }
3417
3418#ifdef ADD_BATTERY_DATA
3419 // when changing the audio output device, call addBatteryData to notify
3420 // the change
3421 if (mOutDevice != type) {
3422 uint32_t params = 0;
3423 // check whether speaker is on
3424 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3425 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003426 }
3427
Eric Laurent054d9d32015-04-24 08:48:48 -07003428 audio_devices_t deviceWithoutSpeaker
3429 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3430 // check if any other device (except speaker) is on
3431 if (type & deviceWithoutSpeaker) {
3432 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3433 }
3434
3435 if (params != 0) {
3436 addBatteryData(params);
3437 }
3438 }
3439#endif
3440
3441 for (size_t i = 0; i < mEffectChains.size(); i++) {
3442 mEffectChains[i]->setDevice_l(type);
3443 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003444
3445 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3446 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3447 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003448 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003449 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003450
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003451 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003452 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3453 status = hwDevice->createAudioPatch(patch->num_sources,
3454 patch->sources,
3455 patch->num_sinks,
3456 patch->sinks,
3457 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003458 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003459 char *address;
3460 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3461 //FIXME: we only support address on first sink with HAL version < 3.0
3462 address = audio_device_address_to_parameter(
3463 patch->sinks[0].ext.device.type,
3464 patch->sinks[0].ext.device.address);
3465 } else {
3466 address = (char *)calloc(1, 1);
3467 }
3468 AudioParameter param = AudioParameter(String8(address));
3469 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003470 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003471 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003472 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003473 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003474 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003475 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003476 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3477 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003478 return status;
3479}
3480
Eric Laurent054d9d32015-04-24 08:48:48 -07003481status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3482{
Andy Hungf60abce2016-08-26 11:37:54 -07003483 status_t status;
3484 if (property_get_bool("af.patch_park", false /* default_value */)) {
3485 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3486 // or if HAL does not properly lock against access.
3487 AutoPark<FastMixer> park(mFastMixer);
3488 status = PlaybackThread::releaseAudioPatch_l(handle);
3489 } else {
3490 status = PlaybackThread::releaseAudioPatch_l(handle);
3491 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003492 return status;
3493}
3494
Eric Laurent1c333e22014-05-20 10:48:17 -07003495status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3496{
3497 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003498
3499 mOutDevice = AUDIO_DEVICE_NONE;
3500
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003501 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003502 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3503 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003504 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003505 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003506 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003507 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003508 }
3509 return status;
3510}
3511
Eric Laurent83b88082014-06-20 18:31:16 -07003512void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3513{
3514 Mutex::Autolock _l(mLock);
3515 mTracks.add(track);
3516}
3517
3518void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3519{
3520 Mutex::Autolock _l(mLock);
3521 destroyTrack_l(track);
3522}
3523
3524void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3525{
3526 ThreadBase::getAudioPortConfig(config);
3527 config->role = AUDIO_PORT_ROLE_SOURCE;
3528 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3529 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3530}
3531
Eric Laurent81784c32012-11-19 14:55:58 -08003532// ----------------------------------------------------------------------------
3533
3534AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003535 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3536 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003537 // mAudioMixer below
3538 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003539 mFastMixerFutex(0),
3540 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003541 // mOutputSink below
3542 // mPipeSink below
3543 // mNormalSink below
3544{
3545 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003546 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3547 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003548 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3549 mNormalFrameCount);
3550 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3551
Andy Hungfbfc3952015-01-15 13:33:51 -08003552 if (type == DUPLICATING) {
3553 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3554 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3555 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3556 return;
3557 }
Eric Laurent81784c32012-11-19 14:55:58 -08003558 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003559 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003560 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003561 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003562#if !LOG_NDEBUG
3563 ssize_t index =
3564#else
3565 (void)
3566#endif
3567 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003568 ALOG_ASSERT(index == 0);
3569
3570 // initialize fast mixer depending on configuration
3571 bool initFastMixer;
3572 switch (kUseFastMixer) {
3573 case FastMixer_Never:
3574 initFastMixer = false;
3575 break;
3576 case FastMixer_Always:
3577 initFastMixer = true;
3578 break;
3579 case FastMixer_Static:
3580 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003581 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3582 // where the period is less than an experimentally determined threshold that can be
3583 // scheduled reliably with CFS. However, the BT A2DP HAL is
3584 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3585 initFastMixer = mFrameCount < mNormalFrameCount
3586 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003587 break;
3588 }
Andy Hungfda69402017-02-15 14:33:12 -08003589 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3590 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3591 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003592 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003593 audio_format_t fastMixerFormat;
3594 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3595 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3596 } else {
3597 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3598 }
3599 if (mFormat != fastMixerFormat) {
3600 // change our Sink format to accept our intermediate precision
3601 mFormat = fastMixerFormat;
3602 free(mSinkBuffer);
3603 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3604 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3605 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3606 }
Eric Laurent81784c32012-11-19 14:55:58 -08003607
3608 // create a MonoPipe to connect our submix to FastMixer
3609 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003610#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003611 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003612#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003613 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003614 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003615 format.mFormat = fastMixerFormat;
3616 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3617
Eric Laurent81784c32012-11-19 14:55:58 -08003618 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3619 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3620 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3621 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3622 const NBAIO_Format offers[1] = {format};
3623 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003624#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003625 ssize_t index =
3626#else
3627 (void)
3628#endif
3629 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003630 ALOG_ASSERT(index == 0);
3631 monoPipe->setAvgFrames((mScreenState & 1) ?
3632 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3633 mPipeSink = monoPipe;
3634
Glenn Kasten46909e72013-02-26 09:20:22 -08003635#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003636 if (mTeeSinkOutputEnabled) {
3637 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003638 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3639 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003640 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003641 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003642 ALOG_ASSERT(index == 0);
3643 mTeeSink = teeSink;
3644 PipeReader *teeSource = new PipeReader(*teeSink);
3645 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003646 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003647 ALOG_ASSERT(index == 0);
3648 mTeeSource = teeSource;
3649 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003650#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003651
3652 // create fast mixer and configure it initially with just one fast track for our submix
3653 mFastMixer = new FastMixer();
3654 FastMixerStateQueue *sq = mFastMixer->sq();
3655#ifdef STATE_QUEUE_DUMP
3656 sq->setObserverDump(&mStateQueueObserverDump);
3657 sq->setMutatorDump(&mStateQueueMutatorDump);
3658#endif
3659 FastMixerState *state = sq->begin();
3660 FastTrack *fastTrack = &state->mFastTracks[0];
3661 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3662 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3663 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003664 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3665 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003666 fastTrack->mGeneration++;
3667 state->mFastTracksGen++;
3668 state->mTrackMask = 1;
3669 // fast mixer will use the HAL output sink
3670 state->mOutputSink = mOutputSink.get();
3671 state->mOutputSinkGen++;
3672 state->mFrameCount = mFrameCount;
3673 state->mCommand = FastMixerState::COLD_IDLE;
3674 // already done in constructor initialization list
3675 //mFastMixerFutex = 0;
3676 state->mColdFutexAddr = &mFastMixerFutex;
3677 state->mColdGen++;
3678 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003679#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003680 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003681#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003682 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3683 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003684 sq->end();
3685 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3686
3687 // start the fast mixer
3688 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3689 pid_t tid = mFastMixer->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08003690 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003691 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003692
3693#ifdef AUDIO_WATCHDOG
3694 // create and start the watchdog
3695 mAudioWatchdog = new AudioWatchdog();
3696 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3697 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3698 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003699 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003700#endif
3701
Eric Laurent81784c32012-11-19 14:55:58 -08003702 }
3703
3704 switch (kUseFastMixer) {
3705 case FastMixer_Never:
3706 case FastMixer_Dynamic:
3707 mNormalSink = mOutputSink;
3708 break;
3709 case FastMixer_Always:
3710 mNormalSink = mPipeSink;
3711 break;
3712 case FastMixer_Static:
3713 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3714 break;
3715 }
3716}
3717
3718AudioFlinger::MixerThread::~MixerThread()
3719{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003720 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003721 FastMixerStateQueue *sq = mFastMixer->sq();
3722 FastMixerState *state = sq->begin();
3723 if (state->mCommand == FastMixerState::COLD_IDLE) {
3724 int32_t old = android_atomic_inc(&mFastMixerFutex);
3725 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003726 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003727 }
3728 }
3729 state->mCommand = FastMixerState::EXIT;
3730 sq->end();
3731 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3732 mFastMixer->join();
3733 // Though the fast mixer thread has exited, it's state queue is still valid.
3734 // We'll use that extract the final state which contains one remaining fast track
3735 // corresponding to our sub-mix.
3736 state = sq->begin();
3737 ALOG_ASSERT(state->mTrackMask == 1);
3738 FastTrack *fastTrack = &state->mFastTracks[0];
3739 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3740 delete fastTrack->mBufferProvider;
3741 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003742 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003743#ifdef AUDIO_WATCHDOG
3744 if (mAudioWatchdog != 0) {
3745 mAudioWatchdog->requestExit();
3746 mAudioWatchdog->requestExitAndWait();
3747 mAudioWatchdog.clear();
3748 }
3749#endif
3750 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003751 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003752 delete mAudioMixer;
3753}
3754
3755
3756uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3757{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003758 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003759 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3760 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3761 }
3762 return latency;
3763}
3764
3765
3766void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3767{
3768 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3769}
3770
Eric Laurentbfb1b832013-01-07 09:53:42 -08003771ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003772{
3773 // FIXME we should only do one push per cycle; confirm this is true
3774 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003775 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003776 FastMixerStateQueue *sq = mFastMixer->sq();
3777 FastMixerState *state = sq->begin();
3778 if (state->mCommand != FastMixerState::MIX_WRITE &&
3779 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3780 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003781
3782 // FIXME workaround for first HAL write being CPU bound on some devices
3783 ATRACE_BEGIN("write");
3784 mOutput->write((char *)mSinkBuffer, 0);
3785 ATRACE_END();
3786
Eric Laurent81784c32012-11-19 14:55:58 -08003787 int32_t old = android_atomic_inc(&mFastMixerFutex);
3788 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003789 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003790 }
3791#ifdef AUDIO_WATCHDOG
3792 if (mAudioWatchdog != 0) {
3793 mAudioWatchdog->resume();
3794 }
3795#endif
3796 }
3797 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003798#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003799 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003800 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003801#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003802 sq->end();
3803 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3804 if (kUseFastMixer == FastMixer_Dynamic) {
3805 mNormalSink = mPipeSink;
3806 }
3807 } else {
3808 sq->end(false /*didModify*/);
3809 }
3810 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003811 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003812}
3813
3814void AudioFlinger::MixerThread::threadLoop_standby()
3815{
3816 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003817 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003818 FastMixerStateQueue *sq = mFastMixer->sq();
3819 FastMixerState *state = sq->begin();
3820 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003821 // Report any frames trapped in the Monopipe
3822 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3823 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3824 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3825 "monoPipeWritten:%lld monoPipeLeft:%lld",
3826 (long long)mFramesWritten, (long long)mSuspendedFrames,
3827 (long long)mPipeSink->framesWritten(), pipeFrames);
3828 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3829
Eric Laurent81784c32012-11-19 14:55:58 -08003830 state->mCommand = FastMixerState::COLD_IDLE;
3831 state->mColdFutexAddr = &mFastMixerFutex;
3832 state->mColdGen++;
3833 mFastMixerFutex = 0;
3834 sq->end();
3835 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3836 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3837 if (kUseFastMixer == FastMixer_Dynamic) {
3838 mNormalSink = mOutputSink;
3839 }
3840#ifdef AUDIO_WATCHDOG
3841 if (mAudioWatchdog != 0) {
3842 mAudioWatchdog->pause();
3843 }
3844#endif
3845 } else {
3846 sq->end(false /*didModify*/);
3847 }
3848 }
3849 PlaybackThread::threadLoop_standby();
3850}
3851
Eric Laurentbfb1b832013-01-07 09:53:42 -08003852bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3853{
3854 return false;
3855}
3856
3857bool AudioFlinger::PlaybackThread::shouldStandby_l()
3858{
3859 return !mStandby;
3860}
3861
3862bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3863{
3864 Mutex::Autolock _l(mLock);
3865 return waitingAsyncCallback_l();
3866}
3867
Eric Laurent81784c32012-11-19 14:55:58 -08003868// shared by MIXER and DIRECT, overridden by DUPLICATING
3869void AudioFlinger::PlaybackThread::threadLoop_standby()
3870{
3871 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003872 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003873 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003874 // discard any pending drain or write ack by incrementing sequence
3875 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3876 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003877 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003878 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3879 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003880 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003881 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003882}
3883
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003884void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3885{
3886 ALOGV("signal playback thread");
3887 broadcast_l();
3888}
3889
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003890void AudioFlinger::PlaybackThread::onAsyncError()
3891{
3892 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3893 invalidateTracks((audio_stream_type_t)i);
3894 }
3895}
3896
Eric Laurent81784c32012-11-19 14:55:58 -08003897void AudioFlinger::MixerThread::threadLoop_mix()
3898{
Eric Laurent81784c32012-11-19 14:55:58 -08003899 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003900 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003901 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003902 // increase sleep time progressively when application underrun condition clears.
3903 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3904 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3905 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003906 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003907 sleepTimeShift--;
3908 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003909 mSleepTimeUs = 0;
3910 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003911 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003912
Eric Laurent81784c32012-11-19 14:55:58 -08003913}
3914
3915void AudioFlinger::MixerThread::threadLoop_sleepTime()
3916{
3917 // If no tracks are ready, sleep once for the duration of an output
3918 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003919 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003920 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003921 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3922 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3923 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003924 }
3925 // reduce sleep time in case of consecutive application underruns to avoid
3926 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3927 // duration we would end up writing less data than needed by the audio HAL if
3928 // the condition persists.
3929 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3930 sleepTimeShift++;
3931 }
3932 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003933 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003934 }
3935 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003936 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3937 // before effects processing or output.
3938 if (mMixerBufferValid) {
3939 memset(mMixerBuffer, 0, mMixerBufferSize);
3940 } else {
3941 memset(mSinkBuffer, 0, mSinkBufferSize);
3942 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003943 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003944 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3945 "anticipated start");
3946 }
3947 // TODO add standby time extension fct of effect tail
3948}
3949
3950// prepareTracks_l() must be called with ThreadBase::mLock held
3951AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3952 Vector< sp<Track> > *tracksToRemove)
3953{
3954
3955 mixer_state mixerStatus = MIXER_IDLE;
3956 // find out which tracks need to be processed
3957 size_t count = mActiveTracks.size();
3958 size_t mixedTracks = 0;
3959 size_t tracksWithEffect = 0;
3960 // counts only _active_ fast tracks
3961 size_t fastTracks = 0;
3962 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3963
3964 float masterVolume = mMasterVolume;
3965 bool masterMute = mMasterMute;
3966
3967 if (masterMute) {
3968 masterVolume = 0;
3969 }
3970 // Delegate master volume control to effect in output mix effect chain if needed
3971 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3972 if (chain != 0) {
3973 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3974 chain->setVolume_l(&v, &v);
3975 masterVolume = (float)((v + (1 << 23)) >> 24);
3976 chain.clear();
3977 }
3978
3979 // prepare a new state to push
3980 FastMixerStateQueue *sq = NULL;
3981 FastMixerState *state = NULL;
3982 bool didModify = false;
3983 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08003984 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003985 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003986 sq = mFastMixer->sq();
3987 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08003988 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08003989 }
3990
Andy Hung69aed5f2014-02-25 17:24:40 -08003991 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003992 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003993
Eric Laurent81784c32012-11-19 14:55:58 -08003994 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07003995 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003996
3997 // this const just means the local variable doesn't change
3998 Track* const track = t.get();
3999
4000 // process fast tracks
4001 if (track->isFastTrack()) {
4002
4003 // It's theoretically possible (though unlikely) for a fast track to be created
4004 // and then removed within the same normal mix cycle. This is not a problem, as
4005 // the track never becomes active so it's fast mixer slot is never touched.
4006 // The converse, of removing an (active) track and then creating a new track
4007 // at the identical fast mixer slot within the same normal mix cycle,
4008 // is impossible because the slot isn't marked available until the end of each cycle.
4009 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004010 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004011 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4012 FastTrack *fastTrack = &state->mFastTracks[j];
4013
4014 // Determine whether the track is currently in underrun condition,
4015 // and whether it had a recent underrun.
4016 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4017 FastTrackUnderruns underruns = ftDump->mUnderruns;
4018 uint32_t recentFull = (underruns.mBitFields.mFull -
4019 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4020 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4021 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4022 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4023 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4024 uint32_t recentUnderruns = recentPartial + recentEmpty;
4025 track->mObservedUnderruns = underruns;
4026 // don't count underruns that occur while stopping or pausing
4027 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004028 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4029 recentUnderruns > 0) {
4030 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4031 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004032 } else {
4033 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004034 }
4035
4036 // This is similar to the state machine for normal tracks,
4037 // with a few modifications for fast tracks.
4038 bool isActive = true;
4039 switch (track->mState) {
4040 case TrackBase::STOPPING_1:
4041 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004042 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004043 track->mState = TrackBase::STOPPING_2;
4044 }
4045 break;
4046 case TrackBase::PAUSING:
4047 // ramp down is not yet implemented
4048 track->setPaused();
4049 break;
4050 case TrackBase::RESUMING:
4051 // ramp up is not yet implemented
4052 track->mState = TrackBase::ACTIVE;
4053 break;
4054 case TrackBase::ACTIVE:
4055 if (recentFull > 0 || recentPartial > 0) {
4056 // track has provided at least some frames recently: reset retry count
4057 track->mRetryCount = kMaxTrackRetries;
4058 }
4059 if (recentUnderruns == 0) {
4060 // no recent underruns: stay active
4061 break;
4062 }
4063 // there has recently been an underrun of some kind
4064 if (track->sharedBuffer() == 0) {
4065 // were any of the recent underruns "empty" (no frames available)?
4066 if (recentEmpty == 0) {
4067 // no, then ignore the partial underruns as they are allowed indefinitely
4068 break;
4069 }
4070 // there has recently been an "empty" underrun: decrement the retry counter
4071 if (--(track->mRetryCount) > 0) {
4072 break;
4073 }
4074 // indicate to client process that the track was disabled because of underrun;
4075 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004076 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004077 // remove from active list, but state remains ACTIVE [confusing but true]
4078 isActive = false;
4079 break;
4080 }
4081 // fall through
4082 case TrackBase::STOPPING_2:
4083 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004084 case TrackBase::STOPPED:
4085 case TrackBase::FLUSHED: // flush() while active
4086 // Check for presentation complete if track is inactive
4087 // We have consumed all the buffers of this track.
4088 // This would be incomplete if we auto-paused on underrun
4089 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004090 uint32_t latency = 0;
4091 status_t result = mOutput->stream->getLatency(&latency);
4092 ALOGE_IF(result != OK,
4093 "Error when retrieving output stream latency: %d", result);
4094 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004095 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004096 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4097 // track stays in active list until presentation is complete
4098 break;
4099 }
4100 }
4101 if (track->isStopping_2()) {
4102 track->mState = TrackBase::STOPPED;
4103 }
4104 if (track->isStopped()) {
4105 // Can't reset directly, as fast mixer is still polling this track
4106 // track->reset();
4107 // So instead mark this track as needing to be reset after push with ack
4108 resetMask |= 1 << i;
4109 }
4110 isActive = false;
4111 break;
4112 case TrackBase::IDLE:
4113 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004114 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004115 }
4116
4117 if (isActive) {
4118 // was it previously inactive?
4119 if (!(state->mTrackMask & (1 << j))) {
4120 ExtendedAudioBufferProvider *eabp = track;
4121 VolumeProvider *vp = track;
4122 fastTrack->mBufferProvider = eabp;
4123 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004124 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004125 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004126 fastTrack->mGeneration++;
4127 state->mTrackMask |= 1 << j;
4128 didModify = true;
4129 // no acknowledgement required for newly active tracks
4130 }
4131 // cache the combined master volume and stream type volume for fast mixer; this
4132 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004133 const float vh = track->getVolumeHandler()->getVolume(
4134 track->mAudioTrackServerProxy->framesReleased());
4135 track->mCachedVolume = masterVolume
4136 * mStreamTypes[track->streamType()].volume
4137 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004138 ++fastTracks;
4139 } else {
4140 // was it previously active?
4141 if (state->mTrackMask & (1 << j)) {
4142 fastTrack->mBufferProvider = NULL;
4143 fastTrack->mGeneration++;
4144 state->mTrackMask &= ~(1 << j);
4145 didModify = true;
4146 // If any fast tracks were removed, we must wait for acknowledgement
4147 // because we're about to decrement the last sp<> on those tracks.
4148 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4149 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004150 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4151 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4152 j, track->mState, state->mTrackMask, recentUnderruns,
4153 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004154 }
4155 tracksToRemove->add(track);
4156 // Avoids a misleading display in dumpsys
4157 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4158 }
4159 continue;
4160 }
4161
4162 { // local variable scope to avoid goto warning
4163
4164 audio_track_cblk_t* cblk = track->cblk();
4165
4166 // The first time a track is added we wait
4167 // for all its buffers to be filled before processing it
4168 int name = track->name();
4169 // make sure that we have enough frames to mix one full buffer.
4170 // enforce this condition only once to enable draining the buffer in case the client
4171 // app does not call stop() and relies on underrun to stop:
4172 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4173 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004174 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004175 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004176 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004177
4178 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004179 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004180 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4181 // add frames already consumed but not yet released by the resampler
4182 // because mAudioTrackServerProxy->framesReady() will include these frames
4183 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4184
Eric Laurent81784c32012-11-19 14:55:58 -08004185 uint32_t minFrames = 1;
4186 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4187 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004188 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004189 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004190
4191 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004192 if (ATRACE_ENABLED()) {
4193 // I wish we had formatted trace names
4194 char traceName[16];
4195 strcpy(traceName, "nRdy");
4196 int name = track->name();
4197 if (AudioMixer::TRACK0 <= name &&
4198 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4199 name -= AudioMixer::TRACK0;
4200 traceName[4] = (name / 10) + '0';
4201 traceName[5] = (name % 10) + '0';
4202 } else {
4203 traceName[4] = '?';
4204 traceName[5] = '?';
4205 }
4206 traceName[6] = '\0';
4207 ATRACE_INT(traceName, framesReady);
4208 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004209 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004210 !track->isPaused() && !track->isTerminated())
4211 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004212 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004213
4214 mixedTracks++;
4215
Andy Hung69aed5f2014-02-25 17:24:40 -08004216 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4217 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004218 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004219 if (track->mainBuffer() != mSinkBuffer &&
4220 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004221 if (mEffectBufferEnabled) {
4222 mEffectBufferValid = true; // Later can set directly.
4223 }
Eric Laurent81784c32012-11-19 14:55:58 -08004224 chain = getEffectChain_l(track->sessionId());
4225 // Delegate volume control to effect in track effect chain if needed
4226 if (chain != 0) {
4227 tracksWithEffect++;
4228 } else {
4229 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4230 "session %d",
4231 name, track->sessionId());
4232 }
4233 }
4234
4235
4236 int param = AudioMixer::VOLUME;
4237 if (track->mFillingUpStatus == Track::FS_FILLED) {
4238 // no ramp for the first volume setting
4239 track->mFillingUpStatus = Track::FS_ACTIVE;
4240 if (track->mState == TrackBase::RESUMING) {
4241 track->mState = TrackBase::ACTIVE;
4242 param = AudioMixer::RAMP_VOLUME;
4243 }
4244 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004245 // FIXME should not make a decision based on mServer
4246 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004247 // If the track is stopped before the first frame was mixed,
4248 // do not apply ramp
4249 param = AudioMixer::RAMP_VOLUME;
4250 }
4251
4252 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004253 uint32_t vl, vr; // in U8.24 integer format
4254 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004255 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004256 vl = vr = 0;
4257 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004258 if (track->isPausing()) {
4259 track->setPaused();
4260 }
4261 } else {
4262
4263 // read original volumes with volume control
4264 float typeVolume = mStreamTypes[track->streamType()].volume;
4265 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004266 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004267 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004268 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4269 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004270 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004271 if (vlf > GAIN_FLOAT_UNITY) {
4272 ALOGV("Track left volume out of range: %.3g", vlf);
4273 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004274 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004275 if (vrf > GAIN_FLOAT_UNITY) {
4276 ALOGV("Track right volume out of range: %.3g", vrf);
4277 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004278 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004279 const float vh = track->getVolumeHandler()->getVolume(
4280 track->mAudioTrackServerProxy->framesReleased());
4281 // now apply the master volume and stream type volume and shaper volume
4282 vlf *= v * vh;
4283 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004284 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004285 // then derive vl and vr as U8.24 versions for the effect chain
4286 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4287 vl = (uint32_t) (scaleto8_24 * vlf);
4288 vr = (uint32_t) (scaleto8_24 * vrf);
4289 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004290 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004291 // send level comes from shared memory and so may be corrupt
4292 if (sendLevel > MAX_GAIN_INT) {
4293 ALOGV("Track send level out of range: %04X", sendLevel);
4294 sendLevel = MAX_GAIN_INT;
4295 }
Andy Hung6be49402014-05-30 10:42:03 -07004296 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4297 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004298 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004299
Eric Laurent81784c32012-11-19 14:55:58 -08004300 // Delegate volume control to effect in track effect chain if needed
4301 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4302 // Do not ramp volume if volume is controlled by effect
4303 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004304 // Update remaining floating point volume levels
4305 vlf = (float)vl / (1 << 24);
4306 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004307 track->mHasVolumeController = true;
4308 } else {
4309 // force no volume ramp when volume controller was just disabled or removed
4310 // from effect chain to avoid volume spike
4311 if (track->mHasVolumeController) {
4312 param = AudioMixer::VOLUME;
4313 }
4314 track->mHasVolumeController = false;
4315 }
4316
Eric Laurent81784c32012-11-19 14:55:58 -08004317 // XXX: these things DON'T need to be done each time
4318 mAudioMixer->setBufferProvider(name, track);
4319 mAudioMixer->enable(name);
4320
Andy Hung6be49402014-05-30 10:42:03 -07004321 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4322 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4323 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004324 mAudioMixer->setParameter(
4325 name,
4326 AudioMixer::TRACK,
4327 AudioMixer::FORMAT, (void *)track->format());
4328 mAudioMixer->setParameter(
4329 name,
4330 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004331 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004332 mAudioMixer->setParameter(
4333 name,
4334 AudioMixer::TRACK,
4335 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004336 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004337 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004338 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004339 if (reqSampleRate == 0) {
4340 reqSampleRate = mSampleRate;
4341 } else if (reqSampleRate > maxSampleRate) {
4342 reqSampleRate = maxSampleRate;
4343 }
Eric Laurent81784c32012-11-19 14:55:58 -08004344 mAudioMixer->setParameter(
4345 name,
4346 AudioMixer::RESAMPLE,
4347 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004348 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004349
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004350 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004351 mAudioMixer->setParameter(
4352 name,
4353 AudioMixer::TIMESTRETCH,
4354 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004355 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004356
Andy Hung69aed5f2014-02-25 17:24:40 -08004357 /*
4358 * Select the appropriate output buffer for the track.
4359 *
Andy Hung98ef9782014-03-04 14:46:50 -08004360 * Tracks with effects go into their own effects chain buffer
4361 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004362 *
4363 * Other tracks can use mMixerBuffer for higher precision
4364 * channel accumulation. If this buffer is enabled
4365 * (mMixerBufferEnabled true), then selected tracks will accumulate
4366 * into it.
4367 *
4368 */
4369 if (mMixerBufferEnabled
4370 && (track->mainBuffer() == mSinkBuffer
4371 || track->mainBuffer() == mMixerBuffer)) {
4372 mAudioMixer->setParameter(
4373 name,
4374 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004375 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004376 mAudioMixer->setParameter(
4377 name,
4378 AudioMixer::TRACK,
4379 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4380 // TODO: override track->mainBuffer()?
4381 mMixerBufferValid = true;
4382 } else {
4383 mAudioMixer->setParameter(
4384 name,
4385 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004386 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004387 mAudioMixer->setParameter(
4388 name,
4389 AudioMixer::TRACK,
4390 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4391 }
Eric Laurent81784c32012-11-19 14:55:58 -08004392 mAudioMixer->setParameter(
4393 name,
4394 AudioMixer::TRACK,
4395 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4396
4397 // reset retry count
4398 track->mRetryCount = kMaxTrackRetries;
4399
4400 // If one track is ready, set the mixer ready if:
4401 // - the mixer was not ready during previous round OR
4402 // - no other track is not ready
4403 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4404 mixerStatus != MIXER_TRACKS_ENABLED) {
4405 mixerStatus = MIXER_TRACKS_READY;
4406 }
4407 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004408 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004409 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4410 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004411 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004412 } else {
4413 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004414 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004415
Eric Laurent81784c32012-11-19 14:55:58 -08004416 // clear effect chain input buffer if an active track underruns to avoid sending
4417 // previous audio buffer again to effects
4418 chain = getEffectChain_l(track->sessionId());
4419 if (chain != 0) {
4420 chain->clearInputBuffer();
4421 }
4422
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004423 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004424 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4425 track->isStopped() || track->isPaused()) {
4426 // We have consumed all the buffers of this track.
4427 // Remove it from the list of active tracks.
4428 // TODO: use actual buffer filling status instead of latency when available from
4429 // audio HAL
4430 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004431 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004432 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4433 if (track->isStopped()) {
4434 track->reset();
4435 }
4436 tracksToRemove->add(track);
4437 }
4438 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004439 // No buffers for this track. Give it a few chances to
4440 // fill a buffer, then remove it from active list.
4441 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004442 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004443 tracksToRemove->add(track);
4444 // indicate to client process that the track was disabled because of underrun;
4445 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004446 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004447 // If one track is not ready, mark the mixer also not ready if:
4448 // - the mixer was ready during previous round OR
4449 // - no other track is ready
4450 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4451 mixerStatus != MIXER_TRACKS_READY) {
4452 mixerStatus = MIXER_TRACKS_ENABLED;
4453 }
4454 }
4455 mAudioMixer->disable(name);
4456 }
4457
4458 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004459
4460 }
4461
4462 // Push the new FastMixer state if necessary
4463 bool pauseAudioWatchdog = false;
4464 if (didModify) {
4465 state->mFastTracksGen++;
4466 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4467 if (kUseFastMixer == FastMixer_Dynamic &&
4468 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4469 state->mCommand = FastMixerState::COLD_IDLE;
4470 state->mColdFutexAddr = &mFastMixerFutex;
4471 state->mColdGen++;
4472 mFastMixerFutex = 0;
4473 if (kUseFastMixer == FastMixer_Dynamic) {
4474 mNormalSink = mOutputSink;
4475 }
4476 // If we go into cold idle, need to wait for acknowledgement
4477 // so that fast mixer stops doing I/O.
4478 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4479 pauseAudioWatchdog = true;
4480 }
Eric Laurent81784c32012-11-19 14:55:58 -08004481 }
4482 if (sq != NULL) {
4483 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004484 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4485 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4486 // when bringing the output sink into standby.)
4487 //
4488 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4489 //
4490 // This occurs with BT suspend when we idle the FastMixer with
4491 // active tracks, which may be added or removed.
4492 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004493 }
4494#ifdef AUDIO_WATCHDOG
4495 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4496 mAudioWatchdog->pause();
4497 }
4498#endif
4499
4500 // Now perform the deferred reset on fast tracks that have stopped
4501 while (resetMask != 0) {
4502 size_t i = __builtin_ctz(resetMask);
4503 ALOG_ASSERT(i < count);
4504 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004505 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004506 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4507 track->reset();
4508 }
4509
4510 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004511 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004512
Eric Laurent97d547d2014-09-02 14:45:53 -07004513 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4514 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004515 }
4516
4517 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004518 // as long as there are effects we should clear the effects buffer, to avoid
4519 // passing a non-clean buffer to the effect chain
4520 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004521 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004522 // sink or mix buffer must be cleared if all tracks are connected to an
4523 // effect chain as in this case the mixer will not write to the sink or mix buffer
4524 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004525 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4526 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004527 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004528 if (mMixerBufferValid) {
4529 memset(mMixerBuffer, 0, mMixerBufferSize);
4530 // TODO: In testing, mSinkBuffer below need not be cleared because
4531 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4532 // after mixing.
4533 //
4534 // To enforce this guarantee:
4535 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4536 // (mixedTracks == 0 && fastTracks > 0))
4537 // must imply MIXER_TRACKS_READY.
4538 // Later, we may clear buffers regardless, and skip much of this logic.
4539 }
Andy Hung98ef9782014-03-04 14:46:50 -08004540 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004541 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004542 }
4543
4544 // if any fast tracks, then status is ready
4545 mMixerStatusIgnoringFastTracks = mixerStatus;
4546 if (fastTracks > 0) {
4547 mixerStatus = MIXER_TRACKS_READY;
4548 }
4549 return mixerStatus;
4550}
4551
Eric Laurentad7dd962016-09-22 12:38:37 -07004552// trackCountForUid_l() must be called with ThreadBase::mLock held
4553uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4554{
4555 uint32_t trackCount = 0;
4556 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004557 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004558 trackCount++;
4559 }
4560 }
4561 return trackCount;
4562}
4563
Eric Laurent81784c32012-11-19 14:55:58 -08004564// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004565int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004566 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004567{
Eric Laurentad7dd962016-09-22 12:38:37 -07004568 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4569 return -1;
4570 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004571 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004572}
4573
4574// deleteTrackName_l() must be called with ThreadBase::mLock held
4575void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4576{
4577 ALOGV("remove track (%d) and delete from mixer", name);
4578 mAudioMixer->deleteTrackName(name);
4579}
4580
Eric Laurent10351942014-05-08 18:49:52 -07004581// checkForNewParameter_l() must be called with ThreadBase::mLock held
4582bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4583 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004584{
Eric Laurent81784c32012-11-19 14:55:58 -08004585 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004586 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004587
Eric Laurent10351942014-05-08 18:49:52 -07004588 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004589
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004590 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004591
Eric Laurent10351942014-05-08 18:49:52 -07004592 AudioParameter param = AudioParameter(keyValuePair);
4593 int value;
4594 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4595 reconfig = true;
4596 }
4597 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004598 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004599 status = BAD_VALUE;
4600 } else {
4601 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004602 reconfig = true;
4603 }
Eric Laurent10351942014-05-08 18:49:52 -07004604 }
4605 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004606 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004607 status = BAD_VALUE;
4608 } else {
4609 // no need to save value, since it's constant
4610 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004611 }
Eric Laurent10351942014-05-08 18:49:52 -07004612 }
4613 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4614 // do not accept frame count changes if tracks are open as the track buffer
4615 // size depends on frame count and correct behavior would not be guaranteed
4616 // if frame count is changed after track creation
4617 if (!mTracks.isEmpty()) {
4618 status = INVALID_OPERATION;
4619 } else {
4620 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004621 }
Eric Laurent10351942014-05-08 18:49:52 -07004622 }
4623 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004624#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004625 // when changing the audio output device, call addBatteryData to notify
4626 // the change
4627 if (mOutDevice != value) {
4628 uint32_t params = 0;
4629 // check whether speaker is on
4630 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4631 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004632 }
Eric Laurent10351942014-05-08 18:49:52 -07004633
4634 audio_devices_t deviceWithoutSpeaker
4635 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4636 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004637 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004638 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4639 }
4640
4641 if (params != 0) {
4642 addBatteryData(params);
4643 }
4644 }
Eric Laurent81784c32012-11-19 14:55:58 -08004645#endif
4646
Eric Laurent10351942014-05-08 18:49:52 -07004647 // forward device change to effects that have requested to be
4648 // aware of attached audio device.
4649 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004650 a2dpDeviceChanged =
4651 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004652 mOutDevice = value;
4653 for (size_t i = 0; i < mEffectChains.size(); i++) {
4654 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004655 }
4656 }
Eric Laurent10351942014-05-08 18:49:52 -07004657 }
Eric Laurent81784c32012-11-19 14:55:58 -08004658
Eric Laurent10351942014-05-08 18:49:52 -07004659 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004660 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004661 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004662 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004663 mStandby = true;
4664 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004665 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004666 }
Eric Laurent10351942014-05-08 18:49:52 -07004667 if (status == NO_ERROR && reconfig) {
4668 readOutputParameters_l();
4669 delete mAudioMixer;
4670 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4671 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004672 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004673 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004674 if (name < 0) {
4675 break;
4676 }
4677 mTracks[i]->mName = name;
4678 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004679 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004680 }
Eric Laurent81784c32012-11-19 14:55:58 -08004681 }
4682
Eric Laurent42537be2016-01-08 17:16:42 -08004683 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004684}
4685
4686
4687void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4688{
Eric Laurent81784c32012-11-19 14:55:58 -08004689 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004690 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004691 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004692 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004693
4694 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004695 // while we are dumping it. It may be inconsistent, but it won't mutate!
4696 // This is a large object so we place it on the heap.
4697 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4698 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4699 copy->dump(fd);
4700 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004701
4702#ifdef STATE_QUEUE_DUMP
4703 // Similar for state queue
4704 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4705 observerCopy.dump(fd);
4706 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4707 mutatorCopy.dump(fd);
4708#endif
4709
Glenn Kasten46909e72013-02-26 09:20:22 -08004710#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004711 // Write the tee output to a .wav file
4712 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004713#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004714
4715#ifdef AUDIO_WATCHDOG
4716 if (mAudioWatchdog != 0) {
4717 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4718 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4719 wdCopy.dump(fd);
4720 }
4721#endif
4722}
4723
4724uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4725{
4726 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4727}
4728
4729uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4730{
4731 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4732}
4733
4734void AudioFlinger::MixerThread::cacheParameters_l()
4735{
4736 PlaybackThread::cacheParameters_l();
4737
4738 // FIXME: Relaxed timing because of a certain device that can't meet latency
4739 // Should be reduced to 2x after the vendor fixes the driver issue
4740 // increase threshold again due to low power audio mode. The way this warning
4741 // threshold is calculated and its usefulness should be reconsidered anyway.
4742 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4743}
4744
4745// ----------------------------------------------------------------------------
4746
4747AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004748 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4749 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004750 // mLeftVolFloat, mRightVolFloat
4751{
4752}
4753
Eric Laurentbfb1b832013-01-07 09:53:42 -08004754AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4755 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004756 ThreadBase::type_t type, bool systemReady)
4757 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004758 // mLeftVolFloat, mRightVolFloat
4759{
4760}
4761
Eric Laurent81784c32012-11-19 14:55:58 -08004762AudioFlinger::DirectOutputThread::~DirectOutputThread()
4763{
4764}
4765
Eric Laurent5850c4c2016-11-10 13:04:31 -08004766void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004767{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004768 float left, right;
4769
4770 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4771 left = right = 0;
4772 } else {
4773 float typeVolume = mStreamTypes[track->streamType()].volume;
4774 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004775 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004776
4777 if (audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4778 const float vh = track->getVolumeHandler()->getVolume(
4779 track->mAudioTrackServerProxy->framesReleased());
4780 v *= vh;
4781 } else {
4782 // TODO: implement volume scaling in HW
4783 }
4784
Glenn Kastenc56f3422014-03-21 17:53:17 -07004785 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4786 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4787 if (left > GAIN_FLOAT_UNITY) {
4788 left = GAIN_FLOAT_UNITY;
4789 }
4790 left *= v;
4791 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4792 if (right > GAIN_FLOAT_UNITY) {
4793 right = GAIN_FLOAT_UNITY;
4794 }
4795 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004796 }
4797
4798 if (lastTrack) {
4799 if (left != mLeftVolFloat || right != mRightVolFloat) {
4800 mLeftVolFloat = left;
4801 mRightVolFloat = right;
4802
4803 // Convert volumes from float to 8.24
4804 uint32_t vl = (uint32_t)(left * (1 << 24));
4805 uint32_t vr = (uint32_t)(right * (1 << 24));
4806
4807 // Delegate volume control to effect in track effect chain if needed
4808 // only one effect chain can be present on DirectOutputThread, so if
4809 // there is one, the track is connected to it
4810 if (!mEffectChains.isEmpty()) {
4811 mEffectChains[0]->setVolume_l(&vl, &vr);
4812 left = (float)vl / (1 << 24);
4813 right = (float)vr / (1 << 24);
4814 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004815 status_t result = mOutput->stream->setVolume(left, right);
4816 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004817 }
4818 }
4819}
4820
Phil Burk43b4dcc2015-06-09 16:53:44 -07004821void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4822{
4823 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004824 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004825
Eric Laurent0f0631e2015-07-06 18:01:25 -07004826 if (previousTrack != 0 && latestTrack != 0) {
4827 if (mType == DIRECT) {
4828 if (previousTrack.get() != latestTrack.get()) {
4829 mFlushPending = true;
4830 }
4831 } else /* mType == OFFLOAD */ {
4832 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4833 mFlushPending = true;
4834 }
4835 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004836 }
4837 PlaybackThread::onAddNewTrack_l();
4838}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004839
Eric Laurent81784c32012-11-19 14:55:58 -08004840AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4841 Vector< sp<Track> > *tracksToRemove
4842)
4843{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004844 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004845 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004846 bool doHwPause = false;
4847 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004848
4849 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004850 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004851 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004852 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004853 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004854 continue;
4855 }
4856
Eric Laurent5850c4c2016-11-10 13:04:31 -08004857 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004858#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004859 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004860#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004861 // Only consider last track started for volume and mixer state control.
4862 // In theory an older track could underrun and restart after the new one starts
4863 // but as we only care about the transition phase between two tracks on a
4864 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004865 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004866 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004867
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004868 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004869 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004870 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004871 doHwPause = true;
4872 mHwPaused = true;
4873 }
4874 tracksToRemove->add(track);
4875 } else if (track->isFlushPending()) {
4876 track->flushAck();
4877 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004878 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004879 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004880 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004881 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004882 if (last) {
4883 mLeftVolFloat = mRightVolFloat = -1.0;
4884 if (mHwPaused) {
4885 doHwResume = true;
4886 mHwPaused = false;
4887 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004888 }
4889 }
4890
Eric Laurent81784c32012-11-19 14:55:58 -08004891 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004892 // for all its buffers to be filled before processing it.
4893 // Allow draining the buffer in case the client
4894 // app does not call stop() and relies on underrun to stop:
4895 // hence the test on (track->mRetryCount > 1).
4896 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004897 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004898 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004899 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004900 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004901 minFrames = mNormalFrameCount;
4902 } else {
4903 minFrames = 1;
4904 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004905
Eric Laurentab5cdba2014-06-09 17:22:27 -07004906 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4907 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004908 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004909 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004910
4911 if (track->mFillingUpStatus == Track::FS_FILLED) {
4912 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004913 if (last) {
4914 // make sure processVolume_l() will apply new volume even if 0
4915 mLeftVolFloat = mRightVolFloat = -1.0;
4916 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004917 if (!mHwSupportsPause) {
4918 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004919 }
4920 }
4921
4922 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004923 processVolume_l(track, last);
4924 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004925 sp<Track> previousTrack = mPreviousTrack.promote();
4926 if (previousTrack != 0) {
4927 if (track != previousTrack.get()) {
4928 // Flush any data still being written from last track
4929 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004930 // Invalidate previous track to force a seek when resuming.
4931 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004932 }
4933 }
4934 mPreviousTrack = track;
4935
Eric Laurentd595b7c2013-04-03 17:27:56 -07004936 // reset retry count
4937 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004938 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004939 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004940 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004941 doHwResume = true;
4942 mHwPaused = false;
4943 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004944 }
Eric Laurent81784c32012-11-19 14:55:58 -08004945 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004946 // clear effect chain input buffer if the last active track started underruns
4947 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004948 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004949 mEffectChains[0]->clearInputBuffer();
4950 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004951 if (track->isStopping_1()) {
4952 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004953 if (last && mHwPaused) {
4954 doHwResume = true;
4955 mHwPaused = false;
4956 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004957 }
4958 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4959 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004960 // We have consumed all the buffers of this track.
4961 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004962 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004963 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004964 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4965 } else {
4966 audioHALFrames = 0;
4967 }
4968
Andy Hung818e7a32016-02-16 18:08:07 -08004969 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004970 if (mStandby || !last ||
4971 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004972 if (track->isStopping_2()) {
4973 track->mState = TrackBase::STOPPED;
4974 }
Eric Laurent81784c32012-11-19 14:55:58 -08004975 if (track->isStopped()) {
4976 track->reset();
4977 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004978 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004979 }
4980 } else {
4981 // No buffers for this track. Give it a few chances to
4982 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004983 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004984 if (--(track->mRetryCount) <= 0) {
4985 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004986 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004987 // indicate to client process that the track was disabled because of underrun;
4988 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004989 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004990 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004991 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4992 "minFrames = %u, mFormat = %#x",
4993 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004994 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004995 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004996 doHwPause = true;
4997 mHwPaused = true;
4998 }
Eric Laurent81784c32012-11-19 14:55:58 -08004999 }
5000 }
5001 }
5002 }
5003
Eric Laurentd1f69b02014-12-15 14:33:13 -08005004 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005005 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005006 for (size_t i = 0; i < mTracks.size(); i++) {
5007 if (mTracks[i]->isFlushPending()) {
5008 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005009 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005010 }
5011 }
5012 }
5013
5014 // make sure the pause/flush/resume sequence is executed in the right order.
5015 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5016 // before flush and then resume HW. This can happen in case of pause/flush/resume
5017 // if resume is received before pause is executed.
5018 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005019 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005020 status_t result = mOutput->stream->pause();
5021 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005022 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005023 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005024 flushHw_l();
5025 }
5026 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005027 status_t result = mOutput->stream->resume();
5028 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005029 }
Eric Laurent81784c32012-11-19 14:55:58 -08005030 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005031 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005032
5033 return mixerStatus;
5034}
5035
5036void AudioFlinger::DirectOutputThread::threadLoop_mix()
5037{
Eric Laurent81784c32012-11-19 14:55:58 -08005038 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005039 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005040 // output audio to hardware
5041 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005042 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005043 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005044 status_t status = mActiveTrack->getNextBuffer(&buffer);
5045 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005046 // no need to pad with 0 for compressed audio
5047 if (audio_has_proportional_frames(mFormat)) {
5048 memset(curBuf, 0, frameCount * mFrameSize);
5049 }
Eric Laurent81784c32012-11-19 14:55:58 -08005050 break;
5051 }
5052 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5053 frameCount -= buffer.frameCount;
5054 curBuf += buffer.frameCount * mFrameSize;
5055 mActiveTrack->releaseBuffer(&buffer);
5056 }
Andy Hung2098f272014-02-27 14:00:06 -08005057 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005058 mSleepTimeUs = 0;
5059 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005060 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005061}
5062
5063void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5064{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005065 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005066 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005067 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005068 return;
5069 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005070 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005071 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005072 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005073 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005074 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005075 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005076 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005077 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005078 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005079 }
5080}
5081
Eric Laurentd1f69b02014-12-15 14:33:13 -08005082void AudioFlinger::DirectOutputThread::threadLoop_exit()
5083{
5084 {
5085 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005086 for (size_t i = 0; i < mTracks.size(); i++) {
5087 if (mTracks[i]->isFlushPending()) {
5088 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005089 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005090 }
5091 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005092 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005093 flushHw_l();
5094 }
5095 }
5096 PlaybackThread::threadLoop_exit();
5097}
5098
5099// must be called with thread mutex locked
5100bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5101{
5102 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005103 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005104
vivek mehta9cd7ad12016-03-17 00:18:29 -07005105 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5106 return !mStandby;
5107 }
5108
Eric Laurentd1f69b02014-12-15 14:33:13 -08005109 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5110 // after a timeout and we will enter standby then.
5111 if (mTracks.size() > 0) {
5112 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005113 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5114 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005115 }
5116
Eric Laurent5cff4032015-05-26 13:49:58 -07005117 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005118}
5119
Eric Laurent81784c32012-11-19 14:55:58 -08005120// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005121int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005122 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005123{
Eric Laurentad7dd962016-09-22 12:38:37 -07005124 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5125 return -1;
5126 }
Eric Laurent81784c32012-11-19 14:55:58 -08005127 return 0;
5128}
5129
5130// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005131void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005132{
5133}
5134
Eric Laurent10351942014-05-08 18:49:52 -07005135// checkForNewParameter_l() must be called with ThreadBase::mLock held
5136bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5137 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005138{
5139 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005140 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005141
Eric Laurent10351942014-05-08 18:49:52 -07005142 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005143
Eric Laurent10351942014-05-08 18:49:52 -07005144 AudioParameter param = AudioParameter(keyValuePair);
5145 int value;
5146 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5147 // forward device change to effects that have requested to be
5148 // aware of attached audio device.
5149 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005150 a2dpDeviceChanged =
5151 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005152 mOutDevice = value;
5153 for (size_t i = 0; i < mEffectChains.size(); i++) {
5154 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005155 }
5156 }
Eric Laurent81784c32012-11-19 14:55:58 -08005157 }
Eric Laurent10351942014-05-08 18:49:52 -07005158 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5159 // do not accept frame count changes if tracks are open as the track buffer
5160 // size depends on frame count and correct behavior would not be garantied
5161 // if frame count is changed after track creation
5162 if (!mTracks.isEmpty()) {
5163 status = INVALID_OPERATION;
5164 } else {
5165 reconfig = true;
5166 }
5167 }
5168 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005169 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005170 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005171 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005172 mStandby = true;
5173 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005174 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005175 }
5176 if (status == NO_ERROR && reconfig) {
5177 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005178 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005179 }
5180 }
5181
Eric Laurent42537be2016-01-08 17:16:42 -08005182 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005183}
5184
5185uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5186{
5187 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005188 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005189 time = PlaybackThread::activeSleepTimeUs();
5190 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005191 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005192 }
5193 return time;
5194}
5195
5196uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5197{
5198 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005199 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005200 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5201 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005202 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005203 }
5204 return time;
5205}
5206
5207uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5208{
5209 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005210 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005211 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5212 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005213 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005214 }
5215 return time;
5216}
5217
5218void AudioFlinger::DirectOutputThread::cacheParameters_l()
5219{
5220 PlaybackThread::cacheParameters_l();
5221
5222 // use shorter standby delay as on normal output to release
5223 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005224 // no delay on outputs with HW A/V sync
5225 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005226 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005227 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005228 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005229 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005230 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005231 }
Eric Laurent81784c32012-11-19 14:55:58 -08005232}
5233
Eric Laurente659ef42014-09-29 13:06:46 -07005234void AudioFlinger::DirectOutputThread::flushHw_l()
5235{
Phil Burk062e67a2015-02-11 13:40:50 -08005236 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005237 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005238 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005239}
5240
Eric Laurent81784c32012-11-19 14:55:58 -08005241// ----------------------------------------------------------------------------
5242
Eric Laurentbfb1b832013-01-07 09:53:42 -08005243AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005244 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005245 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005246 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005247 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005248 mDrainSequence(0),
5249 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005250{
5251}
5252
5253AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5254{
5255}
5256
5257void AudioFlinger::AsyncCallbackThread::onFirstRef()
5258{
5259 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5260}
5261
5262bool AudioFlinger::AsyncCallbackThread::threadLoop()
5263{
5264 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005265 uint32_t writeAckSequence;
5266 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005267 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005268
5269 {
5270 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005271 while (!((mWriteAckSequence & 1) ||
5272 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005273 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005274 exitPending())) {
5275 mWaitWorkCV.wait(mLock);
5276 }
5277
Eric Laurentbfb1b832013-01-07 09:53:42 -08005278 if (exitPending()) {
5279 break;
5280 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005281 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5282 mWriteAckSequence, mDrainSequence);
5283 writeAckSequence = mWriteAckSequence;
5284 mWriteAckSequence &= ~1;
5285 drainSequence = mDrainSequence;
5286 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005287 asyncError = mAsyncError;
5288 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005289 }
5290 {
Eric Laurent4de95592013-09-26 15:28:21 -07005291 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5292 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005293 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005294 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005295 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005296 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005297 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005298 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005299 if (asyncError) {
5300 playbackThread->onAsyncError();
5301 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005302 }
5303 }
5304 }
5305 return false;
5306}
5307
5308void AudioFlinger::AsyncCallbackThread::exit()
5309{
5310 ALOGV("AsyncCallbackThread::exit");
5311 Mutex::Autolock _l(mLock);
5312 requestExit();
5313 mWaitWorkCV.broadcast();
5314}
5315
Eric Laurent3b4529e2013-09-05 18:09:19 -07005316void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005317{
5318 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005319 // bit 0 is cleared
5320 mWriteAckSequence = sequence << 1;
5321}
5322
5323void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5324{
5325 Mutex::Autolock _l(mLock);
5326 // ignore unexpected callbacks
5327 if (mWriteAckSequence & 2) {
5328 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005329 mWaitWorkCV.signal();
5330 }
5331}
5332
Eric Laurent3b4529e2013-09-05 18:09:19 -07005333void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005334{
5335 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005336 // bit 0 is cleared
5337 mDrainSequence = sequence << 1;
5338}
5339
5340void AudioFlinger::AsyncCallbackThread::resetDraining()
5341{
5342 Mutex::Autolock _l(mLock);
5343 // ignore unexpected callbacks
5344 if (mDrainSequence & 2) {
5345 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005346 mWaitWorkCV.signal();
5347 }
5348}
5349
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005350void AudioFlinger::AsyncCallbackThread::setAsyncError()
5351{
5352 Mutex::Autolock _l(mLock);
5353 mAsyncError = true;
5354 mWaitWorkCV.signal();
5355}
5356
Eric Laurentbfb1b832013-01-07 09:53:42 -08005357
5358// ----------------------------------------------------------------------------
5359AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005360 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5361 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005362 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5363 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005364{
Eric Laurentfd477972013-10-25 18:10:40 -07005365 //FIXME: mStandby should be set to true by ThreadBase constructor
5366 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005367 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005368}
5369
Eric Laurentbfb1b832013-01-07 09:53:42 -08005370void AudioFlinger::OffloadThread::threadLoop_exit()
5371{
5372 if (mFlushPending || mHwPaused) {
5373 // If a flush is pending or track was paused, just discard buffered data
5374 flushHw_l();
5375 } else {
5376 mMixerStatus = MIXER_DRAIN_ALL;
5377 threadLoop_drain();
5378 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005379 if (mUseAsyncWrite) {
5380 ALOG_ASSERT(mCallbackThread != 0);
5381 mCallbackThread->exit();
5382 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005383 PlaybackThread::threadLoop_exit();
5384}
5385
5386AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5387 Vector< sp<Track> > *tracksToRemove
5388)
5389{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005390 size_t count = mActiveTracks.size();
5391
5392 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005393 bool doHwPause = false;
5394 bool doHwResume = false;
5395
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005396 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005397
Eric Laurentbfb1b832013-01-07 09:53:42 -08005398 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005399 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005400 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005401#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005402 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005403#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005404 // Only consider last track started for volume and mixer state control.
5405 // In theory an older track could underrun and restart after the new one starts
5406 // but as we only care about the transition phase between two tracks on a
5407 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005408 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005409 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005410
Haynes Mathew George7844f672014-01-15 12:32:55 -08005411 if (track->isInvalid()) {
5412 ALOGW("An invalidated track shouldn't be in active list");
5413 tracksToRemove->add(track);
5414 continue;
5415 }
5416
5417 if (track->mState == TrackBase::IDLE) {
5418 ALOGW("An idle track shouldn't be in active list");
5419 continue;
5420 }
5421
Eric Laurentbfb1b832013-01-07 09:53:42 -08005422 if (track->isPausing()) {
5423 track->setPaused();
5424 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005425 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005426 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005427 mHwPaused = true;
5428 }
5429 // If we were part way through writing the mixbuffer to
5430 // the HAL we must save this until we resume
5431 // BUG - this will be wrong if a different track is made active,
5432 // in that case we want to discard the pending data in the
5433 // mixbuffer and tell the client to present it again when the
5434 // track is resumed
5435 mPausedWriteLength = mCurrentWriteLength;
5436 mPausedBytesRemaining = mBytesRemaining;
5437 mBytesRemaining = 0; // stop writing
5438 }
5439 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005440 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005441 if (track->isStopping_1()) {
5442 track->mRetryCount = kMaxTrackStopRetriesOffload;
5443 } else {
5444 track->mRetryCount = kMaxTrackRetriesOffload;
5445 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005446 track->flushAck();
5447 if (last) {
5448 mFlushPending = true;
5449 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005450 } else if (track->isResumePending()){
5451 track->resumeAck();
5452 if (last) {
5453 if (mPausedBytesRemaining) {
5454 // Need to continue write that was interrupted
5455 mCurrentWriteLength = mPausedWriteLength;
5456 mBytesRemaining = mPausedBytesRemaining;
5457 mPausedBytesRemaining = 0;
5458 }
5459 if (mHwPaused) {
5460 doHwResume = true;
5461 mHwPaused = false;
5462 // threadLoop_mix() will handle the case that we need to
5463 // resume an interrupted write
5464 }
5465 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005466 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005467
Eric Laurent3df841a2016-07-15 15:15:40 -07005468 mLeftVolFloat = mRightVolFloat = -1.0;
5469
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005470 // Do not handle new data in this iteration even if track->framesReady()
5471 mixerStatus = MIXER_TRACKS_ENABLED;
5472 }
5473 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005474 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005475 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005476 if (track->mFillingUpStatus == Track::FS_FILLED) {
5477 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005478 if (last) {
5479 // make sure processVolume_l() will apply new volume even if 0
5480 mLeftVolFloat = mRightVolFloat = -1.0;
5481 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 }
5483
5484 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005485 sp<Track> previousTrack = mPreviousTrack.promote();
5486 if (previousTrack != 0) {
5487 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005488 // Flush any data still being written from last track
5489 mBytesRemaining = 0;
5490 if (mPausedBytesRemaining) {
5491 // Last track was paused so we also need to flush saved
5492 // mixbuffer state and invalidate track so that it will
5493 // re-submit that unwritten data when it is next resumed
5494 mPausedBytesRemaining = 0;
5495 // Invalidate is a bit drastic - would be more efficient
5496 // to have a flag to tell client that some of the
5497 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005498 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005499 }
5500 // flush data already sent to the DSP if changing audio session as audio
5501 // comes from a different source. Also invalidate previous track to force a
5502 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005503 if (previousTrack->sessionId() != track->sessionId()) {
5504 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005505 }
5506 }
5507 }
5508 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005509 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005510 if (track->isStopping_1()) {
5511 track->mRetryCount = kMaxTrackStopRetriesOffload;
5512 } else {
5513 track->mRetryCount = kMaxTrackRetriesOffload;
5514 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005515 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005516 mixerStatus = MIXER_TRACKS_READY;
5517 }
5518 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005519 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005520 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005521 if (--(track->mRetryCount) <= 0) {
5522 // Hardware buffer can hold a large amount of audio so we must
5523 // wait for all current track's data to drain before we say
5524 // that the track is stopped.
5525 if (mBytesRemaining == 0) {
5526 // Only start draining when all data in mixbuffer
5527 // has been written
5528 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5529 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5530 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5531 if (last && !mStandby) {
5532 // do not modify drain sequence if we are already draining. This happens
5533 // when resuming from pause after drain.
5534 if ((mDrainSequence & 1) == 0) {
5535 mSleepTimeUs = 0;
5536 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5537 mixerStatus = MIXER_DRAIN_TRACK;
5538 mDrainSequence += 2;
5539 }
5540 if (mHwPaused) {
5541 // It is possible to move from PAUSED to STOPPING_1 without
5542 // a resume so we must ensure hardware is running
5543 doHwResume = true;
5544 mHwPaused = false;
5545 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005546 }
5547 }
Eric Laurente93cc032016-05-05 10:15:10 -07005548 } else if (last) {
5549 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5550 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005551 }
5552 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005553 // Drain has completed or we are in standby, signal presentation complete
5554 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005555 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005556 uint32_t latency = 0;
5557 status_t result = mOutput->stream->getLatency(&latency);
5558 ALOGE_IF(result != OK,
5559 "Error when retrieving output stream latency: %d", result);
5560 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005561 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005562 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005563 track->presentationComplete(framesWritten, audioHALFrames);
5564 track->reset();
5565 tracksToRemove->add(track);
5566 }
5567 } else {
5568 // No buffers for this track. Give it a few chances to
5569 // fill a buffer, then remove it from active list.
5570 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005571 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005572 uint64_t position = 0;
5573 struct timespec unused;
5574 // The running check restarts the retry counter at least once.
5575 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5576 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5577 running = true;
5578 mOffloadUnderrunPosition = position;
5579 }
5580 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005581 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5582 (long long)position, (long long)mOffloadUnderrunPosition);
5583 }
5584 if (running) { // still running, give us more time.
5585 track->mRetryCount = kMaxTrackRetriesOffload;
5586 } else {
5587 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5588 track->name());
5589 tracksToRemove->add(track);
5590 // indicate to client process that the track was disabled because of underrun;
5591 // it will then automatically call start() when data is available
5592 track->disable();
5593 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005594 } else if (last){
5595 mixerStatus = MIXER_TRACKS_ENABLED;
5596 }
5597 }
5598 }
5599 // compute volume for this track
5600 processVolume_l(track, last);
5601 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005602
Eric Laurentea0fade2013-10-04 16:23:48 -07005603 // make sure the pause/flush/resume sequence is executed in the right order.
5604 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5605 // before flush and then resume HW. This can happen in case of pause/flush/resume
5606 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005607 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005608 status_t result = mOutput->stream->pause();
5609 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005610 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005611 if (mFlushPending) {
5612 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005613 }
Eric Laurentfd477972013-10-25 18:10:40 -07005614 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005615 status_t result = mOutput->stream->resume();
5616 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005617 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005618
Eric Laurentbfb1b832013-01-07 09:53:42 -08005619 // remove all the tracks that need to be...
5620 removeTracks_l(*tracksToRemove);
5621
5622 return mixerStatus;
5623}
5624
Eric Laurentbfb1b832013-01-07 09:53:42 -08005625// must be called with thread mutex locked
5626bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5627{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005628 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5629 mWriteAckSequence, mDrainSequence);
5630 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005631 return true;
5632 }
5633 return false;
5634}
5635
Eric Laurentbfb1b832013-01-07 09:53:42 -08005636bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5637{
5638 Mutex::Autolock _l(mLock);
5639 return waitingAsyncCallback_l();
5640}
5641
5642void AudioFlinger::OffloadThread::flushHw_l()
5643{
Eric Laurente659ef42014-09-29 13:06:46 -07005644 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005645 // Flush anything still waiting in the mixbuffer
5646 mCurrentWriteLength = 0;
5647 mBytesRemaining = 0;
5648 mPausedWriteLength = 0;
5649 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005650 // reset bytes written count to reflect that DSP buffers are empty after flush.
5651 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005652 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005653
Eric Laurentbfb1b832013-01-07 09:53:42 -08005654 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005655 // discard any pending drain or write ack by incrementing sequence
5656 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5657 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005658 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005659 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5660 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005661 }
5662}
5663
Haynes Mathew George05317d22016-05-03 16:34:26 -07005664void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5665{
5666 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005667 if (PlaybackThread::invalidateTracks_l(streamType)) {
5668 mFlushPending = true;
5669 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005670}
5671
Eric Laurentbfb1b832013-01-07 09:53:42 -08005672// ----------------------------------------------------------------------------
5673
Eric Laurent81784c32012-11-19 14:55:58 -08005674AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005675 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005676 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005677 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005678 mWaitTimeMs(UINT_MAX)
5679{
5680 addOutputTrack(mainThread);
5681}
5682
5683AudioFlinger::DuplicatingThread::~DuplicatingThread()
5684{
5685 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5686 mOutputTracks[i]->destroy();
5687 }
5688}
5689
5690void AudioFlinger::DuplicatingThread::threadLoop_mix()
5691{
5692 // mix buffers...
5693 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005694 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005695 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005696 if (mMixerBufferValid) {
5697 memset(mMixerBuffer, 0, mMixerBufferSize);
5698 } else {
5699 memset(mSinkBuffer, 0, mSinkBufferSize);
5700 }
Eric Laurent81784c32012-11-19 14:55:58 -08005701 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005702 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005703 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005704 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005705 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005706}
5707
5708void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5709{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005710 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005711 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005712 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005713 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005714 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005715 }
5716 } else if (mBytesWritten != 0) {
5717 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5718 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005719 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005720 } else {
5721 // flush remaining overflow buffers in output tracks
5722 writeFrames = 0;
5723 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005724 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005725 }
5726}
5727
Eric Laurentbfb1b832013-01-07 09:53:42 -08005728ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005729{
5730 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005731 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005732 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005733 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005734 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005735}
5736
5737void AudioFlinger::DuplicatingThread::threadLoop_standby()
5738{
5739 // DuplicatingThread implements standby by stopping all tracks
5740 for (size_t i = 0; i < outputTracks.size(); i++) {
5741 outputTracks[i]->stop();
5742 }
5743}
5744
5745void AudioFlinger::DuplicatingThread::saveOutputTracks()
5746{
5747 outputTracks = mOutputTracks;
5748}
5749
5750void AudioFlinger::DuplicatingThread::clearOutputTracks()
5751{
5752 outputTracks.clear();
5753}
5754
5755void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5756{
5757 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005758 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5759 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5760 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5761 const size_t frameCount =
5762 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5763 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5764 // from different OutputTracks and their associated MixerThreads (e.g. one may
5765 // nearly empty and the other may be dropping data).
5766
5767 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005768 this,
5769 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005770 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005771 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005772 frameCount,
5773 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005774 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5775 if (status != NO_ERROR) {
5776 ALOGE("addOutputTrack() initCheck failed %d", status);
5777 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005778 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005779 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5780 mOutputTracks.add(outputTrack);
5781 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5782 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005783}
5784
5785void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5786{
5787 Mutex::Autolock _l(mLock);
5788 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5789 if (mOutputTracks[i]->thread() == thread) {
5790 mOutputTracks[i]->destroy();
5791 mOutputTracks.removeAt(i);
5792 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005793 if (thread->getOutput() == mOutput) {
5794 mOutput = NULL;
5795 }
Eric Laurent81784c32012-11-19 14:55:58 -08005796 return;
5797 }
5798 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005799 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005800}
5801
5802// caller must hold mLock
5803void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5804{
5805 mWaitTimeMs = UINT_MAX;
5806 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5807 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5808 if (strong != 0) {
5809 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5810 if (waitTimeMs < mWaitTimeMs) {
5811 mWaitTimeMs = waitTimeMs;
5812 }
5813 }
5814 }
5815}
5816
5817
5818bool AudioFlinger::DuplicatingThread::outputsReady(
5819 const SortedVector< sp<OutputTrack> > &outputTracks)
5820{
5821 for (size_t i = 0; i < outputTracks.size(); i++) {
5822 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5823 if (thread == 0) {
5824 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5825 outputTracks[i].get());
5826 return false;
5827 }
5828 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5829 // see note at standby() declaration
5830 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5831 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5832 thread.get());
5833 return false;
5834 }
5835 }
5836 return true;
5837}
5838
5839uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5840{
5841 return (mWaitTimeMs * 1000) / 2;
5842}
5843
5844void AudioFlinger::DuplicatingThread::cacheParameters_l()
5845{
5846 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5847 updateWaitTime_l();
5848
5849 MixerThread::cacheParameters_l();
5850}
5851
Eric Laurent6acd1d42017-01-04 14:23:29 -08005852
Eric Laurent81784c32012-11-19 14:55:58 -08005853// ----------------------------------------------------------------------------
5854// Record
5855// ----------------------------------------------------------------------------
5856
5857AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5858 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005859 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005860 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005861 audio_devices_t inDevice,
5862 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005863#ifdef TEE_SINK
5864 , const sp<NBAIO_Sink>& teeSink
5865#endif
5866 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005867 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005868 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005869 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005870 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005871#ifdef TEE_SINK
5872 , mTeeSink(teeSink)
5873#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005874 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5875 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005876 // mFastCapture below
5877 , mFastCaptureFutex(0)
5878 // mInputSource
5879 // mPipeSink
5880 // mPipeSource
5881 , mPipeFramesP2(0)
5882 // mPipeMemory
5883 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005884 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005885{
Glenn Kastend7dca052015-03-05 16:05:54 -08005886 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5887 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005888
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005889 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005890
5891 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005892 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005893 size_t numCounterOffers = 0;
5894 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005895#if !LOG_NDEBUG
5896 ssize_t index =
5897#else
5898 (void)
5899#endif
5900 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005901 ALOG_ASSERT(index == 0);
5902
5903 // initialize fast capture depending on configuration
5904 bool initFastCapture;
5905 switch (kUseFastCapture) {
5906 case FastCapture_Never:
5907 initFastCapture = false;
5908 break;
5909 case FastCapture_Always:
5910 initFastCapture = true;
5911 break;
5912 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005913 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005914 break;
5915 // case FastCapture_Dynamic:
5916 }
5917
5918 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005919 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005920 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005921 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5922 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005923 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5924 void *pipeBuffer;
5925 const sp<MemoryDealer> roHeap(readOnlyHeap());
5926 sp<IMemory> pipeMemory;
5927 if ((roHeap == 0) ||
5928 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5929 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5930 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5931 goto failed;
5932 }
5933 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5934 memset(pipeBuffer, 0, pipeSize);
5935 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5936 const NBAIO_Format offers[1] = {format};
5937 size_t numCounterOffers = 0;
5938 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5939 ALOG_ASSERT(index == 0);
5940 mPipeSink = pipe;
5941 PipeReader *pipeReader = new PipeReader(*pipe);
5942 numCounterOffers = 0;
5943 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5944 ALOG_ASSERT(index == 0);
5945 mPipeSource = pipeReader;
5946 mPipeFramesP2 = pipeFramesP2;
5947 mPipeMemory = pipeMemory;
5948
5949 // create fast capture
5950 mFastCapture = new FastCapture();
5951 FastCaptureStateQueue *sq = mFastCapture->sq();
5952#ifdef STATE_QUEUE_DUMP
5953 // FIXME
5954#endif
5955 FastCaptureState *state = sq->begin();
5956 state->mCblk = NULL;
5957 state->mInputSource = mInputSource.get();
5958 state->mInputSourceGen++;
5959 state->mPipeSink = pipe;
5960 state->mPipeSinkGen++;
5961 state->mFrameCount = mFrameCount;
5962 state->mCommand = FastCaptureState::COLD_IDLE;
5963 // already done in constructor initialization list
5964 //mFastCaptureFutex = 0;
5965 state->mColdFutexAddr = &mFastCaptureFutex;
5966 state->mColdGen++;
5967 state->mDumpState = &mFastCaptureDumpState;
5968#ifdef TEE_SINK
5969 // FIXME
5970#endif
5971 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5972 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5973 sq->end();
5974 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5975
5976 // start the fast capture
5977 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5978 pid_t tid = mFastCapture->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08005979 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005980 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005981#ifdef AUDIO_WATCHDOG
5982 // FIXME
5983#endif
5984
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005985 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005986 }
5987failed: ;
5988
5989 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005990}
5991
Eric Laurent81784c32012-11-19 14:55:58 -08005992AudioFlinger::RecordThread::~RecordThread()
5993{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005994 if (mFastCapture != 0) {
5995 FastCaptureStateQueue *sq = mFastCapture->sq();
5996 FastCaptureState *state = sq->begin();
5997 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5998 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5999 if (old == -1) {
6000 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6001 }
6002 }
6003 state->mCommand = FastCaptureState::EXIT;
6004 sq->end();
6005 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6006 mFastCapture->join();
6007 mFastCapture.clear();
6008 }
6009 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006010 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006011 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006012}
6013
6014void AudioFlinger::RecordThread::onFirstRef()
6015{
Glenn Kastend7dca052015-03-05 16:05:54 -08006016 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006017}
6018
Eric Laurent555530a2017-02-07 18:17:24 -08006019void AudioFlinger::RecordThread::preExit()
6020{
6021 ALOGV(" preExit()");
6022 Mutex::Autolock _l(mLock);
6023 for (size_t i = 0; i < mTracks.size(); i++) {
6024 sp<RecordTrack> track = mTracks[i];
6025 track->invalidate();
6026 }
6027 mActiveTracks.clear();
6028 mStartStopCond.broadcast();
6029}
6030
Eric Laurent81784c32012-11-19 14:55:58 -08006031bool AudioFlinger::RecordThread::threadLoop()
6032{
Eric Laurent81784c32012-11-19 14:55:58 -08006033 nsecs_t lastWarning = 0;
6034
6035 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006036
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006037reacquire_wakelock:
6038 sp<RecordTrack> activeTrack;
6039 {
6040 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006041 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006042 }
6043
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006044 // used to request a deferred sleep, to be executed later while mutex is unlocked
6045 uint32_t sleepUs = 0;
6046
6047 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006048 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006049 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006050
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006051 // activeTracks accumulates a copy of a subset of mActiveTracks
6052 Vector< sp<RecordTrack> > activeTracks;
6053
Glenn Kasten735f45f2014-08-18 15:51:59 -07006054 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006055 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006056
Glenn Kasten735f45f2014-08-18 15:51:59 -07006057 // reference to a fast track which is about to be removed
6058 sp<RecordTrack> fastTrackToRemove;
6059
Eric Laurent81784c32012-11-19 14:55:58 -08006060 { // scope for mLock
6061 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006062
Eric Laurent021cf962014-05-13 10:18:14 -07006063 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006064
Eric Laurent000a4192014-01-29 15:17:32 -08006065 // check exitPending here because checkForNewParameters_l() and
6066 // checkForNewParameters_l() can temporarily release mLock
6067 if (exitPending()) {
6068 break;
6069 }
6070
Eric Laurent5c25d562016-07-13 17:17:45 -07006071 // sleep with mutex unlocked
6072 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006073 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006074 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6075 ATRACE_END();
6076 sleepUs = 0;
6077 continue;
6078 }
6079
Glenn Kasten2b806402013-11-20 16:37:38 -08006080 // if no active track(s), then standby and release wakelock
6081 size_t size = mActiveTracks.size();
6082 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006083 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006084 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006085 releaseWakeLock_l();
6086 ALOGV("RecordThread: loop stopping");
6087 // go to sleep
6088 mWaitWorkCV.wait(mLock);
6089 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006090 goto reacquire_wakelock;
6091 }
6092
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006093 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006094 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006095 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006096
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006097 activeTrack = mActiveTracks[i];
6098 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006099 if (activeTrack->isFastTrack()) {
6100 ALOG_ASSERT(fastTrackToRemove == 0);
6101 fastTrackToRemove = activeTrack;
6102 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006103 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006104 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006105 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006106 continue;
6107 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006108
6109 TrackBase::track_state activeTrackState = activeTrack->mState;
6110 switch (activeTrackState) {
6111
6112 case TrackBase::PAUSING:
6113 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006114 doBroadcast = true;
6115 size--;
6116 continue;
6117
6118 case TrackBase::STARTING_1:
6119 sleepUs = 10000;
6120 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006121 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006122 continue;
6123
6124 case TrackBase::STARTING_2:
6125 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006126 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006127 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006128 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006129 break;
6130
6131 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006132 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006133 break;
6134
6135 case TrackBase::IDLE:
6136 i++;
6137 continue;
6138
6139 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006140 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006141 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006142
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006143 activeTracks.add(activeTrack);
6144 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006145
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006146 if (activeTrack->isFastTrack()) {
6147 ALOG_ASSERT(!mFastTrackAvail);
6148 ALOG_ASSERT(fastTrack == 0);
6149 fastTrack = activeTrack;
6150 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006151 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006152
Andy Hungdae27702016-10-31 14:01:16 -07006153 mActiveTracks.updatePowerState(this);
6154
Eric Laurent5c25d562016-07-13 17:17:45 -07006155 if (allStopped) {
6156 standbyIfNotAlreadyInStandby();
6157 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006158 if (doBroadcast) {
6159 mStartStopCond.broadcast();
6160 }
6161
6162 // sleep if there are no active tracks to process
6163 if (activeTracks.size() == 0) {
6164 if (sleepUs == 0) {
6165 sleepUs = kRecordThreadSleepUs;
6166 }
6167 continue;
6168 }
6169 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006170
Eric Laurent81784c32012-11-19 14:55:58 -08006171 lockEffectChains_l(effectChains);
6172 }
6173
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006174 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006175
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006176 size_t size = effectChains.size();
6177 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006178 // thread mutex is not locked, but effect chain is locked
6179 effectChains[i]->process_l();
6180 }
6181
Glenn Kasten735f45f2014-08-18 15:51:59 -07006182 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006183 if (mFastCapture != 0) {
6184 FastCaptureStateQueue *sq = mFastCapture->sq();
6185 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006186 bool didModify = false;
6187 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006188 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6189 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6190 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6191 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6192 if (old == -1) {
6193 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6194 }
6195 }
6196 state->mCommand = FastCaptureState::READ_WRITE;
6197#if 0 // FIXME
6198 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006199 FastThreadDumpState::kSamplingNforLowRamDevice :
6200 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006201#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006202 didModify = true;
6203 }
6204 audio_track_cblk_t *cblkOld = state->mCblk;
6205 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6206 if (cblkNew != cblkOld) {
6207 state->mCblk = cblkNew;
6208 // block until acked if removing a fast track
6209 if (cblkOld != NULL) {
6210 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6211 }
6212 didModify = true;
6213 }
6214 sq->end(didModify);
6215 if (didModify) {
6216 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006217#if 0
6218 if (kUseFastCapture == FastCapture_Dynamic) {
6219 mNormalSource = mPipeSource;
6220 }
6221#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006222 }
6223 }
6224
Glenn Kasten735f45f2014-08-18 15:51:59 -07006225 // now run the fast track destructor with thread mutex unlocked
6226 fastTrackToRemove.clear();
6227
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006228 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6229 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6230 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6231 // If destination is non-contiguous, first read past the nominal end of buffer, then
6232 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006233
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006234 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006235 ssize_t framesRead;
6236
6237 // If an NBAIO source is present, use it to read the normal capture's data
6238 if (mPipeSource != 0) {
6239 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006240 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006241 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006242 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006243 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6244 // buffer size or at least for 20ms.
6245 size_t sleepFrames = max(
6246 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6247 if (framesRead <= (ssize_t) sleepFrames) {
6248 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6249 }
6250 if (framesRead < 0) {
6251 status_t status = (status_t) framesRead;
6252 switch (status) {
6253 case OVERRUN:
6254 ALOGW("overrun on read from pipe");
6255 framesRead = 0;
6256 break;
6257 case NEGOTIATE:
6258 ALOGE("re-negotiation is needed");
6259 framesRead = -1; // Will cause an attempt to recover.
6260 break;
6261 default:
6262 ALOGE("unknown error %d on read from pipe", status);
6263 break;
6264 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006265 }
6266 // otherwise use the HAL / AudioStreamIn directly
6267 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006268 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006269 size_t bytesRead;
6270 status_t result = mInput->stream->read(
6271 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006272 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006273 if (result < 0) {
6274 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006275 } else {
6276 framesRead = bytesRead / mFrameSize;
6277 }
6278 }
6279
Andy Hung3f0c9022016-01-15 17:49:46 -08006280 // Update server timestamp with server stats
6281 // systemTime() is optional if the hardware supports timestamps.
6282 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6283 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6284
6285 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006286 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006287 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006288 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006289 if (ret == NO_ERROR) {
6290 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6291 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6292 // Note: In general record buffers should tend to be empty in
6293 // a properly running pipeline.
6294 //
6295 // Also, it is not advantageous to call get_presentation_position during the read
6296 // as the read obtains a lock, preventing the timestamp call from executing.
6297 }
6298 }
6299 // Use this to track timestamp information
6300 // ALOGD("%s", mTimestamp.toString().c_str());
6301
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006302 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006303 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006304 // Force input into standby so that it tries to recover at next read attempt
6305 inputStandBy();
6306 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006307 }
6308 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006309 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006310 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006311 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006312
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006313 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006314 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006315 }
6316 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006317 {
6318 size_t part1 = mRsmpInFramesP2 - rear;
6319 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006320 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006321 (framesRead - part1) * mFrameSize);
6322 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006323 }
6324 rear = mRsmpInRear += framesRead;
6325
6326 size = activeTracks.size();
6327 // loop over each active track
6328 for (size_t i = 0; i < size; i++) {
6329 activeTrack = activeTracks[i];
6330
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006331 // skip fast tracks, as those are handled directly by FastCapture
6332 if (activeTrack->isFastTrack()) {
6333 continue;
6334 }
6335
Andy Hung73c02e42015-03-29 01:13:58 -07006336 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006337 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6338
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006339 enum {
6340 OVERRUN_UNKNOWN,
6341 OVERRUN_TRUE,
6342 OVERRUN_FALSE
6343 } overrun = OVERRUN_UNKNOWN;
6344
6345 // loop over getNextBuffer to handle circular sink
6346 for (;;) {
6347
6348 activeTrack->mSink.frameCount = ~0;
6349 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6350 size_t framesOut = activeTrack->mSink.frameCount;
6351 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6352
Andy Hung73c02e42015-03-29 01:13:58 -07006353 // check available frames and handle overrun conditions
6354 // if the record track isn't draining fast enough.
6355 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006356 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006357 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6358 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006359 overrun = OVERRUN_TRUE;
6360 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006361 if (framesOut == 0 || framesIn == 0) {
6362 break;
6363 }
6364
Andy Hung6770c6f2015-04-07 13:43:36 -07006365 // Don't allow framesOut to be larger than what is possible with resampling
6366 // from framesIn.
6367 // This isn't strictly necessary but helps limit buffer resizing in
6368 // RecordBufferConverter. TODO: remove when no longer needed.
6369 framesOut = min(framesOut,
6370 destinationFramesPossible(
6371 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006372 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6373 framesOut = activeTrack->mRecordBufferConverter->convert(
6374 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006375
6376 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6377 overrun = OVERRUN_FALSE;
6378 }
6379
6380 if (activeTrack->mFramesToDrop == 0) {
6381 if (framesOut > 0) {
6382 activeTrack->mSink.frameCount = framesOut;
6383 activeTrack->releaseBuffer(&activeTrack->mSink);
6384 }
6385 } else {
6386 // FIXME could do a partial drop of framesOut
6387 if (activeTrack->mFramesToDrop > 0) {
6388 activeTrack->mFramesToDrop -= framesOut;
6389 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006390 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006391 }
6392 } else {
6393 activeTrack->mFramesToDrop += framesOut;
6394 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6395 activeTrack->mSyncStartEvent->isCancelled()) {
6396 ALOGW("Synced record %s, session %d, trigger session %d",
6397 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6398 activeTrack->sessionId(),
6399 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006400 activeTrack->mSyncStartEvent->triggerSession() :
6401 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006402 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006403 }
6404 }
6405 }
6406
6407 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006408 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006409 }
6410 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006411
6412 switch (overrun) {
6413 case OVERRUN_TRUE:
6414 // client isn't retrieving buffers fast enough
6415 if (!activeTrack->setOverflow()) {
6416 nsecs_t now = systemTime();
6417 // FIXME should lastWarning per track?
6418 if ((now - lastWarning) > kWarningThrottleNs) {
6419 ALOGW("RecordThread: buffer overflow");
6420 lastWarning = now;
6421 }
6422 }
6423 break;
6424 case OVERRUN_FALSE:
6425 activeTrack->clearOverflow();
6426 break;
6427 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006428 break;
6429 }
6430
Andy Hung3f0c9022016-01-15 17:49:46 -08006431 // update frame information and push timestamp out
6432 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006433 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006434 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6435 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006436 }
6437
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006438unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006439 // enable changes in effect chain
6440 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006441 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006442 }
6443
Glenn Kasten93e471f2013-08-19 08:40:07 -07006444 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006445
6446 {
6447 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006448 for (size_t i = 0; i < mTracks.size(); i++) {
6449 sp<RecordTrack> track = mTracks[i];
6450 track->invalidate();
6451 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006452 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006453 mStartStopCond.broadcast();
6454 }
6455
6456 releaseWakeLock();
6457
6458 ALOGV("RecordThread %p exiting", this);
6459 return false;
6460}
6461
Glenn Kasten93e471f2013-08-19 08:40:07 -07006462void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006463{
6464 if (!mStandby) {
6465 inputStandBy();
6466 mStandby = true;
6467 }
6468}
6469
6470void AudioFlinger::RecordThread::inputStandBy()
6471{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006472 // Idle the fast capture if it's currently running
6473 if (mFastCapture != 0) {
6474 FastCaptureStateQueue *sq = mFastCapture->sq();
6475 FastCaptureState *state = sq->begin();
6476 if (!(state->mCommand & FastCaptureState::IDLE)) {
6477 state->mCommand = FastCaptureState::COLD_IDLE;
6478 state->mColdFutexAddr = &mFastCaptureFutex;
6479 state->mColdGen++;
6480 mFastCaptureFutex = 0;
6481 sq->end();
6482 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6483 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6484#if 0
6485 if (kUseFastCapture == FastCapture_Dynamic) {
6486 // FIXME
6487 }
6488#endif
6489#ifdef AUDIO_WATCHDOG
6490 // FIXME
6491#endif
6492 } else {
6493 sq->end(false /*didModify*/);
6494 }
6495 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006496 status_t result = mInput->stream->standby();
6497 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006498
6499 // If going into standby, flush the pipe source.
6500 if (mPipeSource.get() != nullptr) {
6501 const ssize_t flushed = mPipeSource->flush();
6502 if (flushed > 0) {
6503 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6504 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6505 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6506 }
6507 }
Eric Laurent81784c32012-11-19 14:55:58 -08006508}
6509
Glenn Kasten05997e22014-03-13 15:08:33 -07006510// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006511sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006512 const sp<AudioFlinger::Client>& client,
6513 uint32_t sampleRate,
6514 audio_format_t format,
6515 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006516 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006517 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006518 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006519 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006520 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006521 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006522 status_t *status,
6523 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006524{
Glenn Kasten74935e42013-12-19 08:56:45 -08006525 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006526 sp<RecordTrack> track;
6527 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006528 audio_input_flags_t inputFlags = mInput->flags;
6529
6530 // special case for FAST flag considered OK if fast capture is present
6531 if (hasFastCapture()) {
6532 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6533 }
6534
6535 // Check if requested flags are compatible with output stream flags
6536 if ((*flags & inputFlags) != *flags) {
6537 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6538 " input flags (%08x)",
6539 *flags, inputFlags);
6540 *flags = (audio_input_flags_t)(*flags & inputFlags);
6541 }
Eric Laurent81784c32012-11-19 14:55:58 -08006542
Glenn Kasten90e58b12013-07-31 16:16:02 -07006543 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006544 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006545 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006546 // we formerly checked for a callback handler (non-0 tid),
6547 // but that is no longer required for TRANSFER_OBTAIN mode
6548 //
Glenn Kasten74105912014-07-03 12:28:53 -07006549 // frame count is not specified, or is exactly the pipe depth
6550 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006551 // PCM data
6552 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006553 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006554 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006555 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006556 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006557 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006558 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006559 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006560 hasFastCapture() &&
6561 // there are sufficient fast track slots available
6562 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006563 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006564 // check compatibility with audio effects.
6565 Mutex::Autolock _l(mLock);
6566 // Do not accept FAST flag if the session has software effects
6567 sp<EffectChain> chain = getEffectChain_l(sessionId);
6568 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006569 audio_input_flags_t old = *flags;
6570 chain->checkInputFlagCompatibility(flags);
6571 if (old != *flags) {
6572 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6573 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006574 }
6575 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006576 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006577 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6578 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006579 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006580 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006581 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006582 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006583 frameCount, mFrameCount, mPipeFramesP2,
6584 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6585 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006586 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006587 }
6588 }
6589
6590 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006591 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006592 // fast track: frame count is exactly the pipe depth
6593 frameCount = mPipeFramesP2;
6594 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6595 *notificationFrames = mFrameCount;
6596 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006597 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6598 // or 20 ms if there is a fast capture
6599 // TODO This could be a roundupRatio inline, and const
6600 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6601 * sampleRate + mSampleRate - 1) / mSampleRate;
6602 // minimum number of notification periods is at least kMinNotifications,
6603 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6604 static const size_t kMinNotifications = 3;
6605 static const uint32_t kMinMs = 30;
6606 // TODO This could be a roundupRatio inline
6607 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6608 // TODO This could be a roundupRatio inline
6609 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6610 maxNotificationFrames;
6611 const size_t minFrameCount = maxNotificationFrames *
6612 max(kMinNotifications, minNotificationsByMs);
6613 frameCount = max(frameCount, minFrameCount);
6614 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6615 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006616 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006617 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006618 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006619
Glenn Kasten15e57982013-09-24 11:52:37 -07006620 lStatus = initCheck();
6621 if (lStatus != NO_ERROR) {
6622 ALOGE("createRecordTrack_l() audio driver not initialized");
6623 goto Exit;
6624 }
Eric Laurent81784c32012-11-19 14:55:58 -08006625
6626 { // scope for mLock
6627 Mutex::Autolock _l(mLock);
6628
6629 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006630 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006631 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006632
Glenn Kasten03003332013-08-06 15:40:54 -07006633 lStatus = track->initCheck();
6634 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006635 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006636 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006637 goto Exit;
6638 }
6639 mTracks.add(track);
6640
6641 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6642 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6643 mAudioFlinger->btNrecIsOff();
6644 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6645 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006646
Eric Laurent05067782016-06-01 18:27:28 -07006647 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006648 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6649 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6650 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08006651 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006652 }
Eric Laurent81784c32012-11-19 14:55:58 -08006653 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006654
Eric Laurent81784c32012-11-19 14:55:58 -08006655 lStatus = NO_ERROR;
6656
6657Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006658 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006659 return track;
6660}
6661
6662status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6663 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006664 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006665{
6666 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6667 sp<ThreadBase> strongMe = this;
6668 status_t status = NO_ERROR;
6669
6670 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006671 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006672 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006673 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006674 triggerSession,
6675 recordTrack->sessionId(),
6676 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006677 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006678 // Sync event can be cancelled by the trigger session if the track is not in a
6679 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006680 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006681 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006682 } else {
6683 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006684 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006685 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006686 }
6687 }
6688
6689 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006690 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006691 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006692 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6693 if (recordTrack->mState == TrackBase::PAUSING) {
6694 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006695 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006696 } else {
6697 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006698 }
6699 return status;
6700 }
6701
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006702 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6703 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6704 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006705 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006706 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006707 status_t status = NO_ERROR;
6708 if (recordTrack->isExternalTrack()) {
6709 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006710 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006711 mLock.lock();
6712 // FIXME should verify that recordTrack is still in mActiveTracks
6713 if (status != NO_ERROR) {
6714 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006715 recordTrack->clearSyncStartEvent();
6716 ALOGV("RecordThread::start error %d", status);
6717 return status;
6718 }
Eric Laurent81784c32012-11-19 14:55:58 -08006719 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006720 // Catch up with current buffer indices if thread is already running.
6721 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6722 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6723 // see previously buffered data before it called start(), but with greater risk of overrun.
6724
Andy Hung73c02e42015-03-29 01:13:58 -07006725 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006726 // clear any converter state as new data will be discontinuous
6727 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006728 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006729 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006730 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006731 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006732 ALOGV("Record failed to start");
6733 status = BAD_VALUE;
6734 goto startError;
6735 }
Eric Laurent81784c32012-11-19 14:55:58 -08006736 return status;
6737 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006738
Eric Laurent81784c32012-11-19 14:55:58 -08006739startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006740 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006741 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006742 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006743 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006744 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006745 return status;
6746}
6747
Eric Laurent81784c32012-11-19 14:55:58 -08006748void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6749{
6750 sp<SyncEvent> strongEvent = event.promote();
6751
6752 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006753 sp<RefBase> ptr = strongEvent->cookie().promote();
6754 if (ptr != 0) {
6755 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6756 recordTrack->handleSyncStartEvent(strongEvent);
6757 }
Eric Laurent81784c32012-11-19 14:55:58 -08006758 }
6759}
6760
Glenn Kastena8356f62013-07-25 14:37:52 -07006761bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006762 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006763 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006764 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006765 return false;
6766 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006767 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006768 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006769 // signal thread to stop
6770 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006771 // do not wait for mStartStopCond if exiting
6772 if (exitPending()) {
6773 return true;
6774 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006775 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006776 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006777 // if we have been restarted, recordTrack is in mActiveTracks here
6778 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006779 ALOGV("Record stopped OK");
6780 return true;
6781 }
6782 return false;
6783}
6784
Glenn Kasten0f11b512014-01-31 16:18:54 -08006785bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006786{
6787 return false;
6788}
6789
Glenn Kasten0f11b512014-01-31 16:18:54 -08006790status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006791{
6792#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6793 if (!isValidSyncEvent(event)) {
6794 return BAD_VALUE;
6795 }
6796
Glenn Kastend848eb42016-03-08 13:42:11 -08006797 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006798 status_t ret = NAME_NOT_FOUND;
6799
6800 Mutex::Autolock _l(mLock);
6801
6802 for (size_t i = 0; i < mTracks.size(); i++) {
6803 sp<RecordTrack> track = mTracks[i];
6804 if (eventSession == track->sessionId()) {
6805 (void) track->setSyncEvent(event);
6806 ret = NO_ERROR;
6807 }
6808 }
6809 return ret;
6810#else
6811 return BAD_VALUE;
6812#endif
6813}
6814
6815// destroyTrack_l() must be called with ThreadBase::mLock held
6816void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6817{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006818 track->terminate();
6819 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006820 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006821 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006822 removeTrack_l(track);
6823 }
6824}
6825
6826void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6827{
6828 mTracks.remove(track);
6829 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006830 if (track->isFastTrack()) {
6831 ALOG_ASSERT(!mFastTrackAvail);
6832 mFastTrackAvail = true;
6833 }
Eric Laurent81784c32012-11-19 14:55:58 -08006834}
6835
6836void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6837{
6838 dumpInternals(fd, args);
6839 dumpTracks(fd, args);
6840 dumpEffectChains(fd, args);
6841}
6842
6843void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6844{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006845 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006846
Glenn Kasten44182c22015-03-05 17:12:23 -08006847 dumpBase(fd, args);
6848
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006849 AudioStreamIn *input = mInput;
6850 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6851 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6852 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006853 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006854 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006855 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006856 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006857 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006858
Glenn Kasten2f90c512015-12-02 11:40:09 -08006859 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6860 // while we are dumping it. It may be inconsistent, but it won't mutate!
6861 // This is a large object so we place it on the heap.
6862 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6863 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6864 copy->dump(fd);
6865 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006866}
6867
Glenn Kasten0f11b512014-01-31 16:18:54 -08006868void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006869{
6870 const size_t SIZE = 256;
6871 char buffer[SIZE];
6872 String8 result;
6873
Marco Nelissenb2208842014-02-07 14:00:50 -08006874 size_t numtracks = mTracks.size();
6875 size_t numactive = mActiveTracks.size();
6876 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006877 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006878 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006879 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006880 RecordTrack::appendDumpHeader(result);
6881 for (size_t i = 0; i < numtracks ; ++i) {
6882 sp<RecordTrack> track = mTracks[i];
6883 if (track != 0) {
6884 bool active = mActiveTracks.indexOf(track) >= 0;
6885 if (active) {
6886 numactiveseen++;
6887 }
6888 track->dump(buffer, SIZE, active);
6889 result.append(buffer);
6890 }
Eric Laurent81784c32012-11-19 14:55:58 -08006891 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006892 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006893 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006894 }
6895
Marco Nelissenb2208842014-02-07 14:00:50 -08006896 if (numactiveseen != numactive) {
6897 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6898 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006899 result.append(buffer);
6900 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006901 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006902 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006903 if (mTracks.indexOf(track) < 0) {
6904 track->dump(buffer, SIZE, true);
6905 result.append(buffer);
6906 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006907 }
Eric Laurent81784c32012-11-19 14:55:58 -08006908
6909 }
6910 write(fd, result.string(), result.size());
6911}
6912
Andy Hung73c02e42015-03-29 01:13:58 -07006913
6914void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6915{
6916 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6917 RecordThread *recordThread = (RecordThread *) threadBase.get();
6918 mRsmpInFront = recordThread->mRsmpInRear;
6919 mRsmpInUnrel = 0;
6920}
6921
6922void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6923 size_t *framesAvailable, bool *hasOverrun)
6924{
6925 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6926 RecordThread *recordThread = (RecordThread *) threadBase.get();
6927 const int32_t rear = recordThread->mRsmpInRear;
6928 const int32_t front = mRsmpInFront;
6929 const ssize_t filled = rear - front;
6930
6931 size_t framesIn;
6932 bool overrun = false;
6933 if (filled < 0) {
6934 // should not happen, but treat like a massive overrun and re-sync
6935 framesIn = 0;
6936 mRsmpInFront = rear;
6937 overrun = true;
6938 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6939 framesIn = (size_t) filled;
6940 } else {
6941 // client is not keeping up with server, but give it latest data
6942 framesIn = recordThread->mRsmpInFrames;
6943 mRsmpInFront = /* front = */ rear - framesIn;
6944 overrun = true;
6945 }
6946 if (framesAvailable != NULL) {
6947 *framesAvailable = framesIn;
6948 }
6949 if (hasOverrun != NULL) {
6950 *hasOverrun = overrun;
6951 }
6952}
6953
Eric Laurent81784c32012-11-19 14:55:58 -08006954// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006955status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006956 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006957{
Andy Hung73c02e42015-03-29 01:13:58 -07006958 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006959 if (threadBase == 0) {
6960 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006961 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006962 return NOT_ENOUGH_DATA;
6963 }
6964 RecordThread *recordThread = (RecordThread *) threadBase.get();
6965 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006966 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006967 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006968 // FIXME should not be P2 (don't want to increase latency)
6969 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006970 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006971 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006972 front &= recordThread->mRsmpInFramesP2 - 1;
6973 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006974 if (part1 > (size_t) filled) {
6975 part1 = filled;
6976 }
6977 size_t ask = buffer->frameCount;
6978 ALOG_ASSERT(ask > 0);
6979 if (part1 > ask) {
6980 part1 = ask;
6981 }
6982 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006983 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006984 buffer->raw = NULL;
6985 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006986 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006987 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006988 }
6989
Andy Hung57446612015-04-19 23:56:46 -07006990 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006991 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006992 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006993 return NO_ERROR;
6994}
6995
6996// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006997void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6998 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006999{
Glenn Kasten85948432013-08-19 12:09:05 -07007000 size_t stepCount = buffer->frameCount;
7001 if (stepCount == 0) {
7002 return;
7003 }
Andy Hung73c02e42015-03-29 01:13:58 -07007004 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7005 mRsmpInUnrel -= stepCount;
7006 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007007 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007008 buffer->frameCount = 0;
7009}
7010
Andy Hung97a893e2015-03-29 01:03:07 -07007011
Eric Laurent10351942014-05-08 18:49:52 -07007012bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7013 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007014{
7015 bool reconfig = false;
7016
Eric Laurent10351942014-05-08 18:49:52 -07007017 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007018
Eric Laurent10351942014-05-08 18:49:52 -07007019 audio_format_t reqFormat = mFormat;
7020 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007021 // 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 -07007022 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7023
7024 AudioParameter param = AudioParameter(keyValuePair);
7025 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007026
7027 // scope for AutoPark extends to end of method
7028 AutoPark<FastCapture> park(mFastCapture);
7029
Eric Laurent10351942014-05-08 18:49:52 -07007030 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7031 // channel count change can be requested. Do we mandate the first client defines the
7032 // HAL sampling rate and channel count or do we allow changes on the fly?
7033 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7034 samplingRate = value;
7035 reconfig = true;
7036 }
7037 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007038 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007039 status = BAD_VALUE;
7040 } else {
7041 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007042 reconfig = true;
7043 }
Eric Laurent10351942014-05-08 18:49:52 -07007044 }
7045 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7046 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007047 if (!audio_is_input_channel(mask) ||
7048 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007049 status = BAD_VALUE;
7050 } else {
7051 channelMask = mask;
7052 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007053 }
Eric Laurent10351942014-05-08 18:49:52 -07007054 }
7055 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7056 // do not accept frame count changes if tracks are open as the track buffer
7057 // size depends on frame count and correct behavior would not be guaranteed
7058 // if frame count is changed after track creation
7059 if (mActiveTracks.size() > 0) {
7060 status = INVALID_OPERATION;
7061 } else {
7062 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007063 }
Eric Laurent10351942014-05-08 18:49:52 -07007064 }
7065 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7066 // forward device change to effects that have requested to be
7067 // aware of attached audio device.
7068 for (size_t i = 0; i < mEffectChains.size(); i++) {
7069 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007070 }
Eric Laurent81784c32012-11-19 14:55:58 -08007071
Eric Laurent10351942014-05-08 18:49:52 -07007072 // store input device and output device but do not forward output device to audio HAL.
7073 // Note that status is ignored by the caller for output device
7074 // (see AudioFlinger::setParameters()
7075 if (audio_is_output_devices(value)) {
7076 mOutDevice = value;
7077 status = BAD_VALUE;
7078 } else {
7079 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007080 if (value != AUDIO_DEVICE_NONE) {
7081 mPrevInDevice = value;
7082 }
Eric Laurent10351942014-05-08 18:49:52 -07007083 // disable AEC and NS if the device is a BT SCO headset supporting those
7084 // pre processings
7085 if (mTracks.size() > 0) {
7086 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7087 mAudioFlinger->btNrecIsOff();
7088 for (size_t i = 0; i < mTracks.size(); i++) {
7089 sp<RecordTrack> track = mTracks[i];
7090 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7091 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007092 }
7093 }
7094 }
Eric Laurent10351942014-05-08 18:49:52 -07007095 }
7096 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7097 mAudioSource != (audio_source_t)value) {
7098 // forward device change to effects that have requested to be
7099 // aware of attached audio device.
7100 for (size_t i = 0; i < mEffectChains.size(); i++) {
7101 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007102 }
Eric Laurent10351942014-05-08 18:49:52 -07007103 mAudioSource = (audio_source_t)value;
7104 }
Glenn Kastene198c362013-08-13 09:13:36 -07007105
Eric Laurent10351942014-05-08 18:49:52 -07007106 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007107 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007108 if (status == INVALID_OPERATION) {
7109 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007110 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007111 }
7112 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007113 if (status == BAD_VALUE) {
7114 uint32_t sRate;
7115 audio_channel_mask_t channelMask;
7116 audio_format_t format;
7117 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7118 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7119 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7120 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7121 status = NO_ERROR;
7122 }
Eric Laurent81784c32012-11-19 14:55:58 -08007123 }
Eric Laurent10351942014-05-08 18:49:52 -07007124 if (status == NO_ERROR) {
7125 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007126 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007127 }
7128 }
Eric Laurent81784c32012-11-19 14:55:58 -08007129 }
Eric Laurent10351942014-05-08 18:49:52 -07007130
Eric Laurent81784c32012-11-19 14:55:58 -08007131 return reconfig;
7132}
7133
7134String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7135{
Eric Laurent81784c32012-11-19 14:55:58 -08007136 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007137 if (initCheck() == NO_ERROR) {
7138 String8 out_s8;
7139 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7140 return out_s8;
7141 }
Eric Laurent81784c32012-11-19 14:55:58 -08007142 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007143 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007144}
7145
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007146void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007147 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7148
7149 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007150
7151 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007152 case AUDIO_INPUT_OPENED:
7153 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007154 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007155 desc->mChannelMask = mChannelMask;
7156 desc->mSamplingRate = mSampleRate;
7157 desc->mFormat = mFormat;
7158 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007159 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007160 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007161 break;
7162
Eric Laurent73e26b62015-04-27 16:55:58 -07007163 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007164 default:
7165 break;
7166 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007167 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007168}
7169
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007170void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007171{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007172 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7173 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007174 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007175 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007176 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007177 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7178 result = mInput->stream->getFrameSize(&mFrameSize);
7179 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7180 result = mInput->stream->getBufferSize(&mBufferSize);
7181 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007182 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007183 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007184 // 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 -07007185 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007186 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007187 // A larger value should allow more old data to be read after a track calls start(),
7188 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007189 //
7190 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007191 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007192 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007193 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007194 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007195
7196 // TODO optimize audio capture buffer sizes ...
7197 // Here we calculate the size of the sliding buffer used as a source
7198 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7199 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7200 // be better to have it derived from the pipe depth in the long term.
7201 // The current value is higher than necessary. However it should not add to latency.
7202
Glenn Kasten85948432013-08-19 12:09:05 -07007203 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007204 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7205 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7206 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007207
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007208 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7209 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007210}
7211
Glenn Kasten5f972c02014-01-13 09:59:31 -08007212uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007213{
7214 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007215 uint32_t result;
7216 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7217 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007218 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007219 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007220}
7221
Eric Laurent4c415062016-06-17 16:14:16 -07007222// hasAudioSession_l() must be called with ThreadBase::mLock held
7223uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007224{
Eric Laurent81784c32012-11-19 14:55:58 -08007225 uint32_t result = 0;
7226 if (getEffectChain_l(sessionId) != 0) {
7227 result = EFFECT_SESSION;
7228 }
7229
7230 for (size_t i = 0; i < mTracks.size(); ++i) {
7231 if (sessionId == mTracks[i]->sessionId()) {
7232 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007233 if (mTracks[i]->isFastTrack()) {
7234 result |= FAST_SESSION;
7235 }
Eric Laurent81784c32012-11-19 14:55:58 -08007236 break;
7237 }
7238 }
7239
7240 return result;
7241}
7242
Glenn Kastend848eb42016-03-08 13:42:11 -08007243KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007244{
Glenn Kastend848eb42016-03-08 13:42:11 -08007245 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007246 Mutex::Autolock _l(mLock);
7247 for (size_t j = 0; j < mTracks.size(); ++j) {
7248 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007249 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007250 if (ids.indexOfKey(sessionId) < 0) {
7251 ids.add(sessionId, true);
7252 }
7253 }
7254 return ids;
7255}
7256
7257AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7258{
7259 Mutex::Autolock _l(mLock);
7260 AudioStreamIn *input = mInput;
7261 mInput = NULL;
7262 return input;
7263}
7264
7265// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007266sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007267{
7268 if (mInput == NULL) {
7269 return NULL;
7270 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007271 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007272}
7273
7274status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7275{
7276 // only one chain per input thread
7277 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007278 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007279 return INVALID_OPERATION;
7280 }
7281 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007282 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007283 chain->setInBuffer(NULL);
7284 chain->setOutBuffer(NULL);
7285
7286 checkSuspendOnAddEffectChain_l(chain);
7287
Eric Laurent1b928682014-10-02 19:41:47 -07007288 // make sure enabled pre processing effects state is communicated to the HAL as we
7289 // just moved them to a new input stream.
7290 chain->syncHalEffectsState();
7291
Eric Laurent81784c32012-11-19 14:55:58 -08007292 mEffectChains.add(chain);
7293
7294 return NO_ERROR;
7295}
7296
7297size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7298{
7299 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7300 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007301 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007302 chain.get(), mEffectChains.size(), this);
7303 if (mEffectChains.size() == 1) {
7304 mEffectChains.removeAt(0);
7305 }
7306 return 0;
7307}
7308
Eric Laurent1c333e22014-05-20 10:48:17 -07007309status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7310 audio_patch_handle_t *handle)
7311{
7312 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007313
7314 // store new device and send to effects
7315 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007316 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007317 for (size_t i = 0; i < mEffectChains.size(); i++) {
7318 mEffectChains[i]->setDevice_l(mInDevice);
7319 }
7320
7321 // disable AEC and NS if the device is a BT SCO headset supporting those
7322 // pre processings
7323 if (mTracks.size() > 0) {
7324 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7325 mAudioFlinger->btNrecIsOff();
7326 for (size_t i = 0; i < mTracks.size(); i++) {
7327 sp<RecordTrack> track = mTracks[i];
7328 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7329 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7330 }
7331 }
7332
7333 // store new source and send to effects
7334 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7335 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007336 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007337 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007338 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007339 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007340
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007341 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007342 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7343 status = hwDevice->createAudioPatch(patch->num_sources,
7344 patch->sources,
7345 patch->num_sinks,
7346 patch->sinks,
7347 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007348 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007349 char *address;
7350 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7351 address = audio_device_address_to_parameter(
7352 patch->sources[0].ext.device.type,
7353 patch->sources[0].ext.device.address);
7354 } else {
7355 address = (char *)calloc(1, 1);
7356 }
7357 AudioParameter param = AudioParameter(String8(address));
7358 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007359 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007360 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007361 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007362 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007363 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007364 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007365 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007366
Eric Laurente8726fe2015-06-26 09:39:24 -07007367 if (mInDevice != mPrevInDevice) {
7368 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7369 mPrevInDevice = mInDevice;
7370 }
Eric Laurent296fb132015-05-01 11:38:42 -07007371
Eric Laurent1c333e22014-05-20 10:48:17 -07007372 return status;
7373}
7374
7375status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7376{
7377 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007378
7379 mInDevice = AUDIO_DEVICE_NONE;
7380
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007381 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007382 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7383 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007384 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007385 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007386 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007387 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007388 }
7389 return status;
7390}
7391
Eric Laurent83b88082014-06-20 18:31:16 -07007392void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7393{
7394 Mutex::Autolock _l(mLock);
7395 mTracks.add(record);
7396}
7397
7398void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7399{
7400 Mutex::Autolock _l(mLock);
7401 destroyTrack_l(record);
7402}
7403
7404void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7405{
7406 ThreadBase::getAudioPortConfig(config);
7407 config->role = AUDIO_PORT_ROLE_SINK;
7408 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7409 config->ext.mix.usecase.source = mAudioSource;
7410}
Eric Laurent1c333e22014-05-20 10:48:17 -07007411
Eric Laurent6acd1d42017-01-04 14:23:29 -08007412// ----------------------------------------------------------------------------
7413// Mmap
7414// ----------------------------------------------------------------------------
7415
7416AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7417 : mThread(thread)
7418{
7419}
7420
7421AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7422{
7423 MmapThread *thread = mThread.get();
7424 // clear our strong reference before disconnecting the thread: the last strong reference
7425 // will be removed when closeInput/closeOutput is executed upono call from audio policy manager
7426 // and the thread removed from mMMapThreads list causing the thread destruction.
7427 mThread.clear();
7428 if (thread != nullptr) {
7429 thread->disconnect();
7430 }
7431}
7432
7433status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7434 struct audio_mmap_buffer_info *info)
7435{
7436 if (mThread == 0) {
7437 return NO_INIT;
7438 }
7439 return mThread->createMmapBuffer(minSizeFrames, info);
7440}
7441
7442status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7443{
7444 if (mThread == 0) {
7445 return NO_INIT;
7446 }
7447 return mThread->getMmapPosition(position);
7448}
7449
7450status_t AudioFlinger::MmapThreadHandle::start(const MmapStreamInterface::Client& client, audio_port_handle_t *handle)
7451
7452{
7453 if (mThread == 0) {
7454 return NO_INIT;
7455 }
7456 return mThread->start(client, handle);
7457}
7458
7459status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7460{
7461 if (mThread == 0) {
7462 return NO_INIT;
7463 }
7464 return mThread->stop(handle);
7465}
7466
7467
7468AudioFlinger::MmapThread::MmapThread(
7469 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7470 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7471 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7472 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
7473 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev)
7474{
7475 readHalParameters_l();
7476}
7477
7478AudioFlinger::MmapThread::~MmapThread()
7479{
7480}
7481
7482void AudioFlinger::MmapThread::onFirstRef()
7483{
7484 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7485}
7486
7487void AudioFlinger::MmapThread::disconnect()
7488{
7489 for (const sp<MmapTrack> &t : mActiveTracks) {
7490 stop(t->portId());
7491 }
7492 // this will cause the destruction of this thread.
7493 if (isOutput()) {
7494 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7495 } else {
7496 AudioSystem::releaseInput(mId, mSessionId);
7497 }
7498}
7499
7500
7501void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7502 audio_stream_type_t streamType __unused,
7503 audio_session_t sessionId,
7504 const sp<MmapStreamCallback>& callback,
7505 audio_port_handle_t portId)
7506{
7507 mAttr = *attr;
7508 mSessionId = sessionId;
7509 mCallback = callback;
7510 mPortId = portId;
7511}
7512
7513status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7514 struct audio_mmap_buffer_info *info)
7515{
7516 if (mHalStream == 0) {
7517 return NO_INIT;
7518 }
7519 return mHalStream->createMmapBuffer(minSizeFrames, info);
7520}
7521
7522status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7523{
7524 if (mHalStream == 0) {
7525 return NO_INIT;
7526 }
7527 return mHalStream->getMmapPosition(position);
7528}
7529
7530status_t AudioFlinger::MmapThread::start(const MmapStreamInterface::Client& client,
7531 audio_port_handle_t *handle)
7532{
7533 ALOGV("%s clientUid %d", __FUNCTION__, client.clientUid);
7534 if (mHalStream == 0) {
7535 return NO_INIT;
7536 }
7537
7538 status_t ret;
7539 audio_session_t sessionId;
7540 audio_port_handle_t portId;
7541
7542 if (mActiveTracks.size() == 0) {
7543 // for the first track, reuse portId and session allocated when the stream was opened
7544 mHalStream->start();
7545 portId = mPortId;
7546 sessionId = mSessionId;
7547 } else {
7548 // for other tracks than first one, get a new port ID from APM.
7549 sessionId = (audio_session_t)mAudioFlinger->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
7550 audio_io_handle_t io;
7551 if (isOutput()) {
7552 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7553 config.sample_rate = mSampleRate;
7554 config.channel_mask = mChannelMask;
7555 config.format = mFormat;
7556 audio_stream_type_t stream = streamType();
7557 audio_output_flags_t flags =
7558 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
7559 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7560 sessionId,
7561 &stream,
7562 client.clientUid,
7563 &config,
7564 flags,
7565 AUDIO_PORT_HANDLE_NONE,
7566 &portId);
7567 } else {
7568 audio_config_base_t config;
7569 config.sample_rate = mSampleRate;
7570 config.channel_mask = mChannelMask;
7571 config.format = mFormat;
7572 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7573 sessionId,
7574 client.clientPid,
7575 client.clientUid,
7576 &config,
7577 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7578 AUDIO_PORT_HANDLE_NONE,
7579 &portId);
7580 }
7581 // APM should not chose a different input or output stream for the same set of attributes
7582 // and audo configuration
7583 if (ret != NO_ERROR || io != mId) {
7584 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7585 __FUNCTION__, ret, io, mId);
7586 return BAD_VALUE;
7587 }
7588 }
7589
7590 if (isOutput()) {
7591 ret = AudioSystem::startOutput(mId, streamType(), sessionId);
7592 } else {
7593 ret = AudioSystem::startInput(mId, sessionId);
7594 }
7595
7596 // abort if start is rejected by audio policy manager
7597 if (ret != NO_ERROR) {
7598 if (mActiveTracks.size() != 0) {
7599 if (isOutput()) {
7600 AudioSystem::releaseOutput(mId, streamType(), sessionId);
7601 } else {
7602 AudioSystem::releaseInput(mId, sessionId);
7603 }
7604 }
7605 return PERMISSION_DENIED;
7606 }
7607
7608 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, sessionId,
7609 client.clientUid, portId);
7610
7611 mActiveTracks.add(track);
7612 sp<EffectChain> chain = getEffectChain_l(sessionId);
7613 if (chain != 0) {
7614 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7615 chain->incTrackCnt();
7616 chain->incActiveTrackCnt();
7617 }
7618
7619 *handle = portId;
7620
7621 broadcast_l();
7622
7623 ALOGV("%s DONE handle %d", __FUNCTION__, portId);
7624
7625 return NO_ERROR;
7626}
7627
7628status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7629{
7630
7631 ALOGV("%s handle %d", __FUNCTION__, handle);
7632
7633 if (mHalStream == 0) {
7634 return NO_INIT;
7635 }
7636
7637 sp<MmapTrack> track;
7638 for (const sp<MmapTrack> &t : mActiveTracks) {
7639 if (handle == t->portId()) {
7640 track = t;
7641 break;
7642 }
7643 }
7644 if (track == 0) {
7645 return BAD_VALUE;
7646 }
7647
7648 mActiveTracks.remove(track);
7649
7650 if (isOutput()) {
7651 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
7652 if (mActiveTracks.size() != 0) {
7653 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
7654 }
7655 } else {
7656 AudioSystem::stopInput(mId, track->sessionId());
7657 if (mActiveTracks.size() != 0) {
7658 AudioSystem::releaseInput(mId, track->sessionId());
7659 }
7660 }
7661
7662 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7663 if (chain != 0) {
7664 chain->decActiveTrackCnt();
7665 chain->decTrackCnt();
7666 }
7667
7668 broadcast_l();
7669
7670 if (mActiveTracks.size() == 0) {
7671 mHalStream->stop();
7672 }
7673 return NO_ERROR;
7674}
7675
7676
7677void AudioFlinger::MmapThread::readHalParameters_l()
7678{
7679 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7680 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7681 mFormat = mHALFormat;
7682 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7683 result = mHalStream->getFrameSize(&mFrameSize);
7684 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7685 result = mHalStream->getBufferSize(&mBufferSize);
7686 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7687 mFrameCount = mBufferSize / mFrameSize;
7688}
7689
7690bool AudioFlinger::MmapThread::threadLoop()
7691{
7692 acquireWakeLock();
7693
7694 checkSilentMode_l();
7695
7696 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7697
7698 while (!exitPending())
7699 {
7700 Mutex::Autolock _l(mLock);
7701 Vector< sp<EffectChain> > effectChains;
7702
7703 if (mSignalPending) {
7704 // A signal was raised while we were unlocked
7705 mSignalPending = false;
7706 } else {
7707 if (mConfigEvents.isEmpty()) {
7708 // we're about to wait, flush the binder command buffer
7709 IPCThreadState::self()->flushCommands();
7710
7711 if (exitPending()) {
7712 break;
7713 }
7714
7715 bool wakelockReleased = false;
7716 if (mActiveTracks.size() == 0) {
7717 releaseWakeLock_l();
7718 wakelockReleased = true;
7719 }
7720 // wait until we have something to do...
7721 ALOGV("%s going to sleep", myName.string());
7722 mWaitWorkCV.wait(mLock);
7723 ALOGV("%s waking up", myName.string());
7724 if (wakelockReleased) {
7725 acquireWakeLock_l();
7726 }
7727
7728 checkSilentMode_l();
7729
7730 continue;
7731 }
7732 }
7733
7734 processConfigEvents_l();
7735
7736 processVolume_l();
7737
7738 checkInvalidTracks_l();
7739
7740 mActiveTracks.updatePowerState(this);
7741
7742 lockEffectChains_l(effectChains);
7743 for (size_t i = 0; i < effectChains.size(); i ++) {
7744 effectChains[i]->process_l();
7745 }
7746 // enable changes in effect chain
7747 unlockEffectChains(effectChains);
7748 // Effect chains will be actually deleted here if they were removed from
7749 // mEffectChains list during mixing or effects processing
7750 }
7751
7752 threadLoop_exit();
7753
7754 if (!mStandby) {
7755 threadLoop_standby();
7756 mStandby = true;
7757 }
7758
7759 releaseWakeLock();
7760
7761 ALOGV("Thread %p type %d exiting", this, mType);
7762 return false;
7763}
7764
7765// checkForNewParameter_l() must be called with ThreadBase::mLock held
7766bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7767 status_t& status)
7768{
7769 AudioParameter param = AudioParameter(keyValuePair);
7770 int value;
7771 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7772 // forward device change to effects that have requested to be
7773 // aware of attached audio device.
7774 if (value != AUDIO_DEVICE_NONE) {
7775 mOutDevice = value;
7776 for (size_t i = 0; i < mEffectChains.size(); i++) {
7777 mEffectChains[i]->setDevice_l(mOutDevice);
7778 }
7779 }
7780 }
7781 status = mHalStream->setParameters(keyValuePair);
7782
7783 return false;
7784}
7785
7786String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7787{
7788 Mutex::Autolock _l(mLock);
7789 String8 out_s8;
7790 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7791 return out_s8;
7792 }
7793 return String8();
7794}
7795
7796void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7797 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7798
7799 desc->mIoHandle = mId;
7800
7801 switch (event) {
7802 case AUDIO_INPUT_OPENED:
7803 case AUDIO_INPUT_CONFIG_CHANGED:
7804 case AUDIO_OUTPUT_OPENED:
7805 case AUDIO_OUTPUT_CONFIG_CHANGED:
7806 desc->mPatch = mPatch;
7807 desc->mChannelMask = mChannelMask;
7808 desc->mSamplingRate = mSampleRate;
7809 desc->mFormat = mFormat;
7810 desc->mFrameCount = mFrameCount;
7811 desc->mFrameCountHAL = mFrameCount;
7812 desc->mLatency = 0;
7813 break;
7814
7815 case AUDIO_INPUT_CLOSED:
7816 case AUDIO_OUTPUT_CLOSED:
7817 default:
7818 break;
7819 }
7820 mAudioFlinger->ioConfigChanged(event, desc, pid);
7821}
7822
7823status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7824 audio_patch_handle_t *handle)
7825{
7826 status_t status = NO_ERROR;
7827
7828 // store new device and send to effects
7829 audio_devices_t type = AUDIO_DEVICE_NONE;
7830 audio_port_handle_t deviceId;
7831 if (isOutput()) {
7832 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7833 type |= patch->sinks[i].ext.device.type;
7834 }
7835 deviceId = patch->sinks[0].id;
7836 } else {
7837 type = patch->sources[0].ext.device.type;
7838 deviceId = patch->sources[0].id;
7839 }
7840
7841 for (size_t i = 0; i < mEffectChains.size(); i++) {
7842 mEffectChains[i]->setDevice_l(type);
7843 }
7844
7845 if (isOutput()) {
7846 mOutDevice = type;
7847 } else {
7848 mInDevice = type;
7849 // store new source and send to effects
7850 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7851 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7852 for (size_t i = 0; i < mEffectChains.size(); i++) {
7853 mEffectChains[i]->setAudioSource_l(mAudioSource);
7854 }
7855 }
7856 }
7857
7858 if (mAudioHwDev->supportsAudioPatches()) {
7859 status = mHalDevice->createAudioPatch(patch->num_sources,
7860 patch->sources,
7861 patch->num_sinks,
7862 patch->sinks,
7863 handle);
7864 } else {
7865 char *address;
7866 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7867 //FIXME: we only support address on first sink with HAL version < 3.0
7868 address = audio_device_address_to_parameter(
7869 patch->sinks[0].ext.device.type,
7870 patch->sinks[0].ext.device.address);
7871 } else {
7872 address = (char *)calloc(1, 1);
7873 }
7874 AudioParameter param = AudioParameter(String8(address));
7875 free(address);
7876 param.addInt(String8(AudioParameter::keyRouting), (int)type);
7877 if (!isOutput()) {
7878 param.addInt(String8(AudioParameter::keyInputSource),
7879 (int)patch->sinks[0].ext.mix.usecase.source);
7880 }
7881 status = mHalStream->setParameters(param.toString());
7882 *handle = AUDIO_PATCH_HANDLE_NONE;
7883 }
7884
7885 if (isOutput() && mPrevOutDevice != mOutDevice) {
7886 mPrevOutDevice = type;
7887 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
7888 if (mCallback != 0) {
7889 mCallback->onRoutingChanged(deviceId);
7890 }
7891 }
7892 if (!isOutput() && mPrevInDevice != mInDevice) {
7893 mPrevInDevice = type;
7894 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7895 if (mCallback != 0) {
7896 mCallback->onRoutingChanged(deviceId);
7897 }
7898 }
7899 return status;
7900}
7901
7902status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7903{
7904 status_t status = NO_ERROR;
7905
7906 mInDevice = AUDIO_DEVICE_NONE;
7907
7908 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
7909 supportsAudioPatches : false;
7910
7911 if (supportsAudioPatches) {
7912 status = mHalDevice->releaseAudioPatch(handle);
7913 } else {
7914 AudioParameter param;
7915 param.addInt(String8(AudioParameter::keyRouting), 0);
7916 status = mHalStream->setParameters(param.toString());
7917 }
7918 return status;
7919}
7920
7921void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
7922{
7923 ThreadBase::getAudioPortConfig(config);
7924 if (isOutput()) {
7925 config->role = AUDIO_PORT_ROLE_SOURCE;
7926 config->ext.mix.hw_module = mAudioHwDev->handle();
7927 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
7928 } else {
7929 config->role = AUDIO_PORT_ROLE_SINK;
7930 config->ext.mix.hw_module = mAudioHwDev->handle();
7931 config->ext.mix.usecase.source = mAudioSource;
7932 }
7933}
7934
7935status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
7936{
7937 audio_session_t session = chain->sessionId();
7938
7939 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
7940 // Attach all tracks with same session ID to this chain.
7941 // indicate all active tracks in the chain
7942 for (const sp<MmapTrack> &track : mActiveTracks) {
7943 if (session == track->sessionId()) {
7944 chain->incTrackCnt();
7945 chain->incActiveTrackCnt();
7946 }
7947 }
7948
7949 chain->setThread(this);
7950 chain->setInBuffer(nullptr);
7951 chain->setOutBuffer(nullptr);
7952 chain->syncHalEffectsState();
7953
7954 mEffectChains.add(chain);
7955 checkSuspendOnAddEffectChain_l(chain);
7956 return NO_ERROR;
7957}
7958
7959size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
7960{
7961 audio_session_t session = chain->sessionId();
7962
7963 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
7964
7965 for (size_t i = 0; i < mEffectChains.size(); i++) {
7966 if (chain == mEffectChains[i]) {
7967 mEffectChains.removeAt(i);
7968 // detach all active tracks from the chain
7969 // detach all tracks with same session ID from this chain
7970 for (const sp<MmapTrack> &track : mActiveTracks) {
7971 if (session == track->sessionId()) {
7972 chain->decActiveTrackCnt();
7973 chain->decTrackCnt();
7974 }
7975 }
7976 break;
7977 }
7978 }
7979 return mEffectChains.size();
7980}
7981
7982// hasAudioSession_l() must be called with ThreadBase::mLock held
7983uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
7984{
7985 uint32_t result = 0;
7986 if (getEffectChain_l(sessionId) != 0) {
7987 result = EFFECT_SESSION;
7988 }
7989
7990 for (size_t i = 0; i < mActiveTracks.size(); i++) {
7991 sp<MmapTrack> track = mActiveTracks[i];
7992 if (sessionId == track->sessionId()) {
7993 result |= TRACK_SESSION;
7994 if (track->isFastTrack()) {
7995 result |= FAST_SESSION;
7996 }
7997 break;
7998 }
7999 }
8000
8001 return result;
8002}
8003
8004void AudioFlinger::MmapThread::threadLoop_standby()
8005{
8006 mHalStream->standby();
8007}
8008
8009void AudioFlinger::MmapThread::threadLoop_exit()
8010{
8011 if (mCallback != 0) {
8012 mCallback->onTearDown();
8013 }
8014}
8015
8016status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8017{
8018 return BAD_VALUE;
8019}
8020
8021bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8022{
8023 return false;
8024}
8025
8026status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8027 const effect_descriptor_t *desc, audio_session_t sessionId)
8028{
8029 // No global effect sessions on mmap threads
8030 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8031 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8032 desc->name, mThreadName);
8033 return BAD_VALUE;
8034 }
8035
8036 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8037 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8038 desc->name);
8039 return BAD_VALUE;
8040 }
8041 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
8042 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap thread",
8043 desc->name);
8044 return BAD_VALUE;
8045 }
8046
8047 // Only allow effects without processing load or latency
8048 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8049 return BAD_VALUE;
8050 }
8051
8052 return NO_ERROR;
8053
8054}
8055
8056void AudioFlinger::MmapThread::checkInvalidTracks_l()
8057{
8058 for (const sp<MmapTrack> &track : mActiveTracks) {
8059 if (track->isInvalid()) {
8060 if (mCallback != 0) {
8061 mCallback->onTearDown();
8062 }
8063 break;
8064 }
8065 }
8066}
8067
8068void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8069{
8070 dumpInternals(fd, args);
8071 dumpTracks(fd, args);
8072 dumpEffectChains(fd, args);
8073}
8074
8075void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8076{
8077 dprintf(fd, "\nMmap thread %p:\n", this);
8078
8079 dumpBase(fd, args);
8080
8081 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8082 mAttr.content_type, mAttr.usage, mAttr.source);
8083 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8084 if (mActiveTracks.size() == 0) {
8085 dprintf(fd, " No active clients\n");
8086 }
8087}
8088
8089void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8090{
8091 const size_t SIZE = 256;
8092 char buffer[SIZE];
8093 String8 result;
8094
8095 size_t numtracks = mActiveTracks.size();
8096 dprintf(fd, " %zu Tracks", numtracks);
8097 if (numtracks) {
8098 MmapTrack::appendDumpHeader(result);
8099 for (size_t i = 0; i < numtracks ; ++i) {
8100 sp<MmapTrack> track = mActiveTracks[i];
8101 track->dump(buffer, SIZE);
8102 result.append(buffer);
8103 }
8104 } else {
8105 dprintf(fd, "\n");
8106 }
8107 write(fd, result.string(), result.size());
8108}
8109
8110AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8111 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8112 AudioHwDevice *hwDev, AudioStreamOut *output,
8113 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8114 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8115 mStreamType(AUDIO_STREAM_MUSIC),
8116 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8117{
8118 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8119 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8120 mMasterVolume = audioFlinger->masterVolume_l();
8121 mMasterMute = audioFlinger->masterMute_l();
8122 if (mAudioHwDev) {
8123 if (mAudioHwDev->canSetMasterVolume()) {
8124 mMasterVolume = 1.0;
8125 }
8126
8127 if (mAudioHwDev->canSetMasterMute()) {
8128 mMasterMute = false;
8129 }
8130 }
8131}
8132
8133void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8134 audio_stream_type_t streamType,
8135 audio_session_t sessionId,
8136 const sp<MmapStreamCallback>& callback,
8137 audio_port_handle_t portId)
8138{
8139 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8140 mStreamType = streamType;
8141}
8142
8143AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8144{
8145 Mutex::Autolock _l(mLock);
8146 AudioStreamOut *output = mOutput;
8147 mOutput = NULL;
8148 return output;
8149}
8150
8151void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8152{
8153 Mutex::Autolock _l(mLock);
8154 // Don't apply master volume in SW if our HAL can do it for us.
8155 if (mAudioHwDev &&
8156 mAudioHwDev->canSetMasterVolume()) {
8157 mMasterVolume = 1.0;
8158 } else {
8159 mMasterVolume = value;
8160 }
8161}
8162
8163void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8164{
8165 Mutex::Autolock _l(mLock);
8166 // Don't apply master mute in SW if our HAL can do it for us.
8167 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8168 mMasterMute = false;
8169 } else {
8170 mMasterMute = muted;
8171 }
8172}
8173
8174void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8175{
8176 Mutex::Autolock _l(mLock);
8177 if (stream == mStreamType) {
8178 mStreamVolume = value;
8179 broadcast_l();
8180 }
8181}
8182
8183float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8184{
8185 Mutex::Autolock _l(mLock);
8186 if (stream == mStreamType) {
8187 return mStreamVolume;
8188 }
8189 return 0.0f;
8190}
8191
8192void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8193{
8194 Mutex::Autolock _l(mLock);
8195 if (stream == mStreamType) {
8196 mStreamMute= muted;
8197 broadcast_l();
8198 }
8199}
8200
8201void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8202{
8203 Mutex::Autolock _l(mLock);
8204 if (streamType == mStreamType) {
8205 for (const sp<MmapTrack> &track : mActiveTracks) {
8206 track->invalidate();
8207 }
8208 broadcast_l();
8209 }
8210}
8211
8212void AudioFlinger::MmapPlaybackThread::processVolume_l()
8213{
8214 float volume;
8215
8216 if (mMasterMute || mStreamMute) {
8217 volume = 0;
8218 } else {
8219 volume = mMasterVolume * mStreamVolume;
8220 }
8221
8222 if (volume != mHalVolFloat) {
8223 mHalVolFloat = volume;
8224
8225 // Convert volumes from float to 8.24
8226 uint32_t vol = (uint32_t)(volume * (1 << 24));
8227
8228 // Delegate volume control to effect in track effect chain if needed
8229 // only one effect chain can be present on DirectOutputThread, so if
8230 // there is one, the track is connected to it
8231 if (!mEffectChains.isEmpty()) {
8232 mEffectChains[0]->setVolume_l(&vol, &vol);
8233 volume = (float)vol / (1 << 24);
8234 }
8235
8236 mOutput->stream->setVolume(volume, volume);
8237
8238 if (mCallback != 0) {
8239 int channelCount;
8240 if (isOutput()) {
8241 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8242 } else {
8243 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8244 }
8245 Vector<float> values;
8246 for (int i = 0; i < channelCount; i++) {
8247 values.add(volume);
8248 }
8249 mCallback->onVolumeChanged(mChannelMask, values);
8250 }
8251 }
8252}
8253
8254void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8255{
8256 if (!mMasterMute) {
8257 char value[PROPERTY_VALUE_MAX];
8258 if (property_get("ro.audio.silent", value, "0") > 0) {
8259 char *endptr;
8260 unsigned long ul = strtoul(value, &endptr, 0);
8261 if (*endptr == '\0' && ul != 0) {
8262 ALOGD("Silence is golden");
8263 // The setprop command will not allow a property to be changed after
8264 // the first time it is set, so we don't have to worry about un-muting.
8265 setMasterMute_l(true);
8266 }
8267 }
8268 }
8269}
8270
8271void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8272{
8273 MmapThread::dumpInternals(fd, args);
8274
8275 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n", mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
8276 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8277}
8278
8279AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8280 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8281 AudioHwDevice *hwDev, AudioStreamIn *input,
8282 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8283 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8284 mInput(input)
8285{
8286 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8287 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8288}
8289
8290AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8291{
8292 Mutex::Autolock _l(mLock);
8293 AudioStreamIn *input = mInput;
8294 mInput = NULL;
8295 return input;
8296}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008297} // namespace android