blob: b10e42c6cc94b61ad339bd3d5a90cbd7968061f9 [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 }
Andy Hung10cbff12017-02-21 17:30:14 -08003066
3067 const int64_t waitNs = computeWaitTimeNs_l();
3068 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3069 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3070 if (status == TIMED_OUT) {
3071 mSignalPending = true; // if timeout recheck everything
3072 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003073 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003074 if (released) {
3075 acquireWakeLock_l();
3076 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003077 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3078 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003079
3080 continue;
3081 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003082 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003083 isSuspended()) {
3084 // put audio hardware into standby after short delay
3085 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003086
3087 threadLoop_standby();
3088
3089 mStandby = true;
3090 }
3091
3092 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3093 // we're about to wait, flush the binder command buffer
3094 IPCThreadState::self()->flushCommands();
3095
3096 clearOutputTracks();
3097
3098 if (exitPending()) {
3099 break;
3100 }
3101
3102 releaseWakeLock_l();
3103 // wait until we have something to do...
3104 ALOGV("%s going to sleep", myName.string());
3105 mWaitWorkCV.wait(mLock);
3106 ALOGV("%s waking up", myName.string());
3107 acquireWakeLock_l();
3108
3109 mMixerStatus = MIXER_IDLE;
3110 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3111 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003113 checkSilentMode_l();
3114
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003115 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3116 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003117 if (mType == MIXER) {
3118 sleepTimeShift = 0;
3119 }
3120
3121 continue;
3122 }
3123 }
Eric Laurent81784c32012-11-19 14:55:58 -08003124 // mMixerStatusIgnoringFastTracks is also updated internally
3125 mMixerStatus = prepareTracks_l(&tracksToRemove);
3126
Andy Hungdae27702016-10-31 14:01:16 -07003127 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003128
Eric Laurent81784c32012-11-19 14:55:58 -08003129 // prevent any changes in effect chain list and in each effect chain
3130 // during mixing and effect process as the audio buffers could be deleted
3131 // or modified if an effect is created or deleted
3132 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003133 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003134
Eric Laurentbfb1b832013-01-07 09:53:42 -08003135 if (mBytesRemaining == 0) {
3136 mCurrentWriteLength = 0;
3137 if (mMixerStatus == MIXER_TRACKS_READY) {
3138 // threadLoop_mix() sets mCurrentWriteLength
3139 threadLoop_mix();
3140 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3141 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003142 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003143 // must be written to HAL
3144 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003145 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003146 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003147 }
3148 }
Andy Hung98ef9782014-03-04 14:46:50 -08003149 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003150 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003151 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3152 // or mSinkBuffer (if there are no effects).
3153 //
3154 // This is done pre-effects computation; if effects change to
3155 // support higher precision, this needs to move.
3156 //
3157 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003158 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003159 if (mMixerBufferValid) {
3160 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3161 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3162
Andy Hung2ddee192015-12-18 17:34:44 -08003163 // mono blend occurs for mixer threads only (not direct or offloaded)
3164 // and is handled here if we're going directly to the sink.
3165 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003166 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3167 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003168 }
3169
Andy Hung98ef9782014-03-04 14:46:50 -08003170 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3171 mNormalFrameCount * mChannelCount);
3172 }
3173
Eric Laurentbfb1b832013-01-07 09:53:42 -08003174 mBytesRemaining = mCurrentWriteLength;
3175 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003176 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3177 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3178 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3179 mBytesWritten += mBytesRemaining;
3180 mFramesWritten += framesRemaining;
3181 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003182 mBytesRemaining = 0;
3183 }
Eric Laurent81784c32012-11-19 14:55:58 -08003184
Eric Laurentbfb1b832013-01-07 09:53:42 -08003185 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003186 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003187 for (size_t i = 0; i < effectChains.size(); i ++) {
3188 effectChains[i]->process_l();
3189 }
Eric Laurent81784c32012-11-19 14:55:58 -08003190 }
3191 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003192 // Process effect chains for offloaded thread even if no audio
3193 // was read from audio track: process only updates effect state
3194 // and thus does have to be synchronized with audio writes but may have
3195 // to be called while waiting for async write callback
3196 if (mType == OFFLOAD) {
3197 for (size_t i = 0; i < effectChains.size(); i ++) {
3198 effectChains[i]->process_l();
3199 }
3200 }
Eric Laurent81784c32012-11-19 14:55:58 -08003201
Andy Hung98ef9782014-03-04 14:46:50 -08003202 // Only if the Effects buffer is enabled and there is data in the
3203 // Effects buffer (buffer valid), we need to
3204 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003205 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003206 if (mEffectBufferValid) {
3207 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003208
3209 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003210 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3211 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003212 }
3213
Andy Hung98ef9782014-03-04 14:46:50 -08003214 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3215 mNormalFrameCount * mChannelCount);
3216 }
3217
Eric Laurent81784c32012-11-19 14:55:58 -08003218 // enable changes in effect chain
3219 unlockEffectChains(effectChains);
3220
Eric Laurentbfb1b832013-01-07 09:53:42 -08003221 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003222 // mSleepTimeUs == 0 means we must write to audio hardware
3223 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003224 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003225 // We save lastWriteFinished here, as previousLastWriteFinished,
3226 // for throttling. On thread start, previousLastWriteFinished will be
3227 // set to -1, which properly results in no throttling after the first write.
3228 nsecs_t previousLastWriteFinished = lastWriteFinished;
3229 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003230 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003231 // FIXME rewrite to reduce number of system calls
3232 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003233 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003234 lastWriteFinished = systemTime();
3235 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003236 if (ret < 0) {
3237 mBytesRemaining = 0;
3238 } else {
3239 mBytesWritten += ret;
3240 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003241 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003242 }
3243 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3244 (mMixerStatus == MIXER_DRAIN_ALL)) {
3245 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003246 }
Andy Hung08fb1742015-05-31 23:22:10 -07003247 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003248 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003249 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003250 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003251 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003252 ATRACE_NAME("underrun");
3253 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003254 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003255 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003256 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003257 }
Andy Hung08fb1742015-05-31 23:22:10 -07003258
3259 if (mThreadThrottle
3260 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3261 && ret > 0) { // we wrote something
3262 // Limit MixerThread data processing to no more than twice the
3263 // expected processing rate.
3264 //
3265 // This helps prevent underruns with NuPlayer and other applications
3266 // which may set up buffers that are close to the minimum size, or use
3267 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3268 //
3269 // The throttle smooths out sudden large data drains from the device,
3270 // e.g. when it comes out of standby, which often causes problems with
3271 // (1) mixer threads without a fast mixer (which has its own warm-up)
3272 // (2) minimum buffer sized tracks (even if the track is full,
3273 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003274 //
3275 // Total time spent in last processing cycle equals time spent in
3276 // 1. threadLoop_write, as well as time spent in
3277 // 2. threadLoop_mix (significant for heavy mixing, especially
3278 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003279
Andy Hung69488c42016-05-16 18:43:33 -07003280 // it's OK if deltaMs is an overestimate.
3281 const int32_t deltaMs =
3282 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003283 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3284 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3285 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003286 // notify of throttle start on verbose log
3287 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3288 "mixer(%p) throttle begin:"
3289 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003290 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003291 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003292 // Throttle must be attributed to the previous mixer loop's write time
3293 // to allow back-to-back throttling.
3294 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003295 } else {
3296 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3297 if (diff > 0) {
3298 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003299 // but prevent spamming for bluetooth
3300 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3301 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003302 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3303 }
Andy Hung08fb1742015-05-31 23:22:10 -07003304 }
3305 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003306 }
Eric Laurent81784c32012-11-19 14:55:58 -08003307
Eric Laurentbfb1b832013-01-07 09:53:42 -08003308 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003309 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003310 Mutex::Autolock _l(mLock);
3311 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3312 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003313 }
Glenn Kastene7754022014-10-31 12:11:26 -07003314 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003315 }
Eric Laurent81784c32012-11-19 14:55:58 -08003316 }
3317
3318 // Finally let go of removed track(s), without the lock held
3319 // since we can't guarantee the destructors won't acquire that
3320 // same lock. This will also mutate and push a new fast mixer state.
3321 threadLoop_removeTracks(tracksToRemove);
3322 tracksToRemove.clear();
3323
3324 // FIXME I don't understand the need for this here;
3325 // it was in the original code but maybe the
3326 // assignment in saveOutputTracks() makes this unnecessary?
3327 clearOutputTracks();
3328
3329 // Effect chains will be actually deleted here if they were removed from
3330 // mEffectChains list during mixing or effects processing
3331 effectChains.clear();
3332
3333 // FIXME Note that the above .clear() is no longer necessary since effectChains
3334 // is now local to this block, but will keep it for now (at least until merge done).
3335 }
3336
Eric Laurentbfb1b832013-01-07 09:53:42 -08003337 threadLoop_exit();
3338
Eric Laurentcf817a22014-08-04 20:36:31 -07003339 if (!mStandby) {
3340 threadLoop_standby();
3341 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003342 }
3343
3344 releaseWakeLock();
3345
3346 ALOGV("Thread %p type %d exiting", this, mType);
3347 return false;
3348}
3349
Eric Laurentbfb1b832013-01-07 09:53:42 -08003350// removeTracks_l() must be called with ThreadBase::mLock held
3351void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3352{
3353 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003354 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003355 for (size_t i=0 ; i<count ; i++) {
3356 const sp<Track>& track = tracksToRemove.itemAt(i);
3357 mActiveTracks.remove(track);
3358 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3359 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3360 if (chain != 0) {
3361 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3362 track->sessionId());
3363 chain->decActiveTrackCnt();
3364 }
3365 if (track->isTerminated()) {
3366 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003367 } else { // inactive but not terminated
3368 char buffer[256];
3369 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3370 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003371 }
3372 }
3373 }
3374
3375}
Eric Laurent81784c32012-11-19 14:55:58 -08003376
Eric Laurentaccc1472013-09-20 09:36:34 -07003377status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3378{
3379 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003380 ExtendedTimestamp ets;
3381 status_t status = mNormalSink->getTimestamp(ets);
3382 if (status == NO_ERROR) {
3383 status = ets.getBestTimestamp(&timestamp);
3384 }
3385 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003386 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003387 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003388 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003389 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003390 timestamp.mPosition = (uint32_t)position64;
3391 return NO_ERROR;
3392 }
3393 }
3394 return INVALID_OPERATION;
3395}
Eric Laurent1c333e22014-05-20 10:48:17 -07003396
Eric Laurent054d9d32015-04-24 08:48:48 -07003397status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3398 audio_patch_handle_t *handle)
3399{
Andy Hungf60abce2016-08-26 11:37:54 -07003400 status_t status;
3401 if (property_get_bool("af.patch_park", false /* default_value */)) {
3402 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3403 // or if HAL does not properly lock against access.
3404 AutoPark<FastMixer> park(mFastMixer);
3405 status = PlaybackThread::createAudioPatch_l(patch, handle);
3406 } else {
3407 status = PlaybackThread::createAudioPatch_l(patch, handle);
3408 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003409 return status;
3410}
3411
Eric Laurent1c333e22014-05-20 10:48:17 -07003412status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3413 audio_patch_handle_t *handle)
3414{
3415 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003416
3417 // store new device and send to effects
3418 audio_devices_t type = AUDIO_DEVICE_NONE;
3419 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3420 type |= patch->sinks[i].ext.device.type;
3421 }
3422
3423#ifdef ADD_BATTERY_DATA
3424 // when changing the audio output device, call addBatteryData to notify
3425 // the change
3426 if (mOutDevice != type) {
3427 uint32_t params = 0;
3428 // check whether speaker is on
3429 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3430 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003431 }
3432
Eric Laurent054d9d32015-04-24 08:48:48 -07003433 audio_devices_t deviceWithoutSpeaker
3434 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3435 // check if any other device (except speaker) is on
3436 if (type & deviceWithoutSpeaker) {
3437 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3438 }
3439
3440 if (params != 0) {
3441 addBatteryData(params);
3442 }
3443 }
3444#endif
3445
3446 for (size_t i = 0; i < mEffectChains.size(); i++) {
3447 mEffectChains[i]->setDevice_l(type);
3448 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003449
3450 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3451 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3452 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003453 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003454 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003455
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003456 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003457 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3458 status = hwDevice->createAudioPatch(patch->num_sources,
3459 patch->sources,
3460 patch->num_sinks,
3461 patch->sinks,
3462 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003463 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003464 char *address;
3465 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3466 //FIXME: we only support address on first sink with HAL version < 3.0
3467 address = audio_device_address_to_parameter(
3468 patch->sinks[0].ext.device.type,
3469 patch->sinks[0].ext.device.address);
3470 } else {
3471 address = (char *)calloc(1, 1);
3472 }
3473 AudioParameter param = AudioParameter(String8(address));
3474 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003475 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003476 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003477 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003478 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003479 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003480 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003481 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3482 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003483 return status;
3484}
3485
Eric Laurent054d9d32015-04-24 08:48:48 -07003486status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3487{
Andy Hungf60abce2016-08-26 11:37:54 -07003488 status_t status;
3489 if (property_get_bool("af.patch_park", false /* default_value */)) {
3490 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3491 // or if HAL does not properly lock against access.
3492 AutoPark<FastMixer> park(mFastMixer);
3493 status = PlaybackThread::releaseAudioPatch_l(handle);
3494 } else {
3495 status = PlaybackThread::releaseAudioPatch_l(handle);
3496 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003497 return status;
3498}
3499
Eric Laurent1c333e22014-05-20 10:48:17 -07003500status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3501{
3502 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003503
3504 mOutDevice = AUDIO_DEVICE_NONE;
3505
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003506 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003507 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3508 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003509 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003510 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003511 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003512 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003513 }
3514 return status;
3515}
3516
Eric Laurent83b88082014-06-20 18:31:16 -07003517void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3518{
3519 Mutex::Autolock _l(mLock);
3520 mTracks.add(track);
3521}
3522
3523void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3524{
3525 Mutex::Autolock _l(mLock);
3526 destroyTrack_l(track);
3527}
3528
3529void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3530{
3531 ThreadBase::getAudioPortConfig(config);
3532 config->role = AUDIO_PORT_ROLE_SOURCE;
3533 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3534 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3535}
3536
Eric Laurent81784c32012-11-19 14:55:58 -08003537// ----------------------------------------------------------------------------
3538
3539AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003540 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3541 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003542 // mAudioMixer below
3543 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003544 mFastMixerFutex(0),
3545 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003546 // mOutputSink below
3547 // mPipeSink below
3548 // mNormalSink below
3549{
3550 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003551 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3552 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003553 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3554 mNormalFrameCount);
3555 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3556
Andy Hungfbfc3952015-01-15 13:33:51 -08003557 if (type == DUPLICATING) {
3558 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3559 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3560 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3561 return;
3562 }
Eric Laurent81784c32012-11-19 14:55:58 -08003563 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003564 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003565 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003566 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003567#if !LOG_NDEBUG
3568 ssize_t index =
3569#else
3570 (void)
3571#endif
3572 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003573 ALOG_ASSERT(index == 0);
3574
3575 // initialize fast mixer depending on configuration
3576 bool initFastMixer;
3577 switch (kUseFastMixer) {
3578 case FastMixer_Never:
3579 initFastMixer = false;
3580 break;
3581 case FastMixer_Always:
3582 initFastMixer = true;
3583 break;
3584 case FastMixer_Static:
3585 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003586 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3587 // where the period is less than an experimentally determined threshold that can be
3588 // scheduled reliably with CFS. However, the BT A2DP HAL is
3589 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3590 initFastMixer = mFrameCount < mNormalFrameCount
3591 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003592 break;
3593 }
Andy Hungfda69402017-02-15 14:33:12 -08003594 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3595 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3596 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003597 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003598 audio_format_t fastMixerFormat;
3599 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3600 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3601 } else {
3602 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3603 }
3604 if (mFormat != fastMixerFormat) {
3605 // change our Sink format to accept our intermediate precision
3606 mFormat = fastMixerFormat;
3607 free(mSinkBuffer);
3608 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3609 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3610 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3611 }
Eric Laurent81784c32012-11-19 14:55:58 -08003612
3613 // create a MonoPipe to connect our submix to FastMixer
3614 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003615#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003616 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003617#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003618 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003619 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003620 format.mFormat = fastMixerFormat;
3621 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3622
Eric Laurent81784c32012-11-19 14:55:58 -08003623 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3624 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3625 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3626 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3627 const NBAIO_Format offers[1] = {format};
3628 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003629#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003630 ssize_t index =
3631#else
3632 (void)
3633#endif
3634 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003635 ALOG_ASSERT(index == 0);
3636 monoPipe->setAvgFrames((mScreenState & 1) ?
3637 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3638 mPipeSink = monoPipe;
3639
Glenn Kasten46909e72013-02-26 09:20:22 -08003640#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003641 if (mTeeSinkOutputEnabled) {
3642 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003643 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3644 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003645 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003646 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003647 ALOG_ASSERT(index == 0);
3648 mTeeSink = teeSink;
3649 PipeReader *teeSource = new PipeReader(*teeSink);
3650 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003651 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003652 ALOG_ASSERT(index == 0);
3653 mTeeSource = teeSource;
3654 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003655#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003656
3657 // create fast mixer and configure it initially with just one fast track for our submix
3658 mFastMixer = new FastMixer();
3659 FastMixerStateQueue *sq = mFastMixer->sq();
3660#ifdef STATE_QUEUE_DUMP
3661 sq->setObserverDump(&mStateQueueObserverDump);
3662 sq->setMutatorDump(&mStateQueueMutatorDump);
3663#endif
3664 FastMixerState *state = sq->begin();
3665 FastTrack *fastTrack = &state->mFastTracks[0];
3666 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3667 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3668 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003669 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3670 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003671 fastTrack->mGeneration++;
3672 state->mFastTracksGen++;
3673 state->mTrackMask = 1;
3674 // fast mixer will use the HAL output sink
3675 state->mOutputSink = mOutputSink.get();
3676 state->mOutputSinkGen++;
3677 state->mFrameCount = mFrameCount;
3678 state->mCommand = FastMixerState::COLD_IDLE;
3679 // already done in constructor initialization list
3680 //mFastMixerFutex = 0;
3681 state->mColdFutexAddr = &mFastMixerFutex;
3682 state->mColdGen++;
3683 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003684#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003685 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003686#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003687 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3688 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003689 sq->end();
3690 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3691
3692 // start the fast mixer
3693 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3694 pid_t tid = mFastMixer->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08003695 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003696 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003697
3698#ifdef AUDIO_WATCHDOG
3699 // create and start the watchdog
3700 mAudioWatchdog = new AudioWatchdog();
3701 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3702 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3703 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003704 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003705#endif
3706
Eric Laurent81784c32012-11-19 14:55:58 -08003707 }
3708
3709 switch (kUseFastMixer) {
3710 case FastMixer_Never:
3711 case FastMixer_Dynamic:
3712 mNormalSink = mOutputSink;
3713 break;
3714 case FastMixer_Always:
3715 mNormalSink = mPipeSink;
3716 break;
3717 case FastMixer_Static:
3718 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3719 break;
3720 }
3721}
3722
3723AudioFlinger::MixerThread::~MixerThread()
3724{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003725 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003726 FastMixerStateQueue *sq = mFastMixer->sq();
3727 FastMixerState *state = sq->begin();
3728 if (state->mCommand == FastMixerState::COLD_IDLE) {
3729 int32_t old = android_atomic_inc(&mFastMixerFutex);
3730 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003731 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003732 }
3733 }
3734 state->mCommand = FastMixerState::EXIT;
3735 sq->end();
3736 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3737 mFastMixer->join();
3738 // Though the fast mixer thread has exited, it's state queue is still valid.
3739 // We'll use that extract the final state which contains one remaining fast track
3740 // corresponding to our sub-mix.
3741 state = sq->begin();
3742 ALOG_ASSERT(state->mTrackMask == 1);
3743 FastTrack *fastTrack = &state->mFastTracks[0];
3744 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3745 delete fastTrack->mBufferProvider;
3746 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003747 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003748#ifdef AUDIO_WATCHDOG
3749 if (mAudioWatchdog != 0) {
3750 mAudioWatchdog->requestExit();
3751 mAudioWatchdog->requestExitAndWait();
3752 mAudioWatchdog.clear();
3753 }
3754#endif
3755 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003756 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003757 delete mAudioMixer;
3758}
3759
3760
3761uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3762{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003763 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003764 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3765 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3766 }
3767 return latency;
3768}
3769
3770
3771void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3772{
3773 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3774}
3775
Eric Laurentbfb1b832013-01-07 09:53:42 -08003776ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003777{
3778 // FIXME we should only do one push per cycle; confirm this is true
3779 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003780 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003781 FastMixerStateQueue *sq = mFastMixer->sq();
3782 FastMixerState *state = sq->begin();
3783 if (state->mCommand != FastMixerState::MIX_WRITE &&
3784 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3785 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003786
3787 // FIXME workaround for first HAL write being CPU bound on some devices
3788 ATRACE_BEGIN("write");
3789 mOutput->write((char *)mSinkBuffer, 0);
3790 ATRACE_END();
3791
Eric Laurent81784c32012-11-19 14:55:58 -08003792 int32_t old = android_atomic_inc(&mFastMixerFutex);
3793 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003794 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003795 }
3796#ifdef AUDIO_WATCHDOG
3797 if (mAudioWatchdog != 0) {
3798 mAudioWatchdog->resume();
3799 }
3800#endif
3801 }
3802 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003803#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003804 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003805 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003806#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003807 sq->end();
3808 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3809 if (kUseFastMixer == FastMixer_Dynamic) {
3810 mNormalSink = mPipeSink;
3811 }
3812 } else {
3813 sq->end(false /*didModify*/);
3814 }
3815 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003816 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003817}
3818
3819void AudioFlinger::MixerThread::threadLoop_standby()
3820{
3821 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003822 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003823 FastMixerStateQueue *sq = mFastMixer->sq();
3824 FastMixerState *state = sq->begin();
3825 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003826 // Report any frames trapped in the Monopipe
3827 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3828 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3829 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3830 "monoPipeWritten:%lld monoPipeLeft:%lld",
3831 (long long)mFramesWritten, (long long)mSuspendedFrames,
3832 (long long)mPipeSink->framesWritten(), pipeFrames);
3833 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3834
Eric Laurent81784c32012-11-19 14:55:58 -08003835 state->mCommand = FastMixerState::COLD_IDLE;
3836 state->mColdFutexAddr = &mFastMixerFutex;
3837 state->mColdGen++;
3838 mFastMixerFutex = 0;
3839 sq->end();
3840 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3841 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3842 if (kUseFastMixer == FastMixer_Dynamic) {
3843 mNormalSink = mOutputSink;
3844 }
3845#ifdef AUDIO_WATCHDOG
3846 if (mAudioWatchdog != 0) {
3847 mAudioWatchdog->pause();
3848 }
3849#endif
3850 } else {
3851 sq->end(false /*didModify*/);
3852 }
3853 }
3854 PlaybackThread::threadLoop_standby();
3855}
3856
Eric Laurentbfb1b832013-01-07 09:53:42 -08003857bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3858{
3859 return false;
3860}
3861
3862bool AudioFlinger::PlaybackThread::shouldStandby_l()
3863{
3864 return !mStandby;
3865}
3866
3867bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3868{
3869 Mutex::Autolock _l(mLock);
3870 return waitingAsyncCallback_l();
3871}
3872
Eric Laurent81784c32012-11-19 14:55:58 -08003873// shared by MIXER and DIRECT, overridden by DUPLICATING
3874void AudioFlinger::PlaybackThread::threadLoop_standby()
3875{
3876 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003877 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003878 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003879 // discard any pending drain or write ack by incrementing sequence
3880 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3881 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003882 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003883 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3884 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003885 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003886 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003887}
3888
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003889void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3890{
3891 ALOGV("signal playback thread");
3892 broadcast_l();
3893}
3894
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003895void AudioFlinger::PlaybackThread::onAsyncError()
3896{
3897 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3898 invalidateTracks((audio_stream_type_t)i);
3899 }
3900}
3901
Eric Laurent81784c32012-11-19 14:55:58 -08003902void AudioFlinger::MixerThread::threadLoop_mix()
3903{
Eric Laurent81784c32012-11-19 14:55:58 -08003904 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003905 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003906 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003907 // increase sleep time progressively when application underrun condition clears.
3908 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3909 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3910 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003911 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003912 sleepTimeShift--;
3913 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003914 mSleepTimeUs = 0;
3915 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003916 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003917
Eric Laurent81784c32012-11-19 14:55:58 -08003918}
3919
3920void AudioFlinger::MixerThread::threadLoop_sleepTime()
3921{
3922 // If no tracks are ready, sleep once for the duration of an output
3923 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003924 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003925 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003926 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3927 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3928 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003929 }
3930 // reduce sleep time in case of consecutive application underruns to avoid
3931 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3932 // duration we would end up writing less data than needed by the audio HAL if
3933 // the condition persists.
3934 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3935 sleepTimeShift++;
3936 }
3937 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003938 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003939 }
3940 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003941 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3942 // before effects processing or output.
3943 if (mMixerBufferValid) {
3944 memset(mMixerBuffer, 0, mMixerBufferSize);
3945 } else {
3946 memset(mSinkBuffer, 0, mSinkBufferSize);
3947 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003948 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003949 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3950 "anticipated start");
3951 }
3952 // TODO add standby time extension fct of effect tail
3953}
3954
3955// prepareTracks_l() must be called with ThreadBase::mLock held
3956AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3957 Vector< sp<Track> > *tracksToRemove)
3958{
3959
3960 mixer_state mixerStatus = MIXER_IDLE;
3961 // find out which tracks need to be processed
3962 size_t count = mActiveTracks.size();
3963 size_t mixedTracks = 0;
3964 size_t tracksWithEffect = 0;
3965 // counts only _active_ fast tracks
3966 size_t fastTracks = 0;
3967 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3968
3969 float masterVolume = mMasterVolume;
3970 bool masterMute = mMasterMute;
3971
3972 if (masterMute) {
3973 masterVolume = 0;
3974 }
3975 // Delegate master volume control to effect in output mix effect chain if needed
3976 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3977 if (chain != 0) {
3978 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3979 chain->setVolume_l(&v, &v);
3980 masterVolume = (float)((v + (1 << 23)) >> 24);
3981 chain.clear();
3982 }
3983
3984 // prepare a new state to push
3985 FastMixerStateQueue *sq = NULL;
3986 FastMixerState *state = NULL;
3987 bool didModify = false;
3988 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08003989 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003990 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003991 sq = mFastMixer->sq();
3992 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08003993 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08003994 }
3995
Andy Hung69aed5f2014-02-25 17:24:40 -08003996 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003997 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003998
Eric Laurent81784c32012-11-19 14:55:58 -08003999 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004000 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004001
4002 // this const just means the local variable doesn't change
4003 Track* const track = t.get();
4004
4005 // process fast tracks
4006 if (track->isFastTrack()) {
4007
4008 // It's theoretically possible (though unlikely) for a fast track to be created
4009 // and then removed within the same normal mix cycle. This is not a problem, as
4010 // the track never becomes active so it's fast mixer slot is never touched.
4011 // The converse, of removing an (active) track and then creating a new track
4012 // at the identical fast mixer slot within the same normal mix cycle,
4013 // is impossible because the slot isn't marked available until the end of each cycle.
4014 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004015 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004016 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4017 FastTrack *fastTrack = &state->mFastTracks[j];
4018
4019 // Determine whether the track is currently in underrun condition,
4020 // and whether it had a recent underrun.
4021 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4022 FastTrackUnderruns underruns = ftDump->mUnderruns;
4023 uint32_t recentFull = (underruns.mBitFields.mFull -
4024 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4025 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4026 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4027 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4028 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4029 uint32_t recentUnderruns = recentPartial + recentEmpty;
4030 track->mObservedUnderruns = underruns;
4031 // don't count underruns that occur while stopping or pausing
4032 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004033 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4034 recentUnderruns > 0) {
4035 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4036 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004037 } else {
4038 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004039 }
4040
4041 // This is similar to the state machine for normal tracks,
4042 // with a few modifications for fast tracks.
4043 bool isActive = true;
4044 switch (track->mState) {
4045 case TrackBase::STOPPING_1:
4046 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004047 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004048 track->mState = TrackBase::STOPPING_2;
4049 }
4050 break;
4051 case TrackBase::PAUSING:
4052 // ramp down is not yet implemented
4053 track->setPaused();
4054 break;
4055 case TrackBase::RESUMING:
4056 // ramp up is not yet implemented
4057 track->mState = TrackBase::ACTIVE;
4058 break;
4059 case TrackBase::ACTIVE:
4060 if (recentFull > 0 || recentPartial > 0) {
4061 // track has provided at least some frames recently: reset retry count
4062 track->mRetryCount = kMaxTrackRetries;
4063 }
4064 if (recentUnderruns == 0) {
4065 // no recent underruns: stay active
4066 break;
4067 }
4068 // there has recently been an underrun of some kind
4069 if (track->sharedBuffer() == 0) {
4070 // were any of the recent underruns "empty" (no frames available)?
4071 if (recentEmpty == 0) {
4072 // no, then ignore the partial underruns as they are allowed indefinitely
4073 break;
4074 }
4075 // there has recently been an "empty" underrun: decrement the retry counter
4076 if (--(track->mRetryCount) > 0) {
4077 break;
4078 }
4079 // indicate to client process that the track was disabled because of underrun;
4080 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004081 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004082 // remove from active list, but state remains ACTIVE [confusing but true]
4083 isActive = false;
4084 break;
4085 }
4086 // fall through
4087 case TrackBase::STOPPING_2:
4088 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004089 case TrackBase::STOPPED:
4090 case TrackBase::FLUSHED: // flush() while active
4091 // Check for presentation complete if track is inactive
4092 // We have consumed all the buffers of this track.
4093 // This would be incomplete if we auto-paused on underrun
4094 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004095 uint32_t latency = 0;
4096 status_t result = mOutput->stream->getLatency(&latency);
4097 ALOGE_IF(result != OK,
4098 "Error when retrieving output stream latency: %d", result);
4099 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004100 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004101 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4102 // track stays in active list until presentation is complete
4103 break;
4104 }
4105 }
4106 if (track->isStopping_2()) {
4107 track->mState = TrackBase::STOPPED;
4108 }
4109 if (track->isStopped()) {
4110 // Can't reset directly, as fast mixer is still polling this track
4111 // track->reset();
4112 // So instead mark this track as needing to be reset after push with ack
4113 resetMask |= 1 << i;
4114 }
4115 isActive = false;
4116 break;
4117 case TrackBase::IDLE:
4118 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004119 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004120 }
4121
4122 if (isActive) {
4123 // was it previously inactive?
4124 if (!(state->mTrackMask & (1 << j))) {
4125 ExtendedAudioBufferProvider *eabp = track;
4126 VolumeProvider *vp = track;
4127 fastTrack->mBufferProvider = eabp;
4128 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004129 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004130 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004131 fastTrack->mGeneration++;
4132 state->mTrackMask |= 1 << j;
4133 didModify = true;
4134 // no acknowledgement required for newly active tracks
4135 }
4136 // cache the combined master volume and stream type volume for fast mixer; this
4137 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004138 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004139 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004140 track->mCachedVolume = masterVolume
4141 * mStreamTypes[track->streamType()].volume
4142 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004143 ++fastTracks;
4144 } else {
4145 // was it previously active?
4146 if (state->mTrackMask & (1 << j)) {
4147 fastTrack->mBufferProvider = NULL;
4148 fastTrack->mGeneration++;
4149 state->mTrackMask &= ~(1 << j);
4150 didModify = true;
4151 // If any fast tracks were removed, we must wait for acknowledgement
4152 // because we're about to decrement the last sp<> on those tracks.
4153 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4154 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004155 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4156 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4157 j, track->mState, state->mTrackMask, recentUnderruns,
4158 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004159 }
4160 tracksToRemove->add(track);
4161 // Avoids a misleading display in dumpsys
4162 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4163 }
4164 continue;
4165 }
4166
4167 { // local variable scope to avoid goto warning
4168
4169 audio_track_cblk_t* cblk = track->cblk();
4170
4171 // The first time a track is added we wait
4172 // for all its buffers to be filled before processing it
4173 int name = track->name();
4174 // make sure that we have enough frames to mix one full buffer.
4175 // enforce this condition only once to enable draining the buffer in case the client
4176 // app does not call stop() and relies on underrun to stop:
4177 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4178 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004179 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004180 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004181 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004182
4183 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004184 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004185 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4186 // add frames already consumed but not yet released by the resampler
4187 // because mAudioTrackServerProxy->framesReady() will include these frames
4188 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4189
Eric Laurent81784c32012-11-19 14:55:58 -08004190 uint32_t minFrames = 1;
4191 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4192 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004193 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004194 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004195
4196 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004197 if (ATRACE_ENABLED()) {
4198 // I wish we had formatted trace names
4199 char traceName[16];
4200 strcpy(traceName, "nRdy");
4201 int name = track->name();
4202 if (AudioMixer::TRACK0 <= name &&
4203 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4204 name -= AudioMixer::TRACK0;
4205 traceName[4] = (name / 10) + '0';
4206 traceName[5] = (name % 10) + '0';
4207 } else {
4208 traceName[4] = '?';
4209 traceName[5] = '?';
4210 }
4211 traceName[6] = '\0';
4212 ATRACE_INT(traceName, framesReady);
4213 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004214 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004215 !track->isPaused() && !track->isTerminated())
4216 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004217 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004218
4219 mixedTracks++;
4220
Andy Hung69aed5f2014-02-25 17:24:40 -08004221 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4222 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004223 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004224 if (track->mainBuffer() != mSinkBuffer &&
4225 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004226 if (mEffectBufferEnabled) {
4227 mEffectBufferValid = true; // Later can set directly.
4228 }
Eric Laurent81784c32012-11-19 14:55:58 -08004229 chain = getEffectChain_l(track->sessionId());
4230 // Delegate volume control to effect in track effect chain if needed
4231 if (chain != 0) {
4232 tracksWithEffect++;
4233 } else {
4234 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4235 "session %d",
4236 name, track->sessionId());
4237 }
4238 }
4239
4240
4241 int param = AudioMixer::VOLUME;
4242 if (track->mFillingUpStatus == Track::FS_FILLED) {
4243 // no ramp for the first volume setting
4244 track->mFillingUpStatus = Track::FS_ACTIVE;
4245 if (track->mState == TrackBase::RESUMING) {
4246 track->mState = TrackBase::ACTIVE;
4247 param = AudioMixer::RAMP_VOLUME;
4248 }
4249 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004250 // FIXME should not make a decision based on mServer
4251 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004252 // If the track is stopped before the first frame was mixed,
4253 // do not apply ramp
4254 param = AudioMixer::RAMP_VOLUME;
4255 }
4256
4257 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004258 uint32_t vl, vr; // in U8.24 integer format
4259 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004260 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004261 vl = vr = 0;
4262 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004263 if (track->isPausing()) {
4264 track->setPaused();
4265 }
4266 } else {
4267
4268 // read original volumes with volume control
4269 float typeVolume = mStreamTypes[track->streamType()].volume;
4270 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004271 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004272 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004273 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4274 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004275 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004276 if (vlf > GAIN_FLOAT_UNITY) {
4277 ALOGV("Track left volume out of range: %.3g", vlf);
4278 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004279 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004280 if (vrf > GAIN_FLOAT_UNITY) {
4281 ALOGV("Track right volume out of range: %.3g", vrf);
4282 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004283 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004284 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004285 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004286 // now apply the master volume and stream type volume and shaper volume
4287 vlf *= v * vh;
4288 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004289 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004290 // then derive vl and vr as U8.24 versions for the effect chain
4291 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4292 vl = (uint32_t) (scaleto8_24 * vlf);
4293 vr = (uint32_t) (scaleto8_24 * vrf);
4294 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004295 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004296 // send level comes from shared memory and so may be corrupt
4297 if (sendLevel > MAX_GAIN_INT) {
4298 ALOGV("Track send level out of range: %04X", sendLevel);
4299 sendLevel = MAX_GAIN_INT;
4300 }
Andy Hung6be49402014-05-30 10:42:03 -07004301 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4302 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004303 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004304
Eric Laurent81784c32012-11-19 14:55:58 -08004305 // Delegate volume control to effect in track effect chain if needed
4306 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4307 // Do not ramp volume if volume is controlled by effect
4308 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004309 // Update remaining floating point volume levels
4310 vlf = (float)vl / (1 << 24);
4311 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004312 track->mHasVolumeController = true;
4313 } else {
4314 // force no volume ramp when volume controller was just disabled or removed
4315 // from effect chain to avoid volume spike
4316 if (track->mHasVolumeController) {
4317 param = AudioMixer::VOLUME;
4318 }
4319 track->mHasVolumeController = false;
4320 }
4321
Eric Laurent81784c32012-11-19 14:55:58 -08004322 // XXX: these things DON'T need to be done each time
4323 mAudioMixer->setBufferProvider(name, track);
4324 mAudioMixer->enable(name);
4325
Andy Hung6be49402014-05-30 10:42:03 -07004326 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4327 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4328 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004329 mAudioMixer->setParameter(
4330 name,
4331 AudioMixer::TRACK,
4332 AudioMixer::FORMAT, (void *)track->format());
4333 mAudioMixer->setParameter(
4334 name,
4335 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004336 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004337 mAudioMixer->setParameter(
4338 name,
4339 AudioMixer::TRACK,
4340 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004341 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004342 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004343 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004344 if (reqSampleRate == 0) {
4345 reqSampleRate = mSampleRate;
4346 } else if (reqSampleRate > maxSampleRate) {
4347 reqSampleRate = maxSampleRate;
4348 }
Eric Laurent81784c32012-11-19 14:55:58 -08004349 mAudioMixer->setParameter(
4350 name,
4351 AudioMixer::RESAMPLE,
4352 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004353 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004354
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004355 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004356 mAudioMixer->setParameter(
4357 name,
4358 AudioMixer::TIMESTRETCH,
4359 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004360 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004361
Andy Hung69aed5f2014-02-25 17:24:40 -08004362 /*
4363 * Select the appropriate output buffer for the track.
4364 *
Andy Hung98ef9782014-03-04 14:46:50 -08004365 * Tracks with effects go into their own effects chain buffer
4366 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004367 *
4368 * Other tracks can use mMixerBuffer for higher precision
4369 * channel accumulation. If this buffer is enabled
4370 * (mMixerBufferEnabled true), then selected tracks will accumulate
4371 * into it.
4372 *
4373 */
4374 if (mMixerBufferEnabled
4375 && (track->mainBuffer() == mSinkBuffer
4376 || track->mainBuffer() == mMixerBuffer)) {
4377 mAudioMixer->setParameter(
4378 name,
4379 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004380 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004381 mAudioMixer->setParameter(
4382 name,
4383 AudioMixer::TRACK,
4384 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4385 // TODO: override track->mainBuffer()?
4386 mMixerBufferValid = true;
4387 } else {
4388 mAudioMixer->setParameter(
4389 name,
4390 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004391 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004392 mAudioMixer->setParameter(
4393 name,
4394 AudioMixer::TRACK,
4395 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4396 }
Eric Laurent81784c32012-11-19 14:55:58 -08004397 mAudioMixer->setParameter(
4398 name,
4399 AudioMixer::TRACK,
4400 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4401
4402 // reset retry count
4403 track->mRetryCount = kMaxTrackRetries;
4404
4405 // If one track is ready, set the mixer ready if:
4406 // - the mixer was not ready during previous round OR
4407 // - no other track is not ready
4408 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4409 mixerStatus != MIXER_TRACKS_ENABLED) {
4410 mixerStatus = MIXER_TRACKS_READY;
4411 }
4412 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004413 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004414 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4415 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004416 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004417 } else {
4418 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004419 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004420
Eric Laurent81784c32012-11-19 14:55:58 -08004421 // clear effect chain input buffer if an active track underruns to avoid sending
4422 // previous audio buffer again to effects
4423 chain = getEffectChain_l(track->sessionId());
4424 if (chain != 0) {
4425 chain->clearInputBuffer();
4426 }
4427
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004428 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004429 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4430 track->isStopped() || track->isPaused()) {
4431 // We have consumed all the buffers of this track.
4432 // Remove it from the list of active tracks.
4433 // TODO: use actual buffer filling status instead of latency when available from
4434 // audio HAL
4435 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004436 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004437 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4438 if (track->isStopped()) {
4439 track->reset();
4440 }
4441 tracksToRemove->add(track);
4442 }
4443 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004444 // No buffers for this track. Give it a few chances to
4445 // fill a buffer, then remove it from active list.
4446 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004447 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004448 tracksToRemove->add(track);
4449 // indicate to client process that the track was disabled because of underrun;
4450 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004451 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004452 // If one track is not ready, mark the mixer also not ready if:
4453 // - the mixer was ready during previous round OR
4454 // - no other track is ready
4455 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4456 mixerStatus != MIXER_TRACKS_READY) {
4457 mixerStatus = MIXER_TRACKS_ENABLED;
4458 }
4459 }
4460 mAudioMixer->disable(name);
4461 }
4462
4463 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004464
4465 }
4466
4467 // Push the new FastMixer state if necessary
4468 bool pauseAudioWatchdog = false;
4469 if (didModify) {
4470 state->mFastTracksGen++;
4471 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4472 if (kUseFastMixer == FastMixer_Dynamic &&
4473 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4474 state->mCommand = FastMixerState::COLD_IDLE;
4475 state->mColdFutexAddr = &mFastMixerFutex;
4476 state->mColdGen++;
4477 mFastMixerFutex = 0;
4478 if (kUseFastMixer == FastMixer_Dynamic) {
4479 mNormalSink = mOutputSink;
4480 }
4481 // If we go into cold idle, need to wait for acknowledgement
4482 // so that fast mixer stops doing I/O.
4483 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4484 pauseAudioWatchdog = true;
4485 }
Eric Laurent81784c32012-11-19 14:55:58 -08004486 }
4487 if (sq != NULL) {
4488 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004489 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4490 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4491 // when bringing the output sink into standby.)
4492 //
4493 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4494 //
4495 // This occurs with BT suspend when we idle the FastMixer with
4496 // active tracks, which may be added or removed.
4497 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004498 }
4499#ifdef AUDIO_WATCHDOG
4500 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4501 mAudioWatchdog->pause();
4502 }
4503#endif
4504
4505 // Now perform the deferred reset on fast tracks that have stopped
4506 while (resetMask != 0) {
4507 size_t i = __builtin_ctz(resetMask);
4508 ALOG_ASSERT(i < count);
4509 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004510 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004511 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4512 track->reset();
4513 }
4514
4515 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004516 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004517
Eric Laurent97d547d2014-09-02 14:45:53 -07004518 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4519 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004520 }
4521
4522 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004523 // as long as there are effects we should clear the effects buffer, to avoid
4524 // passing a non-clean buffer to the effect chain
4525 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004526 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004527 // sink or mix buffer must be cleared if all tracks are connected to an
4528 // effect chain as in this case the mixer will not write to the sink or mix buffer
4529 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004530 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4531 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004532 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004533 if (mMixerBufferValid) {
4534 memset(mMixerBuffer, 0, mMixerBufferSize);
4535 // TODO: In testing, mSinkBuffer below need not be cleared because
4536 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4537 // after mixing.
4538 //
4539 // To enforce this guarantee:
4540 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4541 // (mixedTracks == 0 && fastTracks > 0))
4542 // must imply MIXER_TRACKS_READY.
4543 // Later, we may clear buffers regardless, and skip much of this logic.
4544 }
Andy Hung98ef9782014-03-04 14:46:50 -08004545 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004546 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004547 }
4548
4549 // if any fast tracks, then status is ready
4550 mMixerStatusIgnoringFastTracks = mixerStatus;
4551 if (fastTracks > 0) {
4552 mixerStatus = MIXER_TRACKS_READY;
4553 }
4554 return mixerStatus;
4555}
4556
Eric Laurentad7dd962016-09-22 12:38:37 -07004557// trackCountForUid_l() must be called with ThreadBase::mLock held
4558uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4559{
4560 uint32_t trackCount = 0;
4561 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004562 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004563 trackCount++;
4564 }
4565 }
4566 return trackCount;
4567}
4568
Eric Laurent81784c32012-11-19 14:55:58 -08004569// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004570int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004571 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004572{
Eric Laurentad7dd962016-09-22 12:38:37 -07004573 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4574 return -1;
4575 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004576 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004577}
4578
4579// deleteTrackName_l() must be called with ThreadBase::mLock held
4580void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4581{
4582 ALOGV("remove track (%d) and delete from mixer", name);
4583 mAudioMixer->deleteTrackName(name);
4584}
4585
Eric Laurent10351942014-05-08 18:49:52 -07004586// checkForNewParameter_l() must be called with ThreadBase::mLock held
4587bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4588 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004589{
Eric Laurent81784c32012-11-19 14:55:58 -08004590 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004591 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004592
Eric Laurent10351942014-05-08 18:49:52 -07004593 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004594
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004595 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004596
Eric Laurent10351942014-05-08 18:49:52 -07004597 AudioParameter param = AudioParameter(keyValuePair);
4598 int value;
4599 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4600 reconfig = true;
4601 }
4602 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004603 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004604 status = BAD_VALUE;
4605 } else {
4606 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004607 reconfig = true;
4608 }
Eric Laurent10351942014-05-08 18:49:52 -07004609 }
4610 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004611 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004612 status = BAD_VALUE;
4613 } else {
4614 // no need to save value, since it's constant
4615 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004616 }
Eric Laurent10351942014-05-08 18:49:52 -07004617 }
4618 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4619 // do not accept frame count changes if tracks are open as the track buffer
4620 // size depends on frame count and correct behavior would not be guaranteed
4621 // if frame count is changed after track creation
4622 if (!mTracks.isEmpty()) {
4623 status = INVALID_OPERATION;
4624 } else {
4625 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004626 }
Eric Laurent10351942014-05-08 18:49:52 -07004627 }
4628 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004629#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004630 // when changing the audio output device, call addBatteryData to notify
4631 // the change
4632 if (mOutDevice != value) {
4633 uint32_t params = 0;
4634 // check whether speaker is on
4635 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4636 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004637 }
Eric Laurent10351942014-05-08 18:49:52 -07004638
4639 audio_devices_t deviceWithoutSpeaker
4640 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4641 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004642 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004643 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4644 }
4645
4646 if (params != 0) {
4647 addBatteryData(params);
4648 }
4649 }
Eric Laurent81784c32012-11-19 14:55:58 -08004650#endif
4651
Eric Laurent10351942014-05-08 18:49:52 -07004652 // forward device change to effects that have requested to be
4653 // aware of attached audio device.
4654 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004655 a2dpDeviceChanged =
4656 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004657 mOutDevice = value;
4658 for (size_t i = 0; i < mEffectChains.size(); i++) {
4659 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004660 }
4661 }
Eric Laurent10351942014-05-08 18:49:52 -07004662 }
Eric Laurent81784c32012-11-19 14:55:58 -08004663
Eric Laurent10351942014-05-08 18:49:52 -07004664 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004665 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004666 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004667 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004668 mStandby = true;
4669 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004670 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004671 }
Eric Laurent10351942014-05-08 18:49:52 -07004672 if (status == NO_ERROR && reconfig) {
4673 readOutputParameters_l();
4674 delete mAudioMixer;
4675 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4676 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004677 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004678 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004679 if (name < 0) {
4680 break;
4681 }
4682 mTracks[i]->mName = name;
4683 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004684 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004685 }
Eric Laurent81784c32012-11-19 14:55:58 -08004686 }
4687
Eric Laurent42537be2016-01-08 17:16:42 -08004688 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004689}
4690
4691
4692void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4693{
Eric Laurent81784c32012-11-19 14:55:58 -08004694 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004695 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004696 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004697 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004698
4699 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004700 // while we are dumping it. It may be inconsistent, but it won't mutate!
4701 // This is a large object so we place it on the heap.
4702 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4703 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4704 copy->dump(fd);
4705 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004706
4707#ifdef STATE_QUEUE_DUMP
4708 // Similar for state queue
4709 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4710 observerCopy.dump(fd);
4711 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4712 mutatorCopy.dump(fd);
4713#endif
4714
Glenn Kasten46909e72013-02-26 09:20:22 -08004715#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004716 // Write the tee output to a .wav file
4717 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004718#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004719
4720#ifdef AUDIO_WATCHDOG
4721 if (mAudioWatchdog != 0) {
4722 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4723 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4724 wdCopy.dump(fd);
4725 }
4726#endif
4727}
4728
4729uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4730{
4731 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4732}
4733
4734uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4735{
4736 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4737}
4738
4739void AudioFlinger::MixerThread::cacheParameters_l()
4740{
4741 PlaybackThread::cacheParameters_l();
4742
4743 // FIXME: Relaxed timing because of a certain device that can't meet latency
4744 // Should be reduced to 2x after the vendor fixes the driver issue
4745 // increase threshold again due to low power audio mode. The way this warning
4746 // threshold is calculated and its usefulness should be reconsidered anyway.
4747 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4748}
4749
4750// ----------------------------------------------------------------------------
4751
4752AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004753 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4754 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004755 // mLeftVolFloat, mRightVolFloat
4756{
4757}
4758
Eric Laurentbfb1b832013-01-07 09:53:42 -08004759AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4760 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004761 ThreadBase::type_t type, bool systemReady)
4762 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004763 // mLeftVolFloat, mRightVolFloat
Andy Hung10cbff12017-02-21 17:30:14 -08004764 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004765{
4766}
4767
Eric Laurent81784c32012-11-19 14:55:58 -08004768AudioFlinger::DirectOutputThread::~DirectOutputThread()
4769{
4770}
4771
Eric Laurent5850c4c2016-11-10 13:04:31 -08004772void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004773{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004774 float left, right;
4775
4776 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4777 left = right = 0;
4778 } else {
4779 float typeVolume = mStreamTypes[track->streamType()].volume;
4780 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004781 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004782
Andy Hung10cbff12017-02-21 17:30:14 -08004783 // Get volumeshaper scaling
4784 std::pair<float /* volume */, bool /* active */>
4785 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004786 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004787 v *= vh.first;
4788 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004789
Glenn Kastenc56f3422014-03-21 17:53:17 -07004790 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4791 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4792 if (left > GAIN_FLOAT_UNITY) {
4793 left = GAIN_FLOAT_UNITY;
4794 }
4795 left *= v;
4796 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4797 if (right > GAIN_FLOAT_UNITY) {
4798 right = GAIN_FLOAT_UNITY;
4799 }
4800 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004801 }
4802
4803 if (lastTrack) {
4804 if (left != mLeftVolFloat || right != mRightVolFloat) {
4805 mLeftVolFloat = left;
4806 mRightVolFloat = right;
4807
4808 // Convert volumes from float to 8.24
4809 uint32_t vl = (uint32_t)(left * (1 << 24));
4810 uint32_t vr = (uint32_t)(right * (1 << 24));
4811
4812 // Delegate volume control to effect in track effect chain if needed
4813 // only one effect chain can be present on DirectOutputThread, so if
4814 // there is one, the track is connected to it
4815 if (!mEffectChains.isEmpty()) {
4816 mEffectChains[0]->setVolume_l(&vl, &vr);
4817 left = (float)vl / (1 << 24);
4818 right = (float)vr / (1 << 24);
4819 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004820 status_t result = mOutput->stream->setVolume(left, right);
4821 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004822 }
4823 }
4824}
4825
Phil Burk43b4dcc2015-06-09 16:53:44 -07004826void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4827{
4828 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004829 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004830
Eric Laurent0f0631e2015-07-06 18:01:25 -07004831 if (previousTrack != 0 && latestTrack != 0) {
4832 if (mType == DIRECT) {
4833 if (previousTrack.get() != latestTrack.get()) {
4834 mFlushPending = true;
4835 }
4836 } else /* mType == OFFLOAD */ {
4837 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4838 mFlushPending = true;
4839 }
4840 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004841 }
4842 PlaybackThread::onAddNewTrack_l();
4843}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004844
Eric Laurent81784c32012-11-19 14:55:58 -08004845AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4846 Vector< sp<Track> > *tracksToRemove
4847)
4848{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004849 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004850 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004851 bool doHwPause = false;
4852 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004853
4854 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004855 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004856 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004857 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004858 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004859 continue;
4860 }
4861
Eric Laurent5850c4c2016-11-10 13:04:31 -08004862 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004863#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004864 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004865#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004866 // Only consider last track started for volume and mixer state control.
4867 // In theory an older track could underrun and restart after the new one starts
4868 // but as we only care about the transition phase between two tracks on a
4869 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004870 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004871 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004872
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004873 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004874 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004875 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004876 doHwPause = true;
4877 mHwPaused = true;
4878 }
4879 tracksToRemove->add(track);
4880 } else if (track->isFlushPending()) {
4881 track->flushAck();
4882 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004883 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004884 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004885 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004886 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004887 if (last) {
4888 mLeftVolFloat = mRightVolFloat = -1.0;
4889 if (mHwPaused) {
4890 doHwResume = true;
4891 mHwPaused = false;
4892 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004893 }
4894 }
4895
Eric Laurent81784c32012-11-19 14:55:58 -08004896 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004897 // for all its buffers to be filled before processing it.
4898 // Allow draining the buffer in case the client
4899 // app does not call stop() and relies on underrun to stop:
4900 // hence the test on (track->mRetryCount > 1).
4901 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004902 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004903 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004904 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004905 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004906 minFrames = mNormalFrameCount;
4907 } else {
4908 minFrames = 1;
4909 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004910
Eric Laurentab5cdba2014-06-09 17:22:27 -07004911 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4912 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004913 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004914 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004915
4916 if (track->mFillingUpStatus == Track::FS_FILLED) {
4917 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004918 if (last) {
4919 // make sure processVolume_l() will apply new volume even if 0
4920 mLeftVolFloat = mRightVolFloat = -1.0;
4921 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004922 if (!mHwSupportsPause) {
4923 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004924 }
4925 }
4926
4927 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004928 processVolume_l(track, last);
4929 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004930 sp<Track> previousTrack = mPreviousTrack.promote();
4931 if (previousTrack != 0) {
4932 if (track != previousTrack.get()) {
4933 // Flush any data still being written from last track
4934 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004935 // Invalidate previous track to force a seek when resuming.
4936 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004937 }
4938 }
4939 mPreviousTrack = track;
4940
Eric Laurentd595b7c2013-04-03 17:27:56 -07004941 // reset retry count
4942 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004943 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004944 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004945 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004946 doHwResume = true;
4947 mHwPaused = false;
4948 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004949 }
Eric Laurent81784c32012-11-19 14:55:58 -08004950 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004951 // clear effect chain input buffer if the last active track started underruns
4952 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004953 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004954 mEffectChains[0]->clearInputBuffer();
4955 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004956 if (track->isStopping_1()) {
4957 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004958 if (last && mHwPaused) {
4959 doHwResume = true;
4960 mHwPaused = false;
4961 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004962 }
4963 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4964 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004965 // We have consumed all the buffers of this track.
4966 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004967 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004968 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004969 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4970 } else {
4971 audioHALFrames = 0;
4972 }
4973
Andy Hung818e7a32016-02-16 18:08:07 -08004974 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004975 if (mStandby || !last ||
4976 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004977 if (track->isStopping_2()) {
4978 track->mState = TrackBase::STOPPED;
4979 }
Eric Laurent81784c32012-11-19 14:55:58 -08004980 if (track->isStopped()) {
4981 track->reset();
4982 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004983 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004984 }
4985 } else {
4986 // No buffers for this track. Give it a few chances to
4987 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004988 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004989 if (--(track->mRetryCount) <= 0) {
4990 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004991 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004992 // indicate to client process that the track was disabled because of underrun;
4993 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004994 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004995 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004996 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4997 "minFrames = %u, mFormat = %#x",
4998 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004999 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005000 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005001 doHwPause = true;
5002 mHwPaused = true;
5003 }
Eric Laurent81784c32012-11-19 14:55:58 -08005004 }
5005 }
5006 }
5007 }
5008
Eric Laurentd1f69b02014-12-15 14:33:13 -08005009 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005010 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005011 for (size_t i = 0; i < mTracks.size(); i++) {
5012 if (mTracks[i]->isFlushPending()) {
5013 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005014 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005015 }
5016 }
5017 }
5018
5019 // make sure the pause/flush/resume sequence is executed in the right order.
5020 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5021 // before flush and then resume HW. This can happen in case of pause/flush/resume
5022 // if resume is received before pause is executed.
5023 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005024 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005025 status_t result = mOutput->stream->pause();
5026 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005027 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005028 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005029 flushHw_l();
5030 }
5031 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005032 status_t result = mOutput->stream->resume();
5033 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005034 }
Eric Laurent81784c32012-11-19 14:55:58 -08005035 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005036 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005037
5038 return mixerStatus;
5039}
5040
5041void AudioFlinger::DirectOutputThread::threadLoop_mix()
5042{
Eric Laurent81784c32012-11-19 14:55:58 -08005043 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005044 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005045 // output audio to hardware
5046 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005047 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005048 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005049 status_t status = mActiveTrack->getNextBuffer(&buffer);
5050 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005051 // no need to pad with 0 for compressed audio
5052 if (audio_has_proportional_frames(mFormat)) {
5053 memset(curBuf, 0, frameCount * mFrameSize);
5054 }
Eric Laurent81784c32012-11-19 14:55:58 -08005055 break;
5056 }
5057 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5058 frameCount -= buffer.frameCount;
5059 curBuf += buffer.frameCount * mFrameSize;
5060 mActiveTrack->releaseBuffer(&buffer);
5061 }
Andy Hung2098f272014-02-27 14:00:06 -08005062 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005063 mSleepTimeUs = 0;
5064 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005065 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005066}
5067
5068void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5069{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005070 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005071 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005072 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005073 return;
5074 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005075 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005076 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005077 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005078 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005079 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005080 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005081 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005082 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005083 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005084 }
5085}
5086
Eric Laurentd1f69b02014-12-15 14:33:13 -08005087void AudioFlinger::DirectOutputThread::threadLoop_exit()
5088{
5089 {
5090 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005091 for (size_t i = 0; i < mTracks.size(); i++) {
5092 if (mTracks[i]->isFlushPending()) {
5093 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005094 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005095 }
5096 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005097 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005098 flushHw_l();
5099 }
5100 }
5101 PlaybackThread::threadLoop_exit();
5102}
5103
5104// must be called with thread mutex locked
5105bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5106{
5107 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005108 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005109
vivek mehta9cd7ad12016-03-17 00:18:29 -07005110 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5111 return !mStandby;
5112 }
5113
Eric Laurentd1f69b02014-12-15 14:33:13 -08005114 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5115 // after a timeout and we will enter standby then.
5116 if (mTracks.size() > 0) {
5117 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005118 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5119 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005120 }
5121
Eric Laurent5cff4032015-05-26 13:49:58 -07005122 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005123}
5124
Eric Laurent81784c32012-11-19 14:55:58 -08005125// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005126int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005127 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005128{
Eric Laurentad7dd962016-09-22 12:38:37 -07005129 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5130 return -1;
5131 }
Eric Laurent81784c32012-11-19 14:55:58 -08005132 return 0;
5133}
5134
5135// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005136void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005137{
5138}
5139
Eric Laurent10351942014-05-08 18:49:52 -07005140// checkForNewParameter_l() must be called with ThreadBase::mLock held
5141bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5142 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005143{
5144 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005145 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005146
Eric Laurent10351942014-05-08 18:49:52 -07005147 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005148
Eric Laurent10351942014-05-08 18:49:52 -07005149 AudioParameter param = AudioParameter(keyValuePair);
5150 int value;
5151 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5152 // forward device change to effects that have requested to be
5153 // aware of attached audio device.
5154 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005155 a2dpDeviceChanged =
5156 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005157 mOutDevice = value;
5158 for (size_t i = 0; i < mEffectChains.size(); i++) {
5159 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005160 }
5161 }
Eric Laurent81784c32012-11-19 14:55:58 -08005162 }
Eric Laurent10351942014-05-08 18:49:52 -07005163 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5164 // do not accept frame count changes if tracks are open as the track buffer
5165 // size depends on frame count and correct behavior would not be garantied
5166 // if frame count is changed after track creation
5167 if (!mTracks.isEmpty()) {
5168 status = INVALID_OPERATION;
5169 } else {
5170 reconfig = true;
5171 }
5172 }
5173 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005174 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005175 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005176 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005177 mStandby = true;
5178 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005179 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005180 }
5181 if (status == NO_ERROR && reconfig) {
5182 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005183 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005184 }
5185 }
5186
Eric Laurent42537be2016-01-08 17:16:42 -08005187 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005188}
5189
5190uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5191{
5192 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005193 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005194 time = PlaybackThread::activeSleepTimeUs();
5195 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005196 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005197 }
5198 return time;
5199}
5200
5201uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5202{
5203 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005204 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005205 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5206 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005207 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005208 }
5209 return time;
5210}
5211
5212uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5213{
5214 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005215 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005216 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5217 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005218 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005219 }
5220 return time;
5221}
5222
5223void AudioFlinger::DirectOutputThread::cacheParameters_l()
5224{
5225 PlaybackThread::cacheParameters_l();
5226
5227 // use shorter standby delay as on normal output to release
5228 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005229 // no delay on outputs with HW A/V sync
5230 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005231 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005232 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005233 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005234 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005235 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005236 }
Eric Laurent81784c32012-11-19 14:55:58 -08005237}
5238
Eric Laurente659ef42014-09-29 13:06:46 -07005239void AudioFlinger::DirectOutputThread::flushHw_l()
5240{
Phil Burk062e67a2015-02-11 13:40:50 -08005241 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005242 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005243 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005244}
5245
Andy Hung10cbff12017-02-21 17:30:14 -08005246int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5247 // If a VolumeShaper is active, we must wake up periodically to update volume.
5248 const int64_t NS_PER_MS = 1000000;
5249 return mVolumeShaperActive ?
5250 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5251}
5252
Eric Laurent81784c32012-11-19 14:55:58 -08005253// ----------------------------------------------------------------------------
5254
Eric Laurentbfb1b832013-01-07 09:53:42 -08005255AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005256 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005257 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005258 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005259 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005260 mDrainSequence(0),
5261 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005262{
5263}
5264
5265AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5266{
5267}
5268
5269void AudioFlinger::AsyncCallbackThread::onFirstRef()
5270{
5271 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5272}
5273
5274bool AudioFlinger::AsyncCallbackThread::threadLoop()
5275{
5276 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005277 uint32_t writeAckSequence;
5278 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005279 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005280
5281 {
5282 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005283 while (!((mWriteAckSequence & 1) ||
5284 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005285 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005286 exitPending())) {
5287 mWaitWorkCV.wait(mLock);
5288 }
5289
Eric Laurentbfb1b832013-01-07 09:53:42 -08005290 if (exitPending()) {
5291 break;
5292 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005293 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5294 mWriteAckSequence, mDrainSequence);
5295 writeAckSequence = mWriteAckSequence;
5296 mWriteAckSequence &= ~1;
5297 drainSequence = mDrainSequence;
5298 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005299 asyncError = mAsyncError;
5300 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005301 }
5302 {
Eric Laurent4de95592013-09-26 15:28:21 -07005303 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5304 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005305 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005306 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005307 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005308 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005309 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005310 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005311 if (asyncError) {
5312 playbackThread->onAsyncError();
5313 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005314 }
5315 }
5316 }
5317 return false;
5318}
5319
5320void AudioFlinger::AsyncCallbackThread::exit()
5321{
5322 ALOGV("AsyncCallbackThread::exit");
5323 Mutex::Autolock _l(mLock);
5324 requestExit();
5325 mWaitWorkCV.broadcast();
5326}
5327
Eric Laurent3b4529e2013-09-05 18:09:19 -07005328void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005329{
5330 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005331 // bit 0 is cleared
5332 mWriteAckSequence = sequence << 1;
5333}
5334
5335void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5336{
5337 Mutex::Autolock _l(mLock);
5338 // ignore unexpected callbacks
5339 if (mWriteAckSequence & 2) {
5340 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341 mWaitWorkCV.signal();
5342 }
5343}
5344
Eric Laurent3b4529e2013-09-05 18:09:19 -07005345void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005346{
5347 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005348 // bit 0 is cleared
5349 mDrainSequence = sequence << 1;
5350}
5351
5352void AudioFlinger::AsyncCallbackThread::resetDraining()
5353{
5354 Mutex::Autolock _l(mLock);
5355 // ignore unexpected callbacks
5356 if (mDrainSequence & 2) {
5357 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005358 mWaitWorkCV.signal();
5359 }
5360}
5361
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005362void AudioFlinger::AsyncCallbackThread::setAsyncError()
5363{
5364 Mutex::Autolock _l(mLock);
5365 mAsyncError = true;
5366 mWaitWorkCV.signal();
5367}
5368
Eric Laurentbfb1b832013-01-07 09:53:42 -08005369
5370// ----------------------------------------------------------------------------
5371AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005372 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5373 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005374 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5375 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005376{
Eric Laurentfd477972013-10-25 18:10:40 -07005377 //FIXME: mStandby should be set to true by ThreadBase constructor
5378 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005379 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005380}
5381
Eric Laurentbfb1b832013-01-07 09:53:42 -08005382void AudioFlinger::OffloadThread::threadLoop_exit()
5383{
5384 if (mFlushPending || mHwPaused) {
5385 // If a flush is pending or track was paused, just discard buffered data
5386 flushHw_l();
5387 } else {
5388 mMixerStatus = MIXER_DRAIN_ALL;
5389 threadLoop_drain();
5390 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005391 if (mUseAsyncWrite) {
5392 ALOG_ASSERT(mCallbackThread != 0);
5393 mCallbackThread->exit();
5394 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005395 PlaybackThread::threadLoop_exit();
5396}
5397
5398AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5399 Vector< sp<Track> > *tracksToRemove
5400)
5401{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005402 size_t count = mActiveTracks.size();
5403
5404 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005405 bool doHwPause = false;
5406 bool doHwResume = false;
5407
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005408 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005409
Eric Laurentbfb1b832013-01-07 09:53:42 -08005410 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005411 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005412 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005413#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005414 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005415#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005416 // Only consider last track started for volume and mixer state control.
5417 // In theory an older track could underrun and restart after the new one starts
5418 // but as we only care about the transition phase between two tracks on a
5419 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005420 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005421 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005422
Haynes Mathew George7844f672014-01-15 12:32:55 -08005423 if (track->isInvalid()) {
5424 ALOGW("An invalidated track shouldn't be in active list");
5425 tracksToRemove->add(track);
5426 continue;
5427 }
5428
5429 if (track->mState == TrackBase::IDLE) {
5430 ALOGW("An idle track shouldn't be in active list");
5431 continue;
5432 }
5433
Eric Laurentbfb1b832013-01-07 09:53:42 -08005434 if (track->isPausing()) {
5435 track->setPaused();
5436 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005437 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005438 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005439 mHwPaused = true;
5440 }
5441 // If we were part way through writing the mixbuffer to
5442 // the HAL we must save this until we resume
5443 // BUG - this will be wrong if a different track is made active,
5444 // in that case we want to discard the pending data in the
5445 // mixbuffer and tell the client to present it again when the
5446 // track is resumed
5447 mPausedWriteLength = mCurrentWriteLength;
5448 mPausedBytesRemaining = mBytesRemaining;
5449 mBytesRemaining = 0; // stop writing
5450 }
5451 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005452 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005453 if (track->isStopping_1()) {
5454 track->mRetryCount = kMaxTrackStopRetriesOffload;
5455 } else {
5456 track->mRetryCount = kMaxTrackRetriesOffload;
5457 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005458 track->flushAck();
5459 if (last) {
5460 mFlushPending = true;
5461 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005462 } else if (track->isResumePending()){
5463 track->resumeAck();
5464 if (last) {
5465 if (mPausedBytesRemaining) {
5466 // Need to continue write that was interrupted
5467 mCurrentWriteLength = mPausedWriteLength;
5468 mBytesRemaining = mPausedBytesRemaining;
5469 mPausedBytesRemaining = 0;
5470 }
5471 if (mHwPaused) {
5472 doHwResume = true;
5473 mHwPaused = false;
5474 // threadLoop_mix() will handle the case that we need to
5475 // resume an interrupted write
5476 }
5477 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005478 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005479
Eric Laurent3df841a2016-07-15 15:15:40 -07005480 mLeftVolFloat = mRightVolFloat = -1.0;
5481
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005482 // Do not handle new data in this iteration even if track->framesReady()
5483 mixerStatus = MIXER_TRACKS_ENABLED;
5484 }
5485 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005486 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005487 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005488 if (track->mFillingUpStatus == Track::FS_FILLED) {
5489 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005490 if (last) {
5491 // make sure processVolume_l() will apply new volume even if 0
5492 mLeftVolFloat = mRightVolFloat = -1.0;
5493 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005494 }
5495
5496 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005497 sp<Track> previousTrack = mPreviousTrack.promote();
5498 if (previousTrack != 0) {
5499 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005500 // Flush any data still being written from last track
5501 mBytesRemaining = 0;
5502 if (mPausedBytesRemaining) {
5503 // Last track was paused so we also need to flush saved
5504 // mixbuffer state and invalidate track so that it will
5505 // re-submit that unwritten data when it is next resumed
5506 mPausedBytesRemaining = 0;
5507 // Invalidate is a bit drastic - would be more efficient
5508 // to have a flag to tell client that some of the
5509 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005510 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005511 }
5512 // flush data already sent to the DSP if changing audio session as audio
5513 // comes from a different source. Also invalidate previous track to force a
5514 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005515 if (previousTrack->sessionId() != track->sessionId()) {
5516 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005517 }
5518 }
5519 }
5520 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005521 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005522 if (track->isStopping_1()) {
5523 track->mRetryCount = kMaxTrackStopRetriesOffload;
5524 } else {
5525 track->mRetryCount = kMaxTrackRetriesOffload;
5526 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005527 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005528 mixerStatus = MIXER_TRACKS_READY;
5529 }
5530 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005531 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005532 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005533 if (--(track->mRetryCount) <= 0) {
5534 // Hardware buffer can hold a large amount of audio so we must
5535 // wait for all current track's data to drain before we say
5536 // that the track is stopped.
5537 if (mBytesRemaining == 0) {
5538 // Only start draining when all data in mixbuffer
5539 // has been written
5540 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5541 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5542 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5543 if (last && !mStandby) {
5544 // do not modify drain sequence if we are already draining. This happens
5545 // when resuming from pause after drain.
5546 if ((mDrainSequence & 1) == 0) {
5547 mSleepTimeUs = 0;
5548 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5549 mixerStatus = MIXER_DRAIN_TRACK;
5550 mDrainSequence += 2;
5551 }
5552 if (mHwPaused) {
5553 // It is possible to move from PAUSED to STOPPING_1 without
5554 // a resume so we must ensure hardware is running
5555 doHwResume = true;
5556 mHwPaused = false;
5557 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005558 }
5559 }
Eric Laurente93cc032016-05-05 10:15:10 -07005560 } else if (last) {
5561 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5562 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005563 }
5564 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005565 // Drain has completed or we are in standby, signal presentation complete
5566 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005567 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005568 uint32_t latency = 0;
5569 status_t result = mOutput->stream->getLatency(&latency);
5570 ALOGE_IF(result != OK,
5571 "Error when retrieving output stream latency: %d", result);
5572 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005573 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005574 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005575 track->presentationComplete(framesWritten, audioHALFrames);
5576 track->reset();
5577 tracksToRemove->add(track);
5578 }
5579 } else {
5580 // No buffers for this track. Give it a few chances to
5581 // fill a buffer, then remove it from active list.
5582 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005583 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005584 uint64_t position = 0;
5585 struct timespec unused;
5586 // The running check restarts the retry counter at least once.
5587 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5588 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5589 running = true;
5590 mOffloadUnderrunPosition = position;
5591 }
5592 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005593 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5594 (long long)position, (long long)mOffloadUnderrunPosition);
5595 }
5596 if (running) { // still running, give us more time.
5597 track->mRetryCount = kMaxTrackRetriesOffload;
5598 } else {
5599 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5600 track->name());
5601 tracksToRemove->add(track);
5602 // indicate to client process that the track was disabled because of underrun;
5603 // it will then automatically call start() when data is available
5604 track->disable();
5605 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005606 } else if (last){
5607 mixerStatus = MIXER_TRACKS_ENABLED;
5608 }
5609 }
5610 }
5611 // compute volume for this track
5612 processVolume_l(track, last);
5613 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005614
Eric Laurentea0fade2013-10-04 16:23:48 -07005615 // make sure the pause/flush/resume sequence is executed in the right order.
5616 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5617 // before flush and then resume HW. This can happen in case of pause/flush/resume
5618 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005619 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005620 status_t result = mOutput->stream->pause();
5621 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005622 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005623 if (mFlushPending) {
5624 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005625 }
Eric Laurentfd477972013-10-25 18:10:40 -07005626 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005627 status_t result = mOutput->stream->resume();
5628 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005629 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005630
Eric Laurentbfb1b832013-01-07 09:53:42 -08005631 // remove all the tracks that need to be...
5632 removeTracks_l(*tracksToRemove);
5633
5634 return mixerStatus;
5635}
5636
Eric Laurentbfb1b832013-01-07 09:53:42 -08005637// must be called with thread mutex locked
5638bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5639{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005640 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5641 mWriteAckSequence, mDrainSequence);
5642 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005643 return true;
5644 }
5645 return false;
5646}
5647
Eric Laurentbfb1b832013-01-07 09:53:42 -08005648bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5649{
5650 Mutex::Autolock _l(mLock);
5651 return waitingAsyncCallback_l();
5652}
5653
5654void AudioFlinger::OffloadThread::flushHw_l()
5655{
Eric Laurente659ef42014-09-29 13:06:46 -07005656 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005657 // Flush anything still waiting in the mixbuffer
5658 mCurrentWriteLength = 0;
5659 mBytesRemaining = 0;
5660 mPausedWriteLength = 0;
5661 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005662 // reset bytes written count to reflect that DSP buffers are empty after flush.
5663 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005664 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005665
Eric Laurentbfb1b832013-01-07 09:53:42 -08005666 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005667 // discard any pending drain or write ack by incrementing sequence
5668 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5669 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005670 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005671 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5672 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005673 }
5674}
5675
Haynes Mathew George05317d22016-05-03 16:34:26 -07005676void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5677{
5678 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005679 if (PlaybackThread::invalidateTracks_l(streamType)) {
5680 mFlushPending = true;
5681 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005682}
5683
Eric Laurentbfb1b832013-01-07 09:53:42 -08005684// ----------------------------------------------------------------------------
5685
Eric Laurent81784c32012-11-19 14:55:58 -08005686AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005687 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005688 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005689 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005690 mWaitTimeMs(UINT_MAX)
5691{
5692 addOutputTrack(mainThread);
5693}
5694
5695AudioFlinger::DuplicatingThread::~DuplicatingThread()
5696{
5697 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5698 mOutputTracks[i]->destroy();
5699 }
5700}
5701
5702void AudioFlinger::DuplicatingThread::threadLoop_mix()
5703{
5704 // mix buffers...
5705 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005706 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005707 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005708 if (mMixerBufferValid) {
5709 memset(mMixerBuffer, 0, mMixerBufferSize);
5710 } else {
5711 memset(mSinkBuffer, 0, mSinkBufferSize);
5712 }
Eric Laurent81784c32012-11-19 14:55:58 -08005713 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005714 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005715 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005716 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005717 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005718}
5719
5720void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5721{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005722 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005723 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005724 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005725 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005726 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005727 }
5728 } else if (mBytesWritten != 0) {
5729 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5730 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005731 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005732 } else {
5733 // flush remaining overflow buffers in output tracks
5734 writeFrames = 0;
5735 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005736 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005737 }
5738}
5739
Eric Laurentbfb1b832013-01-07 09:53:42 -08005740ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005741{
5742 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005743 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005744 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005745 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005746 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005747}
5748
5749void AudioFlinger::DuplicatingThread::threadLoop_standby()
5750{
5751 // DuplicatingThread implements standby by stopping all tracks
5752 for (size_t i = 0; i < outputTracks.size(); i++) {
5753 outputTracks[i]->stop();
5754 }
5755}
5756
5757void AudioFlinger::DuplicatingThread::saveOutputTracks()
5758{
5759 outputTracks = mOutputTracks;
5760}
5761
5762void AudioFlinger::DuplicatingThread::clearOutputTracks()
5763{
5764 outputTracks.clear();
5765}
5766
5767void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5768{
5769 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005770 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5771 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5772 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5773 const size_t frameCount =
5774 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5775 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5776 // from different OutputTracks and their associated MixerThreads (e.g. one may
5777 // nearly empty and the other may be dropping data).
5778
5779 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005780 this,
5781 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005782 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005783 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005784 frameCount,
5785 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005786 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5787 if (status != NO_ERROR) {
5788 ALOGE("addOutputTrack() initCheck failed %d", status);
5789 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005790 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005791 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5792 mOutputTracks.add(outputTrack);
5793 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5794 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005795}
5796
5797void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5798{
5799 Mutex::Autolock _l(mLock);
5800 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5801 if (mOutputTracks[i]->thread() == thread) {
5802 mOutputTracks[i]->destroy();
5803 mOutputTracks.removeAt(i);
5804 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005805 if (thread->getOutput() == mOutput) {
5806 mOutput = NULL;
5807 }
Eric Laurent81784c32012-11-19 14:55:58 -08005808 return;
5809 }
5810 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005811 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005812}
5813
5814// caller must hold mLock
5815void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5816{
5817 mWaitTimeMs = UINT_MAX;
5818 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5819 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5820 if (strong != 0) {
5821 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5822 if (waitTimeMs < mWaitTimeMs) {
5823 mWaitTimeMs = waitTimeMs;
5824 }
5825 }
5826 }
5827}
5828
5829
5830bool AudioFlinger::DuplicatingThread::outputsReady(
5831 const SortedVector< sp<OutputTrack> > &outputTracks)
5832{
5833 for (size_t i = 0; i < outputTracks.size(); i++) {
5834 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5835 if (thread == 0) {
5836 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5837 outputTracks[i].get());
5838 return false;
5839 }
5840 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5841 // see note at standby() declaration
5842 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5843 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5844 thread.get());
5845 return false;
5846 }
5847 }
5848 return true;
5849}
5850
5851uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5852{
5853 return (mWaitTimeMs * 1000) / 2;
5854}
5855
5856void AudioFlinger::DuplicatingThread::cacheParameters_l()
5857{
5858 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5859 updateWaitTime_l();
5860
5861 MixerThread::cacheParameters_l();
5862}
5863
Eric Laurent6acd1d42017-01-04 14:23:29 -08005864
Eric Laurent81784c32012-11-19 14:55:58 -08005865// ----------------------------------------------------------------------------
5866// Record
5867// ----------------------------------------------------------------------------
5868
5869AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5870 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005871 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005872 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005873 audio_devices_t inDevice,
5874 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005875#ifdef TEE_SINK
5876 , const sp<NBAIO_Sink>& teeSink
5877#endif
5878 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005879 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005880 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005881 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005882 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005883#ifdef TEE_SINK
5884 , mTeeSink(teeSink)
5885#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005886 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5887 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005888 // mFastCapture below
5889 , mFastCaptureFutex(0)
5890 // mInputSource
5891 // mPipeSink
5892 // mPipeSource
5893 , mPipeFramesP2(0)
5894 // mPipeMemory
5895 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005896 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005897{
Glenn Kastend7dca052015-03-05 16:05:54 -08005898 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5899 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005900
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005901 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005902
5903 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005904 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005905 size_t numCounterOffers = 0;
5906 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005907#if !LOG_NDEBUG
5908 ssize_t index =
5909#else
5910 (void)
5911#endif
5912 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005913 ALOG_ASSERT(index == 0);
5914
5915 // initialize fast capture depending on configuration
5916 bool initFastCapture;
5917 switch (kUseFastCapture) {
5918 case FastCapture_Never:
5919 initFastCapture = false;
5920 break;
5921 case FastCapture_Always:
5922 initFastCapture = true;
5923 break;
5924 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005925 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005926 break;
5927 // case FastCapture_Dynamic:
5928 }
5929
5930 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005931 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005932 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005933 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5934 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005935 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5936 void *pipeBuffer;
5937 const sp<MemoryDealer> roHeap(readOnlyHeap());
5938 sp<IMemory> pipeMemory;
5939 if ((roHeap == 0) ||
5940 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5941 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5942 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5943 goto failed;
5944 }
5945 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5946 memset(pipeBuffer, 0, pipeSize);
5947 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5948 const NBAIO_Format offers[1] = {format};
5949 size_t numCounterOffers = 0;
5950 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5951 ALOG_ASSERT(index == 0);
5952 mPipeSink = pipe;
5953 PipeReader *pipeReader = new PipeReader(*pipe);
5954 numCounterOffers = 0;
5955 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5956 ALOG_ASSERT(index == 0);
5957 mPipeSource = pipeReader;
5958 mPipeFramesP2 = pipeFramesP2;
5959 mPipeMemory = pipeMemory;
5960
5961 // create fast capture
5962 mFastCapture = new FastCapture();
5963 FastCaptureStateQueue *sq = mFastCapture->sq();
5964#ifdef STATE_QUEUE_DUMP
5965 // FIXME
5966#endif
5967 FastCaptureState *state = sq->begin();
5968 state->mCblk = NULL;
5969 state->mInputSource = mInputSource.get();
5970 state->mInputSourceGen++;
5971 state->mPipeSink = pipe;
5972 state->mPipeSinkGen++;
5973 state->mFrameCount = mFrameCount;
5974 state->mCommand = FastCaptureState::COLD_IDLE;
5975 // already done in constructor initialization list
5976 //mFastCaptureFutex = 0;
5977 state->mColdFutexAddr = &mFastCaptureFutex;
5978 state->mColdGen++;
5979 state->mDumpState = &mFastCaptureDumpState;
5980#ifdef TEE_SINK
5981 // FIXME
5982#endif
5983 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5984 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5985 sq->end();
5986 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5987
5988 // start the fast capture
5989 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5990 pid_t tid = mFastCapture->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08005991 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005992 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005993#ifdef AUDIO_WATCHDOG
5994 // FIXME
5995#endif
5996
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005997 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005998 }
5999failed: ;
6000
6001 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006002}
6003
Eric Laurent81784c32012-11-19 14:55:58 -08006004AudioFlinger::RecordThread::~RecordThread()
6005{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006006 if (mFastCapture != 0) {
6007 FastCaptureStateQueue *sq = mFastCapture->sq();
6008 FastCaptureState *state = sq->begin();
6009 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6010 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6011 if (old == -1) {
6012 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6013 }
6014 }
6015 state->mCommand = FastCaptureState::EXIT;
6016 sq->end();
6017 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6018 mFastCapture->join();
6019 mFastCapture.clear();
6020 }
6021 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006022 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006023 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006024}
6025
6026void AudioFlinger::RecordThread::onFirstRef()
6027{
Glenn Kastend7dca052015-03-05 16:05:54 -08006028 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006029}
6030
Eric Laurent555530a2017-02-07 18:17:24 -08006031void AudioFlinger::RecordThread::preExit()
6032{
6033 ALOGV(" preExit()");
6034 Mutex::Autolock _l(mLock);
6035 for (size_t i = 0; i < mTracks.size(); i++) {
6036 sp<RecordTrack> track = mTracks[i];
6037 track->invalidate();
6038 }
6039 mActiveTracks.clear();
6040 mStartStopCond.broadcast();
6041}
6042
Eric Laurent81784c32012-11-19 14:55:58 -08006043bool AudioFlinger::RecordThread::threadLoop()
6044{
Eric Laurent81784c32012-11-19 14:55:58 -08006045 nsecs_t lastWarning = 0;
6046
6047 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006048
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006049reacquire_wakelock:
6050 sp<RecordTrack> activeTrack;
6051 {
6052 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006053 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006054 }
6055
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006056 // used to request a deferred sleep, to be executed later while mutex is unlocked
6057 uint32_t sleepUs = 0;
6058
6059 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006060 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006061 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006062
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006063 // activeTracks accumulates a copy of a subset of mActiveTracks
6064 Vector< sp<RecordTrack> > activeTracks;
6065
Glenn Kasten735f45f2014-08-18 15:51:59 -07006066 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006067 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006068
Glenn Kasten735f45f2014-08-18 15:51:59 -07006069 // reference to a fast track which is about to be removed
6070 sp<RecordTrack> fastTrackToRemove;
6071
Eric Laurent81784c32012-11-19 14:55:58 -08006072 { // scope for mLock
6073 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006074
Eric Laurent021cf962014-05-13 10:18:14 -07006075 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006076
Eric Laurent000a4192014-01-29 15:17:32 -08006077 // check exitPending here because checkForNewParameters_l() and
6078 // checkForNewParameters_l() can temporarily release mLock
6079 if (exitPending()) {
6080 break;
6081 }
6082
Eric Laurent5c25d562016-07-13 17:17:45 -07006083 // sleep with mutex unlocked
6084 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006085 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006086 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6087 ATRACE_END();
6088 sleepUs = 0;
6089 continue;
6090 }
6091
Glenn Kasten2b806402013-11-20 16:37:38 -08006092 // if no active track(s), then standby and release wakelock
6093 size_t size = mActiveTracks.size();
6094 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006095 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006096 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006097 releaseWakeLock_l();
6098 ALOGV("RecordThread: loop stopping");
6099 // go to sleep
6100 mWaitWorkCV.wait(mLock);
6101 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006102 goto reacquire_wakelock;
6103 }
6104
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006105 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006106 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006107 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006108
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006109 activeTrack = mActiveTracks[i];
6110 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006111 if (activeTrack->isFastTrack()) {
6112 ALOG_ASSERT(fastTrackToRemove == 0);
6113 fastTrackToRemove = activeTrack;
6114 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006115 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006116 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006117 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006118 continue;
6119 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006120
6121 TrackBase::track_state activeTrackState = activeTrack->mState;
6122 switch (activeTrackState) {
6123
6124 case TrackBase::PAUSING:
6125 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006126 doBroadcast = true;
6127 size--;
6128 continue;
6129
6130 case TrackBase::STARTING_1:
6131 sleepUs = 10000;
6132 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006133 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006134 continue;
6135
6136 case TrackBase::STARTING_2:
6137 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006138 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006139 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006140 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006141 break;
6142
6143 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006144 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006145 break;
6146
6147 case TrackBase::IDLE:
6148 i++;
6149 continue;
6150
6151 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006152 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006153 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006154
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006155 activeTracks.add(activeTrack);
6156 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006157
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006158 if (activeTrack->isFastTrack()) {
6159 ALOG_ASSERT(!mFastTrackAvail);
6160 ALOG_ASSERT(fastTrack == 0);
6161 fastTrack = activeTrack;
6162 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006163 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006164
Andy Hungdae27702016-10-31 14:01:16 -07006165 mActiveTracks.updatePowerState(this);
6166
Eric Laurent5c25d562016-07-13 17:17:45 -07006167 if (allStopped) {
6168 standbyIfNotAlreadyInStandby();
6169 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006170 if (doBroadcast) {
6171 mStartStopCond.broadcast();
6172 }
6173
6174 // sleep if there are no active tracks to process
6175 if (activeTracks.size() == 0) {
6176 if (sleepUs == 0) {
6177 sleepUs = kRecordThreadSleepUs;
6178 }
6179 continue;
6180 }
6181 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006182
Eric Laurent81784c32012-11-19 14:55:58 -08006183 lockEffectChains_l(effectChains);
6184 }
6185
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006186 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006187
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006188 size_t size = effectChains.size();
6189 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006190 // thread mutex is not locked, but effect chain is locked
6191 effectChains[i]->process_l();
6192 }
6193
Glenn Kasten735f45f2014-08-18 15:51:59 -07006194 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006195 if (mFastCapture != 0) {
6196 FastCaptureStateQueue *sq = mFastCapture->sq();
6197 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006198 bool didModify = false;
6199 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006200 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6201 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6202 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6203 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6204 if (old == -1) {
6205 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6206 }
6207 }
6208 state->mCommand = FastCaptureState::READ_WRITE;
6209#if 0 // FIXME
6210 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006211 FastThreadDumpState::kSamplingNforLowRamDevice :
6212 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006213#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006214 didModify = true;
6215 }
6216 audio_track_cblk_t *cblkOld = state->mCblk;
6217 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6218 if (cblkNew != cblkOld) {
6219 state->mCblk = cblkNew;
6220 // block until acked if removing a fast track
6221 if (cblkOld != NULL) {
6222 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6223 }
6224 didModify = true;
6225 }
6226 sq->end(didModify);
6227 if (didModify) {
6228 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006229#if 0
6230 if (kUseFastCapture == FastCapture_Dynamic) {
6231 mNormalSource = mPipeSource;
6232 }
6233#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006234 }
6235 }
6236
Glenn Kasten735f45f2014-08-18 15:51:59 -07006237 // now run the fast track destructor with thread mutex unlocked
6238 fastTrackToRemove.clear();
6239
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006240 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6241 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6242 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6243 // If destination is non-contiguous, first read past the nominal end of buffer, then
6244 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006245
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006246 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006247 ssize_t framesRead;
6248
6249 // If an NBAIO source is present, use it to read the normal capture's data
6250 if (mPipeSource != 0) {
6251 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006252 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006253 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006254 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006255 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6256 // buffer size or at least for 20ms.
6257 size_t sleepFrames = max(
6258 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6259 if (framesRead <= (ssize_t) sleepFrames) {
6260 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6261 }
6262 if (framesRead < 0) {
6263 status_t status = (status_t) framesRead;
6264 switch (status) {
6265 case OVERRUN:
6266 ALOGW("overrun on read from pipe");
6267 framesRead = 0;
6268 break;
6269 case NEGOTIATE:
6270 ALOGE("re-negotiation is needed");
6271 framesRead = -1; // Will cause an attempt to recover.
6272 break;
6273 default:
6274 ALOGE("unknown error %d on read from pipe", status);
6275 break;
6276 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006277 }
6278 // otherwise use the HAL / AudioStreamIn directly
6279 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006280 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006281 size_t bytesRead;
6282 status_t result = mInput->stream->read(
6283 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006284 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006285 if (result < 0) {
6286 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006287 } else {
6288 framesRead = bytesRead / mFrameSize;
6289 }
6290 }
6291
Andy Hung3f0c9022016-01-15 17:49:46 -08006292 // Update server timestamp with server stats
6293 // systemTime() is optional if the hardware supports timestamps.
6294 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6295 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6296
6297 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006298 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006299 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006300 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006301 if (ret == NO_ERROR) {
6302 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6303 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6304 // Note: In general record buffers should tend to be empty in
6305 // a properly running pipeline.
6306 //
6307 // Also, it is not advantageous to call get_presentation_position during the read
6308 // as the read obtains a lock, preventing the timestamp call from executing.
6309 }
6310 }
6311 // Use this to track timestamp information
6312 // ALOGD("%s", mTimestamp.toString().c_str());
6313
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006314 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006315 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006316 // Force input into standby so that it tries to recover at next read attempt
6317 inputStandBy();
6318 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006319 }
6320 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006321 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006322 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006323 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006324
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006325 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006326 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006327 }
6328 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006329 {
6330 size_t part1 = mRsmpInFramesP2 - rear;
6331 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006332 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006333 (framesRead - part1) * mFrameSize);
6334 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006335 }
6336 rear = mRsmpInRear += framesRead;
6337
6338 size = activeTracks.size();
6339 // loop over each active track
6340 for (size_t i = 0; i < size; i++) {
6341 activeTrack = activeTracks[i];
6342
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006343 // skip fast tracks, as those are handled directly by FastCapture
6344 if (activeTrack->isFastTrack()) {
6345 continue;
6346 }
6347
Andy Hung73c02e42015-03-29 01:13:58 -07006348 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006349 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6350
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006351 enum {
6352 OVERRUN_UNKNOWN,
6353 OVERRUN_TRUE,
6354 OVERRUN_FALSE
6355 } overrun = OVERRUN_UNKNOWN;
6356
6357 // loop over getNextBuffer to handle circular sink
6358 for (;;) {
6359
6360 activeTrack->mSink.frameCount = ~0;
6361 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6362 size_t framesOut = activeTrack->mSink.frameCount;
6363 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6364
Andy Hung73c02e42015-03-29 01:13:58 -07006365 // check available frames and handle overrun conditions
6366 // if the record track isn't draining fast enough.
6367 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006368 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006369 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6370 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006371 overrun = OVERRUN_TRUE;
6372 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006373 if (framesOut == 0 || framesIn == 0) {
6374 break;
6375 }
6376
Andy Hung6770c6f2015-04-07 13:43:36 -07006377 // Don't allow framesOut to be larger than what is possible with resampling
6378 // from framesIn.
6379 // This isn't strictly necessary but helps limit buffer resizing in
6380 // RecordBufferConverter. TODO: remove when no longer needed.
6381 framesOut = min(framesOut,
6382 destinationFramesPossible(
6383 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006384 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6385 framesOut = activeTrack->mRecordBufferConverter->convert(
6386 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006387
6388 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6389 overrun = OVERRUN_FALSE;
6390 }
6391
6392 if (activeTrack->mFramesToDrop == 0) {
6393 if (framesOut > 0) {
6394 activeTrack->mSink.frameCount = framesOut;
6395 activeTrack->releaseBuffer(&activeTrack->mSink);
6396 }
6397 } else {
6398 // FIXME could do a partial drop of framesOut
6399 if (activeTrack->mFramesToDrop > 0) {
6400 activeTrack->mFramesToDrop -= framesOut;
6401 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006402 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006403 }
6404 } else {
6405 activeTrack->mFramesToDrop += framesOut;
6406 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6407 activeTrack->mSyncStartEvent->isCancelled()) {
6408 ALOGW("Synced record %s, session %d, trigger session %d",
6409 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6410 activeTrack->sessionId(),
6411 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006412 activeTrack->mSyncStartEvent->triggerSession() :
6413 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006414 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006415 }
6416 }
6417 }
6418
6419 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006420 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006421 }
6422 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006423
6424 switch (overrun) {
6425 case OVERRUN_TRUE:
6426 // client isn't retrieving buffers fast enough
6427 if (!activeTrack->setOverflow()) {
6428 nsecs_t now = systemTime();
6429 // FIXME should lastWarning per track?
6430 if ((now - lastWarning) > kWarningThrottleNs) {
6431 ALOGW("RecordThread: buffer overflow");
6432 lastWarning = now;
6433 }
6434 }
6435 break;
6436 case OVERRUN_FALSE:
6437 activeTrack->clearOverflow();
6438 break;
6439 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006440 break;
6441 }
6442
Andy Hung3f0c9022016-01-15 17:49:46 -08006443 // update frame information and push timestamp out
6444 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006445 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006446 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6447 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006448 }
6449
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006450unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006451 // enable changes in effect chain
6452 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006453 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006454 }
6455
Glenn Kasten93e471f2013-08-19 08:40:07 -07006456 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006457
6458 {
6459 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006460 for (size_t i = 0; i < mTracks.size(); i++) {
6461 sp<RecordTrack> track = mTracks[i];
6462 track->invalidate();
6463 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006464 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006465 mStartStopCond.broadcast();
6466 }
6467
6468 releaseWakeLock();
6469
6470 ALOGV("RecordThread %p exiting", this);
6471 return false;
6472}
6473
Glenn Kasten93e471f2013-08-19 08:40:07 -07006474void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006475{
6476 if (!mStandby) {
6477 inputStandBy();
6478 mStandby = true;
6479 }
6480}
6481
6482void AudioFlinger::RecordThread::inputStandBy()
6483{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006484 // Idle the fast capture if it's currently running
6485 if (mFastCapture != 0) {
6486 FastCaptureStateQueue *sq = mFastCapture->sq();
6487 FastCaptureState *state = sq->begin();
6488 if (!(state->mCommand & FastCaptureState::IDLE)) {
6489 state->mCommand = FastCaptureState::COLD_IDLE;
6490 state->mColdFutexAddr = &mFastCaptureFutex;
6491 state->mColdGen++;
6492 mFastCaptureFutex = 0;
6493 sq->end();
6494 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6495 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6496#if 0
6497 if (kUseFastCapture == FastCapture_Dynamic) {
6498 // FIXME
6499 }
6500#endif
6501#ifdef AUDIO_WATCHDOG
6502 // FIXME
6503#endif
6504 } else {
6505 sq->end(false /*didModify*/);
6506 }
6507 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006508 status_t result = mInput->stream->standby();
6509 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006510
6511 // If going into standby, flush the pipe source.
6512 if (mPipeSource.get() != nullptr) {
6513 const ssize_t flushed = mPipeSource->flush();
6514 if (flushed > 0) {
6515 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6516 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6517 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6518 }
6519 }
Eric Laurent81784c32012-11-19 14:55:58 -08006520}
6521
Glenn Kasten05997e22014-03-13 15:08:33 -07006522// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006523sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006524 const sp<AudioFlinger::Client>& client,
6525 uint32_t sampleRate,
6526 audio_format_t format,
6527 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006528 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006529 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006530 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006531 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006532 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006533 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006534 status_t *status,
6535 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006536{
Glenn Kasten74935e42013-12-19 08:56:45 -08006537 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006538 sp<RecordTrack> track;
6539 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006540 audio_input_flags_t inputFlags = mInput->flags;
6541
6542 // special case for FAST flag considered OK if fast capture is present
6543 if (hasFastCapture()) {
6544 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6545 }
6546
6547 // Check if requested flags are compatible with output stream flags
6548 if ((*flags & inputFlags) != *flags) {
6549 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6550 " input flags (%08x)",
6551 *flags, inputFlags);
6552 *flags = (audio_input_flags_t)(*flags & inputFlags);
6553 }
Eric Laurent81784c32012-11-19 14:55:58 -08006554
Glenn Kasten90e58b12013-07-31 16:16:02 -07006555 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006556 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006557 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006558 // we formerly checked for a callback handler (non-0 tid),
6559 // but that is no longer required for TRANSFER_OBTAIN mode
6560 //
Glenn Kasten74105912014-07-03 12:28:53 -07006561 // frame count is not specified, or is exactly the pipe depth
6562 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006563 // PCM data
6564 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006565 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006566 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006567 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006568 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006569 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006570 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006571 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006572 hasFastCapture() &&
6573 // there are sufficient fast track slots available
6574 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006575 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006576 // check compatibility with audio effects.
6577 Mutex::Autolock _l(mLock);
6578 // Do not accept FAST flag if the session has software effects
6579 sp<EffectChain> chain = getEffectChain_l(sessionId);
6580 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006581 audio_input_flags_t old = *flags;
6582 chain->checkInputFlagCompatibility(flags);
6583 if (old != *flags) {
6584 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6585 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006586 }
6587 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006588 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006589 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6590 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006591 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006592 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006593 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006594 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006595 frameCount, mFrameCount, mPipeFramesP2,
6596 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6597 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006598 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006599 }
6600 }
6601
6602 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006603 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006604 // fast track: frame count is exactly the pipe depth
6605 frameCount = mPipeFramesP2;
6606 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6607 *notificationFrames = mFrameCount;
6608 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006609 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6610 // or 20 ms if there is a fast capture
6611 // TODO This could be a roundupRatio inline, and const
6612 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6613 * sampleRate + mSampleRate - 1) / mSampleRate;
6614 // minimum number of notification periods is at least kMinNotifications,
6615 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6616 static const size_t kMinNotifications = 3;
6617 static const uint32_t kMinMs = 30;
6618 // TODO This could be a roundupRatio inline
6619 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6620 // TODO This could be a roundupRatio inline
6621 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6622 maxNotificationFrames;
6623 const size_t minFrameCount = maxNotificationFrames *
6624 max(kMinNotifications, minNotificationsByMs);
6625 frameCount = max(frameCount, minFrameCount);
6626 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6627 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006628 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006629 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006630 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006631
Glenn Kasten15e57982013-09-24 11:52:37 -07006632 lStatus = initCheck();
6633 if (lStatus != NO_ERROR) {
6634 ALOGE("createRecordTrack_l() audio driver not initialized");
6635 goto Exit;
6636 }
Eric Laurent81784c32012-11-19 14:55:58 -08006637
6638 { // scope for mLock
6639 Mutex::Autolock _l(mLock);
6640
6641 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006642 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006643 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006644
Glenn Kasten03003332013-08-06 15:40:54 -07006645 lStatus = track->initCheck();
6646 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006647 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006648 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006649 goto Exit;
6650 }
6651 mTracks.add(track);
6652
6653 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6654 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6655 mAudioFlinger->btNrecIsOff();
6656 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6657 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006658
Eric Laurent05067782016-06-01 18:27:28 -07006659 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006660 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6661 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6662 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08006663 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006664 }
Eric Laurent81784c32012-11-19 14:55:58 -08006665 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006666
Eric Laurent81784c32012-11-19 14:55:58 -08006667 lStatus = NO_ERROR;
6668
6669Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006670 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006671 return track;
6672}
6673
6674status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6675 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006676 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006677{
6678 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6679 sp<ThreadBase> strongMe = this;
6680 status_t status = NO_ERROR;
6681
6682 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006683 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006684 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006685 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006686 triggerSession,
6687 recordTrack->sessionId(),
6688 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006689 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006690 // Sync event can be cancelled by the trigger session if the track is not in a
6691 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006692 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006693 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006694 } else {
6695 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006696 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006697 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006698 }
6699 }
6700
6701 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006702 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006703 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006704 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6705 if (recordTrack->mState == TrackBase::PAUSING) {
6706 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006707 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006708 } else {
6709 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006710 }
6711 return status;
6712 }
6713
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006714 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6715 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6716 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006717 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006718 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006719 status_t status = NO_ERROR;
6720 if (recordTrack->isExternalTrack()) {
6721 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006722 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006723 mLock.lock();
6724 // FIXME should verify that recordTrack is still in mActiveTracks
6725 if (status != NO_ERROR) {
6726 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006727 recordTrack->clearSyncStartEvent();
6728 ALOGV("RecordThread::start error %d", status);
6729 return status;
6730 }
Eric Laurent81784c32012-11-19 14:55:58 -08006731 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006732 // Catch up with current buffer indices if thread is already running.
6733 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6734 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6735 // see previously buffered data before it called start(), but with greater risk of overrun.
6736
Andy Hung73c02e42015-03-29 01:13:58 -07006737 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006738 // clear any converter state as new data will be discontinuous
6739 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006740 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006741 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006742 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006743 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006744 ALOGV("Record failed to start");
6745 status = BAD_VALUE;
6746 goto startError;
6747 }
Eric Laurent81784c32012-11-19 14:55:58 -08006748 return status;
6749 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006750
Eric Laurent81784c32012-11-19 14:55:58 -08006751startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006752 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006753 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006754 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006755 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006756 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006757 return status;
6758}
6759
Eric Laurent81784c32012-11-19 14:55:58 -08006760void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6761{
6762 sp<SyncEvent> strongEvent = event.promote();
6763
6764 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006765 sp<RefBase> ptr = strongEvent->cookie().promote();
6766 if (ptr != 0) {
6767 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6768 recordTrack->handleSyncStartEvent(strongEvent);
6769 }
Eric Laurent81784c32012-11-19 14:55:58 -08006770 }
6771}
6772
Glenn Kastena8356f62013-07-25 14:37:52 -07006773bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006774 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006775 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006776 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006777 return false;
6778 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006779 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006780 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006781 // signal thread to stop
6782 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006783 // do not wait for mStartStopCond if exiting
6784 if (exitPending()) {
6785 return true;
6786 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006787 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006788 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006789 // if we have been restarted, recordTrack is in mActiveTracks here
6790 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006791 ALOGV("Record stopped OK");
6792 return true;
6793 }
6794 return false;
6795}
6796
Glenn Kasten0f11b512014-01-31 16:18:54 -08006797bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006798{
6799 return false;
6800}
6801
Glenn Kasten0f11b512014-01-31 16:18:54 -08006802status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006803{
6804#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6805 if (!isValidSyncEvent(event)) {
6806 return BAD_VALUE;
6807 }
6808
Glenn Kastend848eb42016-03-08 13:42:11 -08006809 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006810 status_t ret = NAME_NOT_FOUND;
6811
6812 Mutex::Autolock _l(mLock);
6813
6814 for (size_t i = 0; i < mTracks.size(); i++) {
6815 sp<RecordTrack> track = mTracks[i];
6816 if (eventSession == track->sessionId()) {
6817 (void) track->setSyncEvent(event);
6818 ret = NO_ERROR;
6819 }
6820 }
6821 return ret;
6822#else
6823 return BAD_VALUE;
6824#endif
6825}
6826
6827// destroyTrack_l() must be called with ThreadBase::mLock held
6828void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6829{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006830 track->terminate();
6831 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006832 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006833 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006834 removeTrack_l(track);
6835 }
6836}
6837
6838void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6839{
6840 mTracks.remove(track);
6841 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006842 if (track->isFastTrack()) {
6843 ALOG_ASSERT(!mFastTrackAvail);
6844 mFastTrackAvail = true;
6845 }
Eric Laurent81784c32012-11-19 14:55:58 -08006846}
6847
6848void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6849{
6850 dumpInternals(fd, args);
6851 dumpTracks(fd, args);
6852 dumpEffectChains(fd, args);
6853}
6854
6855void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6856{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006857 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006858
Glenn Kasten44182c22015-03-05 17:12:23 -08006859 dumpBase(fd, args);
6860
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006861 AudioStreamIn *input = mInput;
6862 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6863 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6864 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006865 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006866 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006867 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006868 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006869 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006870
Glenn Kasten2f90c512015-12-02 11:40:09 -08006871 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6872 // while we are dumping it. It may be inconsistent, but it won't mutate!
6873 // This is a large object so we place it on the heap.
6874 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6875 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6876 copy->dump(fd);
6877 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006878}
6879
Glenn Kasten0f11b512014-01-31 16:18:54 -08006880void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006881{
6882 const size_t SIZE = 256;
6883 char buffer[SIZE];
6884 String8 result;
6885
Marco Nelissenb2208842014-02-07 14:00:50 -08006886 size_t numtracks = mTracks.size();
6887 size_t numactive = mActiveTracks.size();
6888 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006889 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006890 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006891 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006892 RecordTrack::appendDumpHeader(result);
6893 for (size_t i = 0; i < numtracks ; ++i) {
6894 sp<RecordTrack> track = mTracks[i];
6895 if (track != 0) {
6896 bool active = mActiveTracks.indexOf(track) >= 0;
6897 if (active) {
6898 numactiveseen++;
6899 }
6900 track->dump(buffer, SIZE, active);
6901 result.append(buffer);
6902 }
Eric Laurent81784c32012-11-19 14:55:58 -08006903 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006904 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006905 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006906 }
6907
Marco Nelissenb2208842014-02-07 14:00:50 -08006908 if (numactiveseen != numactive) {
6909 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6910 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006911 result.append(buffer);
6912 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006913 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006914 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006915 if (mTracks.indexOf(track) < 0) {
6916 track->dump(buffer, SIZE, true);
6917 result.append(buffer);
6918 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006919 }
Eric Laurent81784c32012-11-19 14:55:58 -08006920
6921 }
6922 write(fd, result.string(), result.size());
6923}
6924
Andy Hung73c02e42015-03-29 01:13:58 -07006925
6926void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6927{
6928 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6929 RecordThread *recordThread = (RecordThread *) threadBase.get();
6930 mRsmpInFront = recordThread->mRsmpInRear;
6931 mRsmpInUnrel = 0;
6932}
6933
6934void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6935 size_t *framesAvailable, bool *hasOverrun)
6936{
6937 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6938 RecordThread *recordThread = (RecordThread *) threadBase.get();
6939 const int32_t rear = recordThread->mRsmpInRear;
6940 const int32_t front = mRsmpInFront;
6941 const ssize_t filled = rear - front;
6942
6943 size_t framesIn;
6944 bool overrun = false;
6945 if (filled < 0) {
6946 // should not happen, but treat like a massive overrun and re-sync
6947 framesIn = 0;
6948 mRsmpInFront = rear;
6949 overrun = true;
6950 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6951 framesIn = (size_t) filled;
6952 } else {
6953 // client is not keeping up with server, but give it latest data
6954 framesIn = recordThread->mRsmpInFrames;
6955 mRsmpInFront = /* front = */ rear - framesIn;
6956 overrun = true;
6957 }
6958 if (framesAvailable != NULL) {
6959 *framesAvailable = framesIn;
6960 }
6961 if (hasOverrun != NULL) {
6962 *hasOverrun = overrun;
6963 }
6964}
6965
Eric Laurent81784c32012-11-19 14:55:58 -08006966// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006967status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006968 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006969{
Andy Hung73c02e42015-03-29 01:13:58 -07006970 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006971 if (threadBase == 0) {
6972 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006973 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006974 return NOT_ENOUGH_DATA;
6975 }
6976 RecordThread *recordThread = (RecordThread *) threadBase.get();
6977 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006978 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006979 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006980 // FIXME should not be P2 (don't want to increase latency)
6981 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006982 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006983 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006984 front &= recordThread->mRsmpInFramesP2 - 1;
6985 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006986 if (part1 > (size_t) filled) {
6987 part1 = filled;
6988 }
6989 size_t ask = buffer->frameCount;
6990 ALOG_ASSERT(ask > 0);
6991 if (part1 > ask) {
6992 part1 = ask;
6993 }
6994 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006995 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006996 buffer->raw = NULL;
6997 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006998 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006999 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007000 }
7001
Andy Hung57446612015-04-19 23:56:46 -07007002 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007003 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007004 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007005 return NO_ERROR;
7006}
7007
7008// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007009void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7010 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007011{
Glenn Kasten85948432013-08-19 12:09:05 -07007012 size_t stepCount = buffer->frameCount;
7013 if (stepCount == 0) {
7014 return;
7015 }
Andy Hung73c02e42015-03-29 01:13:58 -07007016 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7017 mRsmpInUnrel -= stepCount;
7018 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007019 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007020 buffer->frameCount = 0;
7021}
7022
Andy Hung97a893e2015-03-29 01:03:07 -07007023
Eric Laurent10351942014-05-08 18:49:52 -07007024bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7025 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007026{
7027 bool reconfig = false;
7028
Eric Laurent10351942014-05-08 18:49:52 -07007029 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007030
Eric Laurent10351942014-05-08 18:49:52 -07007031 audio_format_t reqFormat = mFormat;
7032 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007033 // 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 -07007034 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7035
7036 AudioParameter param = AudioParameter(keyValuePair);
7037 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007038
7039 // scope for AutoPark extends to end of method
7040 AutoPark<FastCapture> park(mFastCapture);
7041
Eric Laurent10351942014-05-08 18:49:52 -07007042 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7043 // channel count change can be requested. Do we mandate the first client defines the
7044 // HAL sampling rate and channel count or do we allow changes on the fly?
7045 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7046 samplingRate = value;
7047 reconfig = true;
7048 }
7049 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007050 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007051 status = BAD_VALUE;
7052 } else {
7053 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007054 reconfig = true;
7055 }
Eric Laurent10351942014-05-08 18:49:52 -07007056 }
7057 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7058 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007059 if (!audio_is_input_channel(mask) ||
7060 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007061 status = BAD_VALUE;
7062 } else {
7063 channelMask = mask;
7064 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007065 }
Eric Laurent10351942014-05-08 18:49:52 -07007066 }
7067 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7068 // do not accept frame count changes if tracks are open as the track buffer
7069 // size depends on frame count and correct behavior would not be guaranteed
7070 // if frame count is changed after track creation
7071 if (mActiveTracks.size() > 0) {
7072 status = INVALID_OPERATION;
7073 } else {
7074 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007075 }
Eric Laurent10351942014-05-08 18:49:52 -07007076 }
7077 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7078 // forward device change to effects that have requested to be
7079 // aware of attached audio device.
7080 for (size_t i = 0; i < mEffectChains.size(); i++) {
7081 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007082 }
Eric Laurent81784c32012-11-19 14:55:58 -08007083
Eric Laurent10351942014-05-08 18:49:52 -07007084 // store input device and output device but do not forward output device to audio HAL.
7085 // Note that status is ignored by the caller for output device
7086 // (see AudioFlinger::setParameters()
7087 if (audio_is_output_devices(value)) {
7088 mOutDevice = value;
7089 status = BAD_VALUE;
7090 } else {
7091 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007092 if (value != AUDIO_DEVICE_NONE) {
7093 mPrevInDevice = value;
7094 }
Eric Laurent10351942014-05-08 18:49:52 -07007095 // disable AEC and NS if the device is a BT SCO headset supporting those
7096 // pre processings
7097 if (mTracks.size() > 0) {
7098 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7099 mAudioFlinger->btNrecIsOff();
7100 for (size_t i = 0; i < mTracks.size(); i++) {
7101 sp<RecordTrack> track = mTracks[i];
7102 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7103 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007104 }
7105 }
7106 }
Eric Laurent10351942014-05-08 18:49:52 -07007107 }
7108 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7109 mAudioSource != (audio_source_t)value) {
7110 // forward device change to effects that have requested to be
7111 // aware of attached audio device.
7112 for (size_t i = 0; i < mEffectChains.size(); i++) {
7113 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007114 }
Eric Laurent10351942014-05-08 18:49:52 -07007115 mAudioSource = (audio_source_t)value;
7116 }
Glenn Kastene198c362013-08-13 09:13:36 -07007117
Eric Laurent10351942014-05-08 18:49:52 -07007118 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007119 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007120 if (status == INVALID_OPERATION) {
7121 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007122 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007123 }
7124 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007125 if (status == BAD_VALUE) {
7126 uint32_t sRate;
7127 audio_channel_mask_t channelMask;
7128 audio_format_t format;
7129 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7130 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7131 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7132 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7133 status = NO_ERROR;
7134 }
Eric Laurent81784c32012-11-19 14:55:58 -08007135 }
Eric Laurent10351942014-05-08 18:49:52 -07007136 if (status == NO_ERROR) {
7137 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007138 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007139 }
7140 }
Eric Laurent81784c32012-11-19 14:55:58 -08007141 }
Eric Laurent10351942014-05-08 18:49:52 -07007142
Eric Laurent81784c32012-11-19 14:55:58 -08007143 return reconfig;
7144}
7145
7146String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7147{
Eric Laurent81784c32012-11-19 14:55:58 -08007148 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007149 if (initCheck() == NO_ERROR) {
7150 String8 out_s8;
7151 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7152 return out_s8;
7153 }
Eric Laurent81784c32012-11-19 14:55:58 -08007154 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007155 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007156}
7157
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007158void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007159 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7160
7161 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007162
7163 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007164 case AUDIO_INPUT_OPENED:
7165 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007166 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007167 desc->mChannelMask = mChannelMask;
7168 desc->mSamplingRate = mSampleRate;
7169 desc->mFormat = mFormat;
7170 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007171 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007172 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007173 break;
7174
Eric Laurent73e26b62015-04-27 16:55:58 -07007175 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007176 default:
7177 break;
7178 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007179 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007180}
7181
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007182void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007183{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007184 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7185 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007186 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007187 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007188 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007189 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7190 result = mInput->stream->getFrameSize(&mFrameSize);
7191 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7192 result = mInput->stream->getBufferSize(&mBufferSize);
7193 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007194 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007195 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007196 // 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 -07007197 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007198 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007199 // A larger value should allow more old data to be read after a track calls start(),
7200 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007201 //
7202 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007203 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007204 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007205 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007206 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007207
7208 // TODO optimize audio capture buffer sizes ...
7209 // Here we calculate the size of the sliding buffer used as a source
7210 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7211 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7212 // be better to have it derived from the pipe depth in the long term.
7213 // The current value is higher than necessary. However it should not add to latency.
7214
Glenn Kasten85948432013-08-19 12:09:05 -07007215 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007216 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7217 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7218 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007219
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007220 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7221 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007222}
7223
Glenn Kasten5f972c02014-01-13 09:59:31 -08007224uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007225{
7226 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007227 uint32_t result;
7228 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7229 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007230 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007231 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007232}
7233
Eric Laurent4c415062016-06-17 16:14:16 -07007234// hasAudioSession_l() must be called with ThreadBase::mLock held
7235uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007236{
Eric Laurent81784c32012-11-19 14:55:58 -08007237 uint32_t result = 0;
7238 if (getEffectChain_l(sessionId) != 0) {
7239 result = EFFECT_SESSION;
7240 }
7241
7242 for (size_t i = 0; i < mTracks.size(); ++i) {
7243 if (sessionId == mTracks[i]->sessionId()) {
7244 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007245 if (mTracks[i]->isFastTrack()) {
7246 result |= FAST_SESSION;
7247 }
Eric Laurent81784c32012-11-19 14:55:58 -08007248 break;
7249 }
7250 }
7251
7252 return result;
7253}
7254
Glenn Kastend848eb42016-03-08 13:42:11 -08007255KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007256{
Glenn Kastend848eb42016-03-08 13:42:11 -08007257 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007258 Mutex::Autolock _l(mLock);
7259 for (size_t j = 0; j < mTracks.size(); ++j) {
7260 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007261 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007262 if (ids.indexOfKey(sessionId) < 0) {
7263 ids.add(sessionId, true);
7264 }
7265 }
7266 return ids;
7267}
7268
7269AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7270{
7271 Mutex::Autolock _l(mLock);
7272 AudioStreamIn *input = mInput;
7273 mInput = NULL;
7274 return input;
7275}
7276
7277// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007278sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007279{
7280 if (mInput == NULL) {
7281 return NULL;
7282 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007283 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007284}
7285
7286status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7287{
7288 // only one chain per input thread
7289 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007290 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007291 return INVALID_OPERATION;
7292 }
7293 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007294 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007295 chain->setInBuffer(NULL);
7296 chain->setOutBuffer(NULL);
7297
7298 checkSuspendOnAddEffectChain_l(chain);
7299
Eric Laurent1b928682014-10-02 19:41:47 -07007300 // make sure enabled pre processing effects state is communicated to the HAL as we
7301 // just moved them to a new input stream.
7302 chain->syncHalEffectsState();
7303
Eric Laurent81784c32012-11-19 14:55:58 -08007304 mEffectChains.add(chain);
7305
7306 return NO_ERROR;
7307}
7308
7309size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7310{
7311 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7312 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007313 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007314 chain.get(), mEffectChains.size(), this);
7315 if (mEffectChains.size() == 1) {
7316 mEffectChains.removeAt(0);
7317 }
7318 return 0;
7319}
7320
Eric Laurent1c333e22014-05-20 10:48:17 -07007321status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7322 audio_patch_handle_t *handle)
7323{
7324 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007325
7326 // store new device and send to effects
7327 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007328 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007329 for (size_t i = 0; i < mEffectChains.size(); i++) {
7330 mEffectChains[i]->setDevice_l(mInDevice);
7331 }
7332
7333 // disable AEC and NS if the device is a BT SCO headset supporting those
7334 // pre processings
7335 if (mTracks.size() > 0) {
7336 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7337 mAudioFlinger->btNrecIsOff();
7338 for (size_t i = 0; i < mTracks.size(); i++) {
7339 sp<RecordTrack> track = mTracks[i];
7340 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7341 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7342 }
7343 }
7344
7345 // store new source and send to effects
7346 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7347 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007348 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007349 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007350 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007351 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007352
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007353 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007354 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7355 status = hwDevice->createAudioPatch(patch->num_sources,
7356 patch->sources,
7357 patch->num_sinks,
7358 patch->sinks,
7359 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007360 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007361 char *address;
7362 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7363 address = audio_device_address_to_parameter(
7364 patch->sources[0].ext.device.type,
7365 patch->sources[0].ext.device.address);
7366 } else {
7367 address = (char *)calloc(1, 1);
7368 }
7369 AudioParameter param = AudioParameter(String8(address));
7370 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007371 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007372 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007373 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007374 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007375 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007376 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007377 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007378
Eric Laurente8726fe2015-06-26 09:39:24 -07007379 if (mInDevice != mPrevInDevice) {
7380 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7381 mPrevInDevice = mInDevice;
7382 }
Eric Laurent296fb132015-05-01 11:38:42 -07007383
Eric Laurent1c333e22014-05-20 10:48:17 -07007384 return status;
7385}
7386
7387status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7388{
7389 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007390
7391 mInDevice = AUDIO_DEVICE_NONE;
7392
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007393 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007394 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7395 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007396 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007397 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007398 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007399 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007400 }
7401 return status;
7402}
7403
Eric Laurent83b88082014-06-20 18:31:16 -07007404void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7405{
7406 Mutex::Autolock _l(mLock);
7407 mTracks.add(record);
7408}
7409
7410void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7411{
7412 Mutex::Autolock _l(mLock);
7413 destroyTrack_l(record);
7414}
7415
7416void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7417{
7418 ThreadBase::getAudioPortConfig(config);
7419 config->role = AUDIO_PORT_ROLE_SINK;
7420 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7421 config->ext.mix.usecase.source = mAudioSource;
7422}
Eric Laurent1c333e22014-05-20 10:48:17 -07007423
Eric Laurent6acd1d42017-01-04 14:23:29 -08007424// ----------------------------------------------------------------------------
7425// Mmap
7426// ----------------------------------------------------------------------------
7427
7428AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7429 : mThread(thread)
7430{
7431}
7432
7433AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7434{
7435 MmapThread *thread = mThread.get();
7436 // clear our strong reference before disconnecting the thread: the last strong reference
7437 // will be removed when closeInput/closeOutput is executed upono call from audio policy manager
7438 // and the thread removed from mMMapThreads list causing the thread destruction.
7439 mThread.clear();
7440 if (thread != nullptr) {
7441 thread->disconnect();
7442 }
7443}
7444
7445status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7446 struct audio_mmap_buffer_info *info)
7447{
7448 if (mThread == 0) {
7449 return NO_INIT;
7450 }
7451 return mThread->createMmapBuffer(minSizeFrames, info);
7452}
7453
7454status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7455{
7456 if (mThread == 0) {
7457 return NO_INIT;
7458 }
7459 return mThread->getMmapPosition(position);
7460}
7461
7462status_t AudioFlinger::MmapThreadHandle::start(const MmapStreamInterface::Client& client, audio_port_handle_t *handle)
7463
7464{
7465 if (mThread == 0) {
7466 return NO_INIT;
7467 }
7468 return mThread->start(client, handle);
7469}
7470
7471status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7472{
7473 if (mThread == 0) {
7474 return NO_INIT;
7475 }
7476 return mThread->stop(handle);
7477}
7478
7479
7480AudioFlinger::MmapThread::MmapThread(
7481 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7482 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7483 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7484 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
7485 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev)
7486{
7487 readHalParameters_l();
7488}
7489
7490AudioFlinger::MmapThread::~MmapThread()
7491{
7492}
7493
7494void AudioFlinger::MmapThread::onFirstRef()
7495{
7496 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7497}
7498
7499void AudioFlinger::MmapThread::disconnect()
7500{
7501 for (const sp<MmapTrack> &t : mActiveTracks) {
7502 stop(t->portId());
7503 }
7504 // this will cause the destruction of this thread.
7505 if (isOutput()) {
7506 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7507 } else {
7508 AudioSystem::releaseInput(mId, mSessionId);
7509 }
7510}
7511
7512
7513void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7514 audio_stream_type_t streamType __unused,
7515 audio_session_t sessionId,
7516 const sp<MmapStreamCallback>& callback,
7517 audio_port_handle_t portId)
7518{
7519 mAttr = *attr;
7520 mSessionId = sessionId;
7521 mCallback = callback;
7522 mPortId = portId;
7523}
7524
7525status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7526 struct audio_mmap_buffer_info *info)
7527{
7528 if (mHalStream == 0) {
7529 return NO_INIT;
7530 }
7531 return mHalStream->createMmapBuffer(minSizeFrames, info);
7532}
7533
7534status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7535{
7536 if (mHalStream == 0) {
7537 return NO_INIT;
7538 }
7539 return mHalStream->getMmapPosition(position);
7540}
7541
7542status_t AudioFlinger::MmapThread::start(const MmapStreamInterface::Client& client,
7543 audio_port_handle_t *handle)
7544{
7545 ALOGV("%s clientUid %d", __FUNCTION__, client.clientUid);
7546 if (mHalStream == 0) {
7547 return NO_INIT;
7548 }
7549
7550 status_t ret;
7551 audio_session_t sessionId;
7552 audio_port_handle_t portId;
7553
7554 if (mActiveTracks.size() == 0) {
7555 // for the first track, reuse portId and session allocated when the stream was opened
7556 mHalStream->start();
7557 portId = mPortId;
7558 sessionId = mSessionId;
7559 } else {
7560 // for other tracks than first one, get a new port ID from APM.
7561 sessionId = (audio_session_t)mAudioFlinger->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
7562 audio_io_handle_t io;
7563 if (isOutput()) {
7564 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7565 config.sample_rate = mSampleRate;
7566 config.channel_mask = mChannelMask;
7567 config.format = mFormat;
7568 audio_stream_type_t stream = streamType();
7569 audio_output_flags_t flags =
7570 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
7571 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7572 sessionId,
7573 &stream,
7574 client.clientUid,
7575 &config,
7576 flags,
7577 AUDIO_PORT_HANDLE_NONE,
7578 &portId);
7579 } else {
7580 audio_config_base_t config;
7581 config.sample_rate = mSampleRate;
7582 config.channel_mask = mChannelMask;
7583 config.format = mFormat;
7584 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7585 sessionId,
7586 client.clientPid,
7587 client.clientUid,
7588 &config,
7589 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7590 AUDIO_PORT_HANDLE_NONE,
7591 &portId);
7592 }
7593 // APM should not chose a different input or output stream for the same set of attributes
7594 // and audo configuration
7595 if (ret != NO_ERROR || io != mId) {
7596 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7597 __FUNCTION__, ret, io, mId);
7598 return BAD_VALUE;
7599 }
7600 }
7601
7602 if (isOutput()) {
7603 ret = AudioSystem::startOutput(mId, streamType(), sessionId);
7604 } else {
7605 ret = AudioSystem::startInput(mId, sessionId);
7606 }
7607
7608 // abort if start is rejected by audio policy manager
7609 if (ret != NO_ERROR) {
7610 if (mActiveTracks.size() != 0) {
7611 if (isOutput()) {
7612 AudioSystem::releaseOutput(mId, streamType(), sessionId);
7613 } else {
7614 AudioSystem::releaseInput(mId, sessionId);
7615 }
7616 }
7617 return PERMISSION_DENIED;
7618 }
7619
7620 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, sessionId,
7621 client.clientUid, portId);
7622
7623 mActiveTracks.add(track);
7624 sp<EffectChain> chain = getEffectChain_l(sessionId);
7625 if (chain != 0) {
7626 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7627 chain->incTrackCnt();
7628 chain->incActiveTrackCnt();
7629 }
7630
7631 *handle = portId;
7632
7633 broadcast_l();
7634
7635 ALOGV("%s DONE handle %d", __FUNCTION__, portId);
7636
7637 return NO_ERROR;
7638}
7639
7640status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7641{
7642
7643 ALOGV("%s handle %d", __FUNCTION__, handle);
7644
7645 if (mHalStream == 0) {
7646 return NO_INIT;
7647 }
7648
7649 sp<MmapTrack> track;
7650 for (const sp<MmapTrack> &t : mActiveTracks) {
7651 if (handle == t->portId()) {
7652 track = t;
7653 break;
7654 }
7655 }
7656 if (track == 0) {
7657 return BAD_VALUE;
7658 }
7659
7660 mActiveTracks.remove(track);
7661
7662 if (isOutput()) {
7663 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
7664 if (mActiveTracks.size() != 0) {
7665 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
7666 }
7667 } else {
7668 AudioSystem::stopInput(mId, track->sessionId());
7669 if (mActiveTracks.size() != 0) {
7670 AudioSystem::releaseInput(mId, track->sessionId());
7671 }
7672 }
7673
7674 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7675 if (chain != 0) {
7676 chain->decActiveTrackCnt();
7677 chain->decTrackCnt();
7678 }
7679
7680 broadcast_l();
7681
7682 if (mActiveTracks.size() == 0) {
7683 mHalStream->stop();
7684 }
7685 return NO_ERROR;
7686}
7687
7688
7689void AudioFlinger::MmapThread::readHalParameters_l()
7690{
7691 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7692 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7693 mFormat = mHALFormat;
7694 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7695 result = mHalStream->getFrameSize(&mFrameSize);
7696 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7697 result = mHalStream->getBufferSize(&mBufferSize);
7698 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7699 mFrameCount = mBufferSize / mFrameSize;
7700}
7701
7702bool AudioFlinger::MmapThread::threadLoop()
7703{
7704 acquireWakeLock();
7705
7706 checkSilentMode_l();
7707
7708 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7709
7710 while (!exitPending())
7711 {
7712 Mutex::Autolock _l(mLock);
7713 Vector< sp<EffectChain> > effectChains;
7714
7715 if (mSignalPending) {
7716 // A signal was raised while we were unlocked
7717 mSignalPending = false;
7718 } else {
7719 if (mConfigEvents.isEmpty()) {
7720 // we're about to wait, flush the binder command buffer
7721 IPCThreadState::self()->flushCommands();
7722
7723 if (exitPending()) {
7724 break;
7725 }
7726
7727 bool wakelockReleased = false;
7728 if (mActiveTracks.size() == 0) {
7729 releaseWakeLock_l();
7730 wakelockReleased = true;
7731 }
7732 // wait until we have something to do...
7733 ALOGV("%s going to sleep", myName.string());
7734 mWaitWorkCV.wait(mLock);
7735 ALOGV("%s waking up", myName.string());
7736 if (wakelockReleased) {
7737 acquireWakeLock_l();
7738 }
7739
7740 checkSilentMode_l();
7741
7742 continue;
7743 }
7744 }
7745
7746 processConfigEvents_l();
7747
7748 processVolume_l();
7749
7750 checkInvalidTracks_l();
7751
7752 mActiveTracks.updatePowerState(this);
7753
7754 lockEffectChains_l(effectChains);
7755 for (size_t i = 0; i < effectChains.size(); i ++) {
7756 effectChains[i]->process_l();
7757 }
7758 // enable changes in effect chain
7759 unlockEffectChains(effectChains);
7760 // Effect chains will be actually deleted here if they were removed from
7761 // mEffectChains list during mixing or effects processing
7762 }
7763
7764 threadLoop_exit();
7765
7766 if (!mStandby) {
7767 threadLoop_standby();
7768 mStandby = true;
7769 }
7770
7771 releaseWakeLock();
7772
7773 ALOGV("Thread %p type %d exiting", this, mType);
7774 return false;
7775}
7776
7777// checkForNewParameter_l() must be called with ThreadBase::mLock held
7778bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7779 status_t& status)
7780{
7781 AudioParameter param = AudioParameter(keyValuePair);
7782 int value;
7783 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7784 // forward device change to effects that have requested to be
7785 // aware of attached audio device.
7786 if (value != AUDIO_DEVICE_NONE) {
7787 mOutDevice = value;
7788 for (size_t i = 0; i < mEffectChains.size(); i++) {
7789 mEffectChains[i]->setDevice_l(mOutDevice);
7790 }
7791 }
7792 }
7793 status = mHalStream->setParameters(keyValuePair);
7794
7795 return false;
7796}
7797
7798String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7799{
7800 Mutex::Autolock _l(mLock);
7801 String8 out_s8;
7802 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7803 return out_s8;
7804 }
7805 return String8();
7806}
7807
7808void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7809 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7810
7811 desc->mIoHandle = mId;
7812
7813 switch (event) {
7814 case AUDIO_INPUT_OPENED:
7815 case AUDIO_INPUT_CONFIG_CHANGED:
7816 case AUDIO_OUTPUT_OPENED:
7817 case AUDIO_OUTPUT_CONFIG_CHANGED:
7818 desc->mPatch = mPatch;
7819 desc->mChannelMask = mChannelMask;
7820 desc->mSamplingRate = mSampleRate;
7821 desc->mFormat = mFormat;
7822 desc->mFrameCount = mFrameCount;
7823 desc->mFrameCountHAL = mFrameCount;
7824 desc->mLatency = 0;
7825 break;
7826
7827 case AUDIO_INPUT_CLOSED:
7828 case AUDIO_OUTPUT_CLOSED:
7829 default:
7830 break;
7831 }
7832 mAudioFlinger->ioConfigChanged(event, desc, pid);
7833}
7834
7835status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7836 audio_patch_handle_t *handle)
7837{
7838 status_t status = NO_ERROR;
7839
7840 // store new device and send to effects
7841 audio_devices_t type = AUDIO_DEVICE_NONE;
7842 audio_port_handle_t deviceId;
7843 if (isOutput()) {
7844 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7845 type |= patch->sinks[i].ext.device.type;
7846 }
7847 deviceId = patch->sinks[0].id;
7848 } else {
7849 type = patch->sources[0].ext.device.type;
7850 deviceId = patch->sources[0].id;
7851 }
7852
7853 for (size_t i = 0; i < mEffectChains.size(); i++) {
7854 mEffectChains[i]->setDevice_l(type);
7855 }
7856
7857 if (isOutput()) {
7858 mOutDevice = type;
7859 } else {
7860 mInDevice = type;
7861 // store new source and send to effects
7862 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7863 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7864 for (size_t i = 0; i < mEffectChains.size(); i++) {
7865 mEffectChains[i]->setAudioSource_l(mAudioSource);
7866 }
7867 }
7868 }
7869
7870 if (mAudioHwDev->supportsAudioPatches()) {
7871 status = mHalDevice->createAudioPatch(patch->num_sources,
7872 patch->sources,
7873 patch->num_sinks,
7874 patch->sinks,
7875 handle);
7876 } else {
7877 char *address;
7878 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7879 //FIXME: we only support address on first sink with HAL version < 3.0
7880 address = audio_device_address_to_parameter(
7881 patch->sinks[0].ext.device.type,
7882 patch->sinks[0].ext.device.address);
7883 } else {
7884 address = (char *)calloc(1, 1);
7885 }
7886 AudioParameter param = AudioParameter(String8(address));
7887 free(address);
7888 param.addInt(String8(AudioParameter::keyRouting), (int)type);
7889 if (!isOutput()) {
7890 param.addInt(String8(AudioParameter::keyInputSource),
7891 (int)patch->sinks[0].ext.mix.usecase.source);
7892 }
7893 status = mHalStream->setParameters(param.toString());
7894 *handle = AUDIO_PATCH_HANDLE_NONE;
7895 }
7896
7897 if (isOutput() && mPrevOutDevice != mOutDevice) {
7898 mPrevOutDevice = type;
7899 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
7900 if (mCallback != 0) {
7901 mCallback->onRoutingChanged(deviceId);
7902 }
7903 }
7904 if (!isOutput() && mPrevInDevice != mInDevice) {
7905 mPrevInDevice = type;
7906 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7907 if (mCallback != 0) {
7908 mCallback->onRoutingChanged(deviceId);
7909 }
7910 }
7911 return status;
7912}
7913
7914status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7915{
7916 status_t status = NO_ERROR;
7917
7918 mInDevice = AUDIO_DEVICE_NONE;
7919
7920 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
7921 supportsAudioPatches : false;
7922
7923 if (supportsAudioPatches) {
7924 status = mHalDevice->releaseAudioPatch(handle);
7925 } else {
7926 AudioParameter param;
7927 param.addInt(String8(AudioParameter::keyRouting), 0);
7928 status = mHalStream->setParameters(param.toString());
7929 }
7930 return status;
7931}
7932
7933void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
7934{
7935 ThreadBase::getAudioPortConfig(config);
7936 if (isOutput()) {
7937 config->role = AUDIO_PORT_ROLE_SOURCE;
7938 config->ext.mix.hw_module = mAudioHwDev->handle();
7939 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
7940 } else {
7941 config->role = AUDIO_PORT_ROLE_SINK;
7942 config->ext.mix.hw_module = mAudioHwDev->handle();
7943 config->ext.mix.usecase.source = mAudioSource;
7944 }
7945}
7946
7947status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
7948{
7949 audio_session_t session = chain->sessionId();
7950
7951 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
7952 // Attach all tracks with same session ID to this chain.
7953 // indicate all active tracks in the chain
7954 for (const sp<MmapTrack> &track : mActiveTracks) {
7955 if (session == track->sessionId()) {
7956 chain->incTrackCnt();
7957 chain->incActiveTrackCnt();
7958 }
7959 }
7960
7961 chain->setThread(this);
7962 chain->setInBuffer(nullptr);
7963 chain->setOutBuffer(nullptr);
7964 chain->syncHalEffectsState();
7965
7966 mEffectChains.add(chain);
7967 checkSuspendOnAddEffectChain_l(chain);
7968 return NO_ERROR;
7969}
7970
7971size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
7972{
7973 audio_session_t session = chain->sessionId();
7974
7975 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
7976
7977 for (size_t i = 0; i < mEffectChains.size(); i++) {
7978 if (chain == mEffectChains[i]) {
7979 mEffectChains.removeAt(i);
7980 // detach all active tracks from the chain
7981 // detach all tracks with same session ID from this chain
7982 for (const sp<MmapTrack> &track : mActiveTracks) {
7983 if (session == track->sessionId()) {
7984 chain->decActiveTrackCnt();
7985 chain->decTrackCnt();
7986 }
7987 }
7988 break;
7989 }
7990 }
7991 return mEffectChains.size();
7992}
7993
7994// hasAudioSession_l() must be called with ThreadBase::mLock held
7995uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
7996{
7997 uint32_t result = 0;
7998 if (getEffectChain_l(sessionId) != 0) {
7999 result = EFFECT_SESSION;
8000 }
8001
8002 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8003 sp<MmapTrack> track = mActiveTracks[i];
8004 if (sessionId == track->sessionId()) {
8005 result |= TRACK_SESSION;
8006 if (track->isFastTrack()) {
8007 result |= FAST_SESSION;
8008 }
8009 break;
8010 }
8011 }
8012
8013 return result;
8014}
8015
8016void AudioFlinger::MmapThread::threadLoop_standby()
8017{
8018 mHalStream->standby();
8019}
8020
8021void AudioFlinger::MmapThread::threadLoop_exit()
8022{
8023 if (mCallback != 0) {
8024 mCallback->onTearDown();
8025 }
8026}
8027
8028status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8029{
8030 return BAD_VALUE;
8031}
8032
8033bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8034{
8035 return false;
8036}
8037
8038status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8039 const effect_descriptor_t *desc, audio_session_t sessionId)
8040{
8041 // No global effect sessions on mmap threads
8042 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8043 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8044 desc->name, mThreadName);
8045 return BAD_VALUE;
8046 }
8047
8048 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8049 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8050 desc->name);
8051 return BAD_VALUE;
8052 }
8053 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
8054 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap thread",
8055 desc->name);
8056 return BAD_VALUE;
8057 }
8058
8059 // Only allow effects without processing load or latency
8060 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8061 return BAD_VALUE;
8062 }
8063
8064 return NO_ERROR;
8065
8066}
8067
8068void AudioFlinger::MmapThread::checkInvalidTracks_l()
8069{
8070 for (const sp<MmapTrack> &track : mActiveTracks) {
8071 if (track->isInvalid()) {
8072 if (mCallback != 0) {
8073 mCallback->onTearDown();
8074 }
8075 break;
8076 }
8077 }
8078}
8079
8080void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8081{
8082 dumpInternals(fd, args);
8083 dumpTracks(fd, args);
8084 dumpEffectChains(fd, args);
8085}
8086
8087void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8088{
8089 dprintf(fd, "\nMmap thread %p:\n", this);
8090
8091 dumpBase(fd, args);
8092
8093 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8094 mAttr.content_type, mAttr.usage, mAttr.source);
8095 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8096 if (mActiveTracks.size() == 0) {
8097 dprintf(fd, " No active clients\n");
8098 }
8099}
8100
8101void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8102{
8103 const size_t SIZE = 256;
8104 char buffer[SIZE];
8105 String8 result;
8106
8107 size_t numtracks = mActiveTracks.size();
8108 dprintf(fd, " %zu Tracks", numtracks);
8109 if (numtracks) {
8110 MmapTrack::appendDumpHeader(result);
8111 for (size_t i = 0; i < numtracks ; ++i) {
8112 sp<MmapTrack> track = mActiveTracks[i];
8113 track->dump(buffer, SIZE);
8114 result.append(buffer);
8115 }
8116 } else {
8117 dprintf(fd, "\n");
8118 }
8119 write(fd, result.string(), result.size());
8120}
8121
8122AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8123 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8124 AudioHwDevice *hwDev, AudioStreamOut *output,
8125 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8126 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8127 mStreamType(AUDIO_STREAM_MUSIC),
8128 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8129{
8130 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8131 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8132 mMasterVolume = audioFlinger->masterVolume_l();
8133 mMasterMute = audioFlinger->masterMute_l();
8134 if (mAudioHwDev) {
8135 if (mAudioHwDev->canSetMasterVolume()) {
8136 mMasterVolume = 1.0;
8137 }
8138
8139 if (mAudioHwDev->canSetMasterMute()) {
8140 mMasterMute = false;
8141 }
8142 }
8143}
8144
8145void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8146 audio_stream_type_t streamType,
8147 audio_session_t sessionId,
8148 const sp<MmapStreamCallback>& callback,
8149 audio_port_handle_t portId)
8150{
8151 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8152 mStreamType = streamType;
8153}
8154
8155AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8156{
8157 Mutex::Autolock _l(mLock);
8158 AudioStreamOut *output = mOutput;
8159 mOutput = NULL;
8160 return output;
8161}
8162
8163void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8164{
8165 Mutex::Autolock _l(mLock);
8166 // Don't apply master volume in SW if our HAL can do it for us.
8167 if (mAudioHwDev &&
8168 mAudioHwDev->canSetMasterVolume()) {
8169 mMasterVolume = 1.0;
8170 } else {
8171 mMasterVolume = value;
8172 }
8173}
8174
8175void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8176{
8177 Mutex::Autolock _l(mLock);
8178 // Don't apply master mute in SW if our HAL can do it for us.
8179 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8180 mMasterMute = false;
8181 } else {
8182 mMasterMute = muted;
8183 }
8184}
8185
8186void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8187{
8188 Mutex::Autolock _l(mLock);
8189 if (stream == mStreamType) {
8190 mStreamVolume = value;
8191 broadcast_l();
8192 }
8193}
8194
8195float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8196{
8197 Mutex::Autolock _l(mLock);
8198 if (stream == mStreamType) {
8199 return mStreamVolume;
8200 }
8201 return 0.0f;
8202}
8203
8204void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8205{
8206 Mutex::Autolock _l(mLock);
8207 if (stream == mStreamType) {
8208 mStreamMute= muted;
8209 broadcast_l();
8210 }
8211}
8212
8213void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8214{
8215 Mutex::Autolock _l(mLock);
8216 if (streamType == mStreamType) {
8217 for (const sp<MmapTrack> &track : mActiveTracks) {
8218 track->invalidate();
8219 }
8220 broadcast_l();
8221 }
8222}
8223
8224void AudioFlinger::MmapPlaybackThread::processVolume_l()
8225{
8226 float volume;
8227
8228 if (mMasterMute || mStreamMute) {
8229 volume = 0;
8230 } else {
8231 volume = mMasterVolume * mStreamVolume;
8232 }
8233
8234 if (volume != mHalVolFloat) {
8235 mHalVolFloat = volume;
8236
8237 // Convert volumes from float to 8.24
8238 uint32_t vol = (uint32_t)(volume * (1 << 24));
8239
8240 // Delegate volume control to effect in track effect chain if needed
8241 // only one effect chain can be present on DirectOutputThread, so if
8242 // there is one, the track is connected to it
8243 if (!mEffectChains.isEmpty()) {
8244 mEffectChains[0]->setVolume_l(&vol, &vol);
8245 volume = (float)vol / (1 << 24);
8246 }
8247
8248 mOutput->stream->setVolume(volume, volume);
8249
8250 if (mCallback != 0) {
8251 int channelCount;
8252 if (isOutput()) {
8253 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8254 } else {
8255 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8256 }
8257 Vector<float> values;
8258 for (int i = 0; i < channelCount; i++) {
8259 values.add(volume);
8260 }
8261 mCallback->onVolumeChanged(mChannelMask, values);
8262 }
8263 }
8264}
8265
8266void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8267{
8268 if (!mMasterMute) {
8269 char value[PROPERTY_VALUE_MAX];
8270 if (property_get("ro.audio.silent", value, "0") > 0) {
8271 char *endptr;
8272 unsigned long ul = strtoul(value, &endptr, 0);
8273 if (*endptr == '\0' && ul != 0) {
8274 ALOGD("Silence is golden");
8275 // The setprop command will not allow a property to be changed after
8276 // the first time it is set, so we don't have to worry about un-muting.
8277 setMasterMute_l(true);
8278 }
8279 }
8280 }
8281}
8282
8283void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8284{
8285 MmapThread::dumpInternals(fd, args);
8286
8287 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n", mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
8288 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8289}
8290
8291AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8292 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8293 AudioHwDevice *hwDev, AudioStreamIn *input,
8294 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8295 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8296 mInput(input)
8297{
8298 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8299 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8300}
8301
8302AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8303{
8304 Mutex::Autolock _l(mLock);
8305 AudioStreamIn *input = mInput;
8306 mInput = NULL;
8307 return input;
8308}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008309} // namespace android