blob: 8e6c72025bbb1860bd7e72f62f079f37d9e9abff [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>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080039#include <audio_utils/mono_blend.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
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700113
Eric Laurent51716182016-02-29 18:00:56 -0800114
Eric Laurent81784c32012-11-19 14:55:58 -0800115
116// don't warn about blocked writes or record buffer overflows more often than this
117static const nsecs_t kWarningThrottleNs = seconds(5);
118
119// RecordThread loop sleep time upon application overrun or audio HAL read error
120static const int kRecordThreadSleepUs = 5000;
121
Eric Laurent10351942014-05-08 18:49:52 -0700122// maximum time to wait in sendConfigEvent_l() for a status to be received
123static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800124
125// minimum sleep time for the mixer thread loop when tracks are active but in underrun
126static const uint32_t kMinThreadSleepTimeUs = 5000;
127// maximum divider applied to the active sleep time in the mixer thread loop
128static const uint32_t kMaxThreadSleepTimeShift = 2;
129
Andy Hung09a50072014-02-27 14:30:47 -0800130// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700131// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800132static const uint32_t kMinNormalSinkBufferSizeMs = 20;
133// maximum normal sink buffer size
134static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800135
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
137// FIXME This should be based on experimentally observed scheduling jitter
138static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
139
Eric Laurent972a1732013-09-04 09:42:59 -0700140// Offloaded output thread standby delay: allows track transition without going to standby
141static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
142
Eric Laurent51716182016-02-29 18:00:56 -0800143// Direct output thread minimum sleep time in idle or active(underrun) state
144static const nsecs_t kDirectMinSleepTimeUs = 10000;
145
Glenn Kasten1b291842016-07-18 14:55:21 -0700146// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
147// balance between power consumption and latency, and allows threads to be scheduled reliably
148// by the CFS scheduler.
149// FIXME Express other hardcoded references to 20ms with references to this constant and move
150// it appropriately.
151#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800152
Eric Laurent81784c32012-11-19 14:55:58 -0800153// Whether to use fast mixer
154static const enum {
155 FastMixer_Never, // never initialize or use: for debugging only
156 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
157 // normal mixer multiplier is 1
158 FastMixer_Static, // initialize if needed, then use all the time if initialized,
159 // multiplier is calculated based on min & max normal mixer buffer size
160 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 // FIXME for FastMixer_Dynamic:
163 // Supporting this option will require fixing HALs that can't handle large writes.
164 // For example, one HAL implementation returns an error from a large write,
165 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
166 // We could either fix the HAL implementations, or provide a wrapper that breaks
167 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
168} kUseFastMixer = FastMixer_Static;
169
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700170// Whether to use fast capture
171static const enum {
172 FastCapture_Never, // never initialize or use: for debugging only
173 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
174 FastCapture_Static, // initialize if needed, then use all the time if initialized
175} kUseFastCapture = FastCapture_Static;
176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// Priorities for requestPriority
178static const int kPriorityAudioApp = 2;
179static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700180static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800181
Glenn Kastenea38ee72016-04-18 11:08:01 -0700182// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
183// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
184// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700185
186// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800187static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800188
Glenn Kasten03490092014-05-27 12:30:54 -0700189// The minimum and maximum allowed values
190static const int kFastTrackMultiplierMin = 1;
191static const int kFastTrackMultiplierMax = 2;
192
193// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
194static int sFastTrackMultiplier = kFastTrackMultiplier;
195
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700196// See Thread::readOnlyHeap().
197// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
198// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
199// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten691b02a2017-10-03 10:12:20 -0700200static const size_t kRecordThreadReadOnlyHeapSize = 0x4000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// ----------------------------------------------------------------------------
203
Glenn Kasten03490092014-05-27 12:30:54 -0700204static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
205
206static void sFastTrackMultiplierInit()
207{
208 char value[PROPERTY_VALUE_MAX];
209 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
210 char *endptr;
211 unsigned long ul = strtoul(value, &endptr, 0);
212 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
213 sFastTrackMultiplier = (int) ul;
214 }
215 }
216}
217
218// ----------------------------------------------------------------------------
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220#ifdef ADD_BATTERY_DATA
221// To collect the amplifier usage
222static void addBatteryData(uint32_t params) {
223 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
224 if (service == NULL) {
225 // it already logged
226 return;
227 }
228
229 service->addBatteryData(params);
230}
231#endif
232
Andy Hung3f0c9022016-01-15 17:49:46 -0800233// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
234struct {
235 // call when you acquire a partial wakelock
236 void acquire(const sp<IBinder> &wakeLockToken) {
237 pthread_mutex_lock(&mLock);
238 if (wakeLockToken.get() == nullptr) {
239 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
240 } else {
241 if (mCount == 0) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 }
244 ++mCount;
245 }
246 pthread_mutex_unlock(&mLock);
247 }
248
249 // call when you release a partial wakelock.
250 void release(const sp<IBinder> &wakeLockToken) {
251 if (wakeLockToken.get() == nullptr) {
252 return;
253 }
254 pthread_mutex_lock(&mLock);
255 if (--mCount < 0) {
256 ALOGE("negative wakelock count");
257 mCount = 0;
258 }
259 pthread_mutex_unlock(&mLock);
260 }
261
262 // retrieves the boottime timebase offset from monotonic.
263 int64_t getBoottimeOffset() {
264 pthread_mutex_lock(&mLock);
265 int64_t boottimeOffset = mBoottimeOffset;
266 pthread_mutex_unlock(&mLock);
267 return boottimeOffset;
268 }
269
270 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
271 // and the selected timebase.
272 // Currently only TIMEBASE_BOOTTIME is allowed.
273 //
274 // This only needs to be called upon acquiring the first partial wakelock
275 // after all other partial wakelocks are released.
276 //
277 // We do an empirical measurement of the offset rather than parsing
278 // /proc/timer_list since the latter is not a formal kernel ABI.
279 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
280 int clockbase;
281 switch (timebase) {
282 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
283 clockbase = SYSTEM_TIME_BOOTTIME;
284 break;
285 default:
286 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
287 break;
288 }
289 // try three times to get the clock offset, choose the one
290 // with the minimum gap in measurements.
291 const int tries = 3;
292 nsecs_t bestGap, measured;
293 for (int i = 0; i < tries; ++i) {
294 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
295 const nsecs_t tbase = systemTime(clockbase);
296 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t gap = tmono2 - tmono;
298 if (i == 0 || gap < bestGap) {
299 bestGap = gap;
300 measured = tbase - ((tmono + tmono2) >> 1);
301 }
302 }
303
304 // to avoid micro-adjusting, we don't change the timebase
305 // unless it is significantly different.
306 //
307 // Assumption: It probably takes more than toleranceNs to
308 // suspend and resume the device.
309 static int64_t toleranceNs = 10000; // 10 us
310 if (llabs(*offset - measured) > toleranceNs) {
311 ALOGV("Adjusting timebase offset old: %lld new: %lld",
312 (long long)*offset, (long long)measured);
313 *offset = measured;
314 }
315 }
316
317 pthread_mutex_t mLock;
318 int32_t mCount;
319 int64_t mBoottimeOffset;
320} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800321
322// ----------------------------------------------------------------------------
323// CPU Stats
324// ----------------------------------------------------------------------------
325
326class CpuStats {
327public:
328 CpuStats();
329 void sample(const String8 &title);
330#ifdef DEBUG_CPU_USAGE
331private:
332 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
333 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
334
335 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
336
337 int mCpuNum; // thread's current CPU number
338 int mCpukHz; // frequency of thread's current CPU in kHz
339#endif
340};
341
342CpuStats::CpuStats()
343#ifdef DEBUG_CPU_USAGE
344 : mCpuNum(-1), mCpukHz(-1)
345#endif
346{
347}
348
Glenn Kasten0f11b512014-01-31 16:18:54 -0800349void CpuStats::sample(const String8 &title
350#ifndef DEBUG_CPU_USAGE
351 __unused
352#endif
353 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800354#ifdef DEBUG_CPU_USAGE
355 // get current thread's delta CPU time in wall clock ns
356 double wcNs;
357 bool valid = mCpuUsage.sampleAndEnable(wcNs);
358
359 // record sample for wall clock statistics
360 if (valid) {
361 mWcStats.sample(wcNs);
362 }
363
364 // get the current CPU number
365 int cpuNum = sched_getcpu();
366
367 // get the current CPU frequency in kHz
368 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
369
370 // check if either CPU number or frequency changed
371 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
372 mCpuNum = cpuNum;
373 mCpukHz = cpukHz;
374 // ignore sample for purposes of cycles
375 valid = false;
376 }
377
378 // if no change in CPU number or frequency, then record sample for cycle statistics
379 if (valid && mCpukHz > 0) {
380 double cycles = wcNs * cpukHz * 0.000001;
381 mHzStats.sample(cycles);
382 }
383
384 unsigned n = mWcStats.n();
385 // mCpuUsage.elapsed() is expensive, so don't call it every loop
386 if ((n & 127) == 1) {
387 long long elapsed = mCpuUsage.elapsed();
388 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
389 double perLoop = elapsed / (double) n;
390 double perLoop100 = perLoop * 0.01;
391 double perLoop1k = perLoop * 0.001;
392 double mean = mWcStats.mean();
393 double stddev = mWcStats.stddev();
394 double minimum = mWcStats.minimum();
395 double maximum = mWcStats.maximum();
396 double meanCycles = mHzStats.mean();
397 double stddevCycles = mHzStats.stddev();
398 double minCycles = mHzStats.minimum();
399 double maxCycles = mHzStats.maximum();
400 mCpuUsage.resetElapsed();
401 mWcStats.reset();
402 mHzStats.reset();
403 ALOGD("CPU usage for %s over past %.1f secs\n"
404 " (%u mixer loops at %.1f mean ms per loop):\n"
405 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
406 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
407 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
408 title.string(),
409 elapsed * .000000001, n, perLoop * .000001,
410 mean * .001,
411 stddev * .001,
412 minimum * .001,
413 maximum * .001,
414 mean / perLoop100,
415 stddev / perLoop100,
416 minimum / perLoop100,
417 maximum / perLoop100,
418 meanCycles / perLoop1k,
419 stddevCycles / perLoop1k,
420 minCycles / perLoop1k,
421 maxCycles / perLoop1k);
422
423 }
424 }
425#endif
426};
427
428// ----------------------------------------------------------------------------
429// ThreadBase
430// ----------------------------------------------------------------------------
431
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432// static
433const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
434{
435 switch (type) {
436 case MIXER:
437 return "MIXER";
438 case DIRECT:
439 return "DIRECT";
440 case DUPLICATING:
441 return "DUPLICATING";
442 case RECORD:
443 return "RECORD";
444 case OFFLOAD:
445 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800446 case MMAP:
447 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700448 default:
449 return "unknown";
450 }
451}
452
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700453std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 }
461 return result;
462}
463
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 std::string result;
467 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475 return result;
476}
477
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800478const char *sourceToString(audio_source_t source)
479{
480 switch (source) {
481 case AUDIO_SOURCE_DEFAULT: return "default";
482 case AUDIO_SOURCE_MIC: return "mic";
483 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
484 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
485 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
486 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
487 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
488 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
489 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800490 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800491 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
492 case AUDIO_SOURCE_HOTWORD: return "hotword";
493 default: return "unknown";
494 }
495}
496
Eric Laurent81784c32012-11-19 14:55:58 -0800497AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700498 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800499 : Thread(false /*canCallJava*/),
500 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700501 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700502 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800503 // are set by PlaybackThread::readOutputParameters_l() or
504 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700505 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800506 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700507 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
508 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800509 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700510 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800511 mSystemReady(systemReady),
512 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800513{
Eric Laurent296fb132015-05-01 11:38:42 -0700514 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
517AudioFlinger::ThreadBase::~ThreadBase()
518{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 mConfigEvents.clear();
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522 // do not lock the mutex in destructor
523 releaseWakeLock_l();
524 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800525 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800526 binder->unlinkToDeath(mDeathRecipient);
527 }
528}
529
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700530status_t AudioFlinger::ThreadBase::readyToRun()
531{
532 status_t status = initCheck();
533 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800534 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700535 } else {
536 ALOGE("No working audio driver found.");
537 }
538 return status;
539}
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541void AudioFlinger::ThreadBase::exit()
542{
543 ALOGV("ThreadBase::exit");
544 // do any cleanup required for exit to succeed
545 preExit();
546 {
547 // This lock prevents the following race in thread (uniprocessor for illustration):
548 // if (!exitPending()) {
549 // // context switch from here to exit()
550 // // exit() calls requestExit(), what exitPending() observes
551 // // exit() calls signal(), which is dropped since no waiters
552 // // context switch back from exit() to here
553 // mWaitWorkCV.wait(...);
554 // // now thread is hung
555 // }
556 AutoMutex lock(mLock);
557 requestExit();
558 mWaitWorkCV.broadcast();
559 }
560 // When Thread::requestExitAndWait is made virtual and this method is renamed to
561 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
562 requestExitAndWait();
563}
564
565status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
566{
Eric Laurent81784c32012-11-19 14:55:58 -0800567 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
568 Mutex::Autolock _l(mLock);
569
Eric Laurent10351942014-05-08 18:49:52 -0700570 return sendSetParameterConfigEvent_l(keyValuePairs);
571}
572
573// sendConfigEvent_l() must be called with ThreadBase::mLock held
574// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
575status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
576{
577 status_t status = NO_ERROR;
578
Eric Laurent72e3f392015-05-20 14:43:50 -0700579 if (event->mRequiresSystemReady && !mSystemReady) {
580 event->mWaitStatus = false;
581 mPendingConfigEvents.add(event);
582 return status;
583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700585 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800586 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700587 mLock.unlock();
588 {
589 Mutex::Autolock _l(event->mLock);
590 while (event->mWaitStatus) {
591 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
592 event->mStatus = TIMED_OUT;
593 event->mWaitStatus = false;
594 }
595 }
596 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800597 }
Eric Laurent10351942014-05-08 18:49:52 -0700598 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800599 return status;
600}
601
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700602void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
604 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
608// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700612 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800613}
614
Mikhail Naganov83f04272017-02-07 10:45:09 -0800615void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700616{
617 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800618 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800622void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
623 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800624{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800625 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700626 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800627}
628
Eric Laurent10351942014-05-08 18:49:52 -0700629// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
630status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
Andy Hung2ddee192015-12-18 17:34:44 -0800632 sp<ConfigEvent> configEvent;
633 AudioParameter param(keyValuePair);
634 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700635 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800636 setMasterMono_l(value != 0);
637 if (param.size() == 1) {
638 return NO_ERROR; // should be a solo parameter - we don't pass down
639 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700640 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800641 configEvent = new SetParameterConfigEvent(param.toString());
642 } else {
643 configEvent = new SetParameterConfigEvent(keyValuePair);
644 }
Eric Laurent10351942014-05-08 18:49:52 -0700645 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700646}
647
Eric Laurent1c333e22014-05-20 10:48:17 -0700648status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
649 const struct audio_patch *patch,
650 audio_patch_handle_t *handle)
651{
652 Mutex::Autolock _l(mLock);
653 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
654 status_t status = sendConfigEvent_l(configEvent);
655 if (status == NO_ERROR) {
656 CreateAudioPatchConfigEventData *data =
657 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
658 *handle = data->mHandle;
659 }
660 return status;
661}
662
663status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
664 const audio_patch_handle_t handle)
665{
666 Mutex::Autolock _l(mLock);
667 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
668 return sendConfigEvent_l(configEvent);
669}
670
671
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700672// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700673void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700674{
Eric Laurent10351942014-05-08 18:49:52 -0700675 bool configChanged = false;
676
Eric Laurent81784c32012-11-19 14:55:58 -0800677 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700678 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700679 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800680 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700681 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700682 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700683 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
684 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800685 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700686 true /*asynchronous*/);
687 if (err != 0) {
688 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700689 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700690 }
691 } break;
692 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700693 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700694 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700695 } break;
696 case CFG_EVENT_SET_PARAMETER: {
697 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
698 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
699 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700700 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
701 data->mKeyValuePairs.string());
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: {
Andy Hung293558a2017-03-21 12:19:20 -0700705 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700706 CreateAudioPatchConfigEventData *data =
707 (CreateAudioPatchConfigEventData *)event->mData.get();
708 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700709 const audio_devices_t newDevice = getDevice();
710 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
711 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
712 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700713 } break;
714 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700715 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700716 ReleaseAudioPatchConfigEventData *data =
717 (ReleaseAudioPatchConfigEventData *)event->mData.get();
718 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700719 const audio_devices_t newDevice = getDevice();
720 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
721 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
722 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700723 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700724 default:
Eric Laurent10351942014-05-08 18:49:52 -0700725 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700726 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800727 }
Eric Laurent10351942014-05-08 18:49:52 -0700728 {
729 Mutex::Autolock _l(event->mLock);
730 if (event->mWaitStatus) {
731 event->mWaitStatus = false;
732 event->mCond.signal();
733 }
734 }
735 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
736 }
737
738 if (configChanged) {
739 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800740 }
Eric Laurent81784c32012-11-19 14:55:58 -0800741}
742
Marco Nelissenb2208842014-02-07 14:00:50 -0800743String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
744 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700745 const audio_channel_representation_t representation =
746 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700747
748 switch (representation) {
749 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
750 if (output) {
751 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
752 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
754 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
755 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
762 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
769 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
770 } else {
771 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
772 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
773 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
774 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
775 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
776 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
780 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
781 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
782 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
783 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
784 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
785 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
786 }
787 const int len = s.length();
788 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700789 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700790 s.unlockBuffer(len - 2); // remove trailing ", "
791 }
792 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800793 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
795 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
796 return s;
797 default:
798 s.appendFormat("unknown mask, representation:%d bits:%#x",
799 representation, audio_channel_mask_get_bits(mask));
800 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800801 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800802}
803
Glenn Kasten0f11b512014-01-31 16:18:54 -0800804void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800805{
806 const size_t SIZE = 256;
807 char buffer[SIZE];
808 String8 result;
809
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800810 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
811 this, mThreadName, getTid(), type(), threadTypeToString(type()));
812
Eric Laurent81784c32012-11-19 14:55:58 -0800813 bool locked = AudioFlinger::dumpTryLock(mLock);
814 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800815 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800816 }
817
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700820 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700822 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700823 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " Channel count: %u\n", mChannelCount);
825 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800826 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700827 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700828 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800830 size_t numConfig = mConfigEvents.size();
831 if (numConfig) {
832 for (size_t i = 0; i < numConfig; i++) {
833 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800835 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800839 }
Andy Hung293558a2017-03-21 12:19:20 -0700840 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700841 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
842 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800843 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800844
845 if (locked) {
846 mLock.unlock();
847 }
848}
849
850void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
851{
852 const size_t SIZE = 256;
853 char buffer[SIZE];
854 String8 result;
855
Marco Nelissenb2208842014-02-07 14:00:50 -0800856 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000857 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800858 write(fd, buffer, strlen(buffer));
859
Marco Nelissenb2208842014-02-07 14:00:50 -0800860 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800861 sp<EffectChain> chain = mEffectChains[i];
862 if (chain != 0) {
863 chain->dump(fd, args);
864 }
865 }
866}
867
Andy Hungdae27702016-10-31 14:01:16 -0700868void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800869{
870 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700871 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800872}
873
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100874String16 AudioFlinger::ThreadBase::getWakeLockTag()
875{
876 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800877 case MIXER:
878 return String16("AudioMix");
879 case DIRECT:
880 return String16("AudioDirectOut");
881 case DUPLICATING:
882 return String16("AudioDup");
883 case RECORD:
884 return String16("AudioIn");
885 case OFFLOAD:
886 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800887 case MMAP:
888 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800889 default:
890 ALOG_ASSERT(false);
891 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100892 }
893}
894
Andy Hungdae27702016-10-31 14:01:16 -0700895void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800896{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800897 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800898 if (mPowerManager != 0) {
899 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700900 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
901 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700902 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100903 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700904 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700905 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800906 if (status == NO_ERROR) {
907 mWakeLockToken = binder;
908 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800909 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 }
Wei Jia3f273d12015-11-24 09:06:49 -0800911
Andy Hung3f0c9022016-01-15 17:49:46 -0800912 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800913 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
914 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800915}
916
917void AudioFlinger::ThreadBase::releaseWakeLock()
918{
919 Mutex::Autolock _l(mLock);
920 releaseWakeLock_l();
921}
922
923void AudioFlinger::ThreadBase::releaseWakeLock_l()
924{
Andy Hung3f0c9022016-01-15 17:49:46 -0800925 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800926 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800927 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700929 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
930 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 }
932 mWakeLockToken.clear();
933 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800934}
935
936void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700937 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800938 // use checkService() to avoid blocking if power service is not up yet
939 sp<IBinder> binder =
940 defaultServiceManager()->checkService(String16("power"));
941 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800942 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800943 } else {
944 mPowerManager = interface_cast<IPowerManager>(binder);
945 binder->linkToDeath(mDeathRecipient);
946 }
947 }
948}
949
Andy Hungd01b0f12016-11-07 16:10:30 -0800950void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700952
953#if !LOG_NDEBUG
954 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800955 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700956 s << uid << " ";
957 }
958 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
959#endif
960
Andy Hung438e7572015-12-14 15:51:17 -0800961 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
962 if (mSystemReady) {
963 ALOGE("no wake lock to update, but system ready!");
964 } else {
965 ALOGW("no wake lock to update, system not ready yet");
966 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800967 return;
968 }
969 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800970 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
971 status_t status = mPowerManager->updateWakeLockUids(
972 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
973 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800974 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800975 }
976}
977
Eric Laurent81784c32012-11-19 14:55:58 -0800978void AudioFlinger::ThreadBase::clearPowerManager()
979{
980 Mutex::Autolock _l(mLock);
981 releaseWakeLock_l();
982 mPowerManager.clear();
983}
984
Glenn Kasten0f11b512014-01-31 16:18:54 -0800985void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800986{
987 sp<ThreadBase> thread = mThread.promote();
988 if (thread != 0) {
989 thread->clearPowerManager();
990 }
991 ALOGW("power manager service died !!!");
992}
993
Eric Laurent81784c32012-11-19 14:55:58 -0800994void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800995 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800996{
997 sp<EffectChain> chain = getEffectChain_l(sessionId);
998 if (chain != 0) {
999 if (type != NULL) {
1000 chain->setEffectSuspended_l(type, suspend);
1001 } else {
1002 chain->setEffectSuspendedAll_l(suspend);
1003 }
1004 }
1005
1006 updateSuspendedSessions_l(type, suspend, sessionId);
1007}
1008
1009void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1010{
1011 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1012 if (index < 0) {
1013 return;
1014 }
1015
1016 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1017 mSuspendedSessions.valueAt(index);
1018
1019 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001020 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001021 for (int j = 0; j < desc->mRefCount; j++) {
1022 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1023 chain->setEffectSuspendedAll_l(true);
1024 } else {
1025 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1026 desc->mType.timeLow);
1027 chain->setEffectSuspended_l(&desc->mType, true);
1028 }
1029 }
1030 }
1031}
1032
1033void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1034 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001035 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001036{
1037 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1038
1039 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1040
1041 if (suspend) {
1042 if (index >= 0) {
1043 sessionEffects = mSuspendedSessions.valueAt(index);
1044 } else {
1045 mSuspendedSessions.add(sessionId, sessionEffects);
1046 }
1047 } else {
1048 if (index < 0) {
1049 return;
1050 }
1051 sessionEffects = mSuspendedSessions.valueAt(index);
1052 }
1053
1054
1055 int key = EffectChain::kKeyForSuspendAll;
1056 if (type != NULL) {
1057 key = type->timeLow;
1058 }
1059 index = sessionEffects.indexOfKey(key);
1060
1061 sp<SuspendedSessionDesc> desc;
1062 if (suspend) {
1063 if (index >= 0) {
1064 desc = sessionEffects.valueAt(index);
1065 } else {
1066 desc = new SuspendedSessionDesc();
1067 if (type != NULL) {
1068 desc->mType = *type;
1069 }
1070 sessionEffects.add(key, desc);
1071 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1072 }
1073 desc->mRefCount++;
1074 } else {
1075 if (index < 0) {
1076 return;
1077 }
1078 desc = sessionEffects.valueAt(index);
1079 if (--desc->mRefCount == 0) {
1080 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1081 sessionEffects.removeItemsAt(index);
1082 if (sessionEffects.isEmpty()) {
1083 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1084 sessionId);
1085 mSuspendedSessions.removeItem(sessionId);
1086 }
1087 }
1088 }
1089 if (!sessionEffects.isEmpty()) {
1090 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1091 }
1092}
1093
1094void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1095 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001096 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001097{
1098 Mutex::Autolock _l(mLock);
1099 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1103 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001104 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001105{
1106 if (mType != RECORD) {
1107 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1108 // another session. This gives the priority to well behaved effect control panels
1109 // and applications not using global effects.
1110 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1111 // global effects
1112 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1113 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1114 }
1115 }
1116
1117 sp<EffectChain> chain = getEffectChain_l(sessionId);
1118 if (chain != 0) {
1119 chain->checkSuspendOnEffectEnabled(effect, enabled);
1120 }
1121}
1122
Eric Laurent4c415062016-06-17 16:14:16 -07001123// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1124status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1125 const effect_descriptor_t *desc, audio_session_t sessionId)
1126{
1127 // No global effect sessions on record threads
1128 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1129 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1130 desc->name, mThreadName);
1131 return BAD_VALUE;
1132 }
1133 // only pre processing effects on record thread
1134 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1135 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1136 desc->name, mThreadName);
1137 return BAD_VALUE;
1138 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001139
1140 // always allow effects without processing load or latency
1141 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1142 return NO_ERROR;
1143 }
1144
Eric Laurent4c415062016-06-17 16:14:16 -07001145 audio_input_flags_t flags = mInput->flags;
1146 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1147 if (flags & AUDIO_INPUT_FLAG_RAW) {
1148 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1149 desc->name, mThreadName);
1150 return BAD_VALUE;
1151 }
1152 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1153 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1154 desc->name, mThreadName);
1155 return BAD_VALUE;
1156 }
1157 }
1158 return NO_ERROR;
1159}
1160
1161// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1162status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1163 const effect_descriptor_t *desc, audio_session_t sessionId)
1164{
1165 // no preprocessing on playback threads
1166 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1167 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1168 " thread %s", desc->name, mThreadName);
1169 return BAD_VALUE;
1170 }
1171
Eric Laurent3e4de772017-07-16 16:55:08 -07001172 // always allow effects without processing load or latency
1173 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1174 return NO_ERROR;
1175 }
1176
Eric Laurent4c415062016-06-17 16:14:16 -07001177 switch (mType) {
1178 case MIXER: {
1179 // Reject any effect on mixer multichannel sinks.
1180 // TODO: fix both format and multichannel issues with effects.
1181 if (mChannelCount != FCC_2) {
1182 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1183 " thread %s", desc->name, mChannelCount, mThreadName);
1184 return BAD_VALUE;
1185 }
1186 audio_output_flags_t flags = mOutput->flags;
1187 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1188 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1189 // global effects are applied only to non fast tracks if they are SW
1190 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1191 break;
1192 }
1193 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1194 // only post processing on output stage session
1195 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1196 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1197 " on output stage session", desc->name);
1198 return BAD_VALUE;
1199 }
1200 } else {
1201 // no restriction on effects applied on non fast tracks
1202 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1203 break;
1204 }
1205 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001206
Eric Laurent4c415062016-06-17 16:14:16 -07001207 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1208 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1209 desc->name);
1210 return BAD_VALUE;
1211 }
1212 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1213 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1214 " in fast mode", desc->name);
1215 return BAD_VALUE;
1216 }
1217 }
1218 } break;
1219 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001220 // nothing actionable on offload threads, if the effect:
1221 // - is offloadable: the effect can be created
1222 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1223 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001224 break;
1225 case DIRECT:
1226 // Reject any effect on Direct output threads for now, since the format of
1227 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1228 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1229 desc->name, mThreadName);
1230 return BAD_VALUE;
1231 case DUPLICATING:
1232 // Reject any effect on mixer multichannel sinks.
1233 // TODO: fix both format and multichannel issues with effects.
1234 if (mChannelCount != FCC_2) {
1235 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1236 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1237 return BAD_VALUE;
1238 }
1239 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1240 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1241 " thread %s", desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1245 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1246 " DUPLICATING thread %s", desc->name, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1250 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1251 " DUPLICATING thread %s", desc->name, mThreadName);
1252 return BAD_VALUE;
1253 }
1254 break;
1255 default:
1256 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1257 }
1258
1259 return NO_ERROR;
1260}
1261
Eric Laurent81784c32012-11-19 14:55:58 -08001262// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1263sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1264 const sp<AudioFlinger::Client>& client,
1265 const sp<IEffectClient>& effectClient,
1266 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001267 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001268 effect_descriptor_t *desc,
1269 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001270 status_t *status,
1271 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001272{
1273 sp<EffectModule> effect;
1274 sp<EffectHandle> handle;
1275 status_t lStatus;
1276 sp<EffectChain> chain;
1277 bool chainCreated = false;
1278 bool effectCreated = false;
1279 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001280 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001281
1282 lStatus = initCheck();
1283 if (lStatus != NO_ERROR) {
1284 ALOGW("createEffect_l() Audio driver not initialized.");
1285 goto Exit;
1286 }
1287
Eric Laurent81784c32012-11-19 14:55:58 -08001288 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1289
1290 { // scope for mLock
1291 Mutex::Autolock _l(mLock);
1292
Eric Laurent4c415062016-06-17 16:14:16 -07001293 lStatus = checkEffectCompatibility_l(desc, sessionId);
1294 if (lStatus != NO_ERROR) {
1295 goto Exit;
1296 }
1297
Eric Laurent81784c32012-11-19 14:55:58 -08001298 // check for existing effect chain with the requested audio session
1299 chain = getEffectChain_l(sessionId);
1300 if (chain == 0) {
1301 // create a new chain for this session
1302 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1303 chain = new EffectChain(this, sessionId);
1304 addEffectChain_l(chain);
1305 chain->setStrategy(getStrategyForSession_l(sessionId));
1306 chainCreated = true;
1307 } else {
1308 effect = chain->getEffectFromDesc_l(desc);
1309 }
1310
1311 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1312
1313 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001314 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001315 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001316 lStatus = AudioSystem::registerEffect(
1317 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001318 if (lStatus != NO_ERROR) {
1319 goto Exit;
1320 }
1321 effectRegistered = true;
1322 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001323 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (lStatus != NO_ERROR) {
1325 goto Exit;
1326 }
1327 effectCreated = true;
1328
1329 effect->setDevice(mOutDevice);
1330 effect->setDevice(mInDevice);
1331 effect->setMode(mAudioFlinger->getMode());
1332 effect->setAudioSource(mAudioSource);
1333 }
1334 // create effect handle and connect it to effect module
1335 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001336 lStatus = handle->initCheck();
1337 if (lStatus == OK) {
1338 lStatus = effect->addHandle(handle.get());
1339 }
Eric Laurent81784c32012-11-19 14:55:58 -08001340 if (enabled != NULL) {
1341 *enabled = (int)effect->isEnabled();
1342 }
1343 }
1344
1345Exit:
1346 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1347 Mutex::Autolock _l(mLock);
1348 if (effectCreated) {
1349 chain->removeEffect_l(effect);
1350 }
1351 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001352 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001353 }
1354 if (chainCreated) {
1355 removeEffectChain_l(chain);
1356 }
1357 handle.clear();
1358 }
1359
Glenn Kasten9156ef32013-08-06 15:39:08 -07001360 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001361 return handle;
1362}
1363
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001364void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1365 bool unpinIfLast)
1366{
1367 bool remove = false;
1368 sp<EffectModule> effect;
1369 {
1370 Mutex::Autolock _l(mLock);
1371
1372 effect = handle->effect().promote();
1373 if (effect == 0) {
1374 return;
1375 }
1376 // restore suspended effects if the disconnected handle was enabled and the last one.
1377 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1378 if (remove) {
1379 removeEffect_l(effect, true);
1380 }
1381 }
1382 if (remove) {
1383 mAudioFlinger->updateOrphanEffectChains(effect);
1384 AudioSystem::unregisterEffect(effect->id());
1385 if (handle->enabled()) {
1386 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1387 }
1388 }
1389}
1390
Glenn Kastend848eb42016-03-08 13:42:11 -08001391sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1392 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001393{
1394 Mutex::Autolock _l(mLock);
1395 return getEffect_l(sessionId, effectId);
1396}
1397
Glenn Kastend848eb42016-03-08 13:42:11 -08001398sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1399 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001400{
1401 sp<EffectChain> chain = getEffectChain_l(sessionId);
1402 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1403}
1404
1405// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1406// PlaybackThread::mLock held
1407status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1408{
1409 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001410 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001411 sp<EffectChain> chain = getEffectChain_l(sessionId);
1412 bool chainCreated = false;
1413
Eric Laurent5baf2af2013-09-12 17:37:00 -07001414 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1415 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1416 this, effect->desc().name, effect->desc().flags);
1417
Eric Laurent81784c32012-11-19 14:55:58 -08001418 if (chain == 0) {
1419 // create a new chain for this session
1420 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1421 chain = new EffectChain(this, sessionId);
1422 addEffectChain_l(chain);
1423 chain->setStrategy(getStrategyForSession_l(sessionId));
1424 chainCreated = true;
1425 }
1426 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1427
1428 if (chain->getEffectFromId_l(effect->id()) != 0) {
1429 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1430 this, effect->desc().name, chain.get());
1431 return BAD_VALUE;
1432 }
1433
Eric Laurent5baf2af2013-09-12 17:37:00 -07001434 effect->setOffloaded(mType == OFFLOAD, mId);
1435
Eric Laurent81784c32012-11-19 14:55:58 -08001436 status_t status = chain->addEffect_l(effect);
1437 if (status != NO_ERROR) {
1438 if (chainCreated) {
1439 removeEffectChain_l(chain);
1440 }
1441 return status;
1442 }
1443
1444 effect->setDevice(mOutDevice);
1445 effect->setDevice(mInDevice);
1446 effect->setMode(mAudioFlinger->getMode());
1447 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001448
Eric Laurent81784c32012-11-19 14:55:58 -08001449 return NO_ERROR;
1450}
1451
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001452void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001453
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001454 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001455 effect_descriptor_t desc = effect->desc();
1456 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1457 detachAuxEffect_l(effect->id());
1458 }
1459
1460 sp<EffectChain> chain = effect->chain().promote();
1461 if (chain != 0) {
1462 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001463 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001464 removeEffectChain_l(chain);
1465 }
1466 } else {
1467 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1468 }
1469}
1470
1471void AudioFlinger::ThreadBase::lockEffectChains_l(
1472 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1473{
1474 effectChains = mEffectChains;
1475 for (size_t i = 0; i < mEffectChains.size(); i++) {
1476 mEffectChains[i]->lock();
1477 }
1478}
1479
1480void AudioFlinger::ThreadBase::unlockEffectChains(
1481 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1482{
1483 for (size_t i = 0; i < effectChains.size(); i++) {
1484 effectChains[i]->unlock();
1485 }
1486}
1487
Glenn Kastend848eb42016-03-08 13:42:11 -08001488sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001489{
1490 Mutex::Autolock _l(mLock);
1491 return getEffectChain_l(sessionId);
1492}
1493
Glenn Kastend848eb42016-03-08 13:42:11 -08001494sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1495 const
Eric Laurent81784c32012-11-19 14:55:58 -08001496{
1497 size_t size = mEffectChains.size();
1498 for (size_t i = 0; i < size; i++) {
1499 if (mEffectChains[i]->sessionId() == sessionId) {
1500 return mEffectChains[i];
1501 }
1502 }
1503 return 0;
1504}
1505
1506void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1507{
1508 Mutex::Autolock _l(mLock);
1509 size_t size = mEffectChains.size();
1510 for (size_t i = 0; i < size; i++) {
1511 mEffectChains[i]->setMode_l(mode);
1512 }
1513}
1514
Eric Laurent83b88082014-06-20 18:31:16 -07001515void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1516{
1517 config->type = AUDIO_PORT_TYPE_MIX;
1518 config->ext.mix.handle = mId;
1519 config->sample_rate = mSampleRate;
1520 config->format = mFormat;
1521 config->channel_mask = mChannelMask;
1522 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1523 AUDIO_PORT_CONFIG_FORMAT;
1524}
1525
Eric Laurent72e3f392015-05-20 14:43:50 -07001526void AudioFlinger::ThreadBase::systemReady()
1527{
1528 Mutex::Autolock _l(mLock);
1529 if (mSystemReady) {
1530 return;
1531 }
1532 mSystemReady = true;
1533
1534 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1535 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1536 }
1537 mPendingConfigEvents.clear();
1538}
1539
Andy Hungdae27702016-10-31 14:01:16 -07001540template <typename T>
1541ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1542 ssize_t index = mActiveTracks.indexOf(track);
1543 if (index >= 0) {
1544 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1545 return index;
1546 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001547 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001548 mActiveTracksGeneration++;
1549 mLatestActiveTrack = track;
1550 ++mBatteryCounter[track->uid()].second;
1551 return mActiveTracks.add(track);
1552}
1553
1554template <typename T>
1555ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1556 ssize_t index = mActiveTracks.remove(track);
1557 if (index < 0) {
1558 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1559 return index;
1560 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001561 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001562 mActiveTracksGeneration++;
1563 --mBatteryCounter[track->uid()].second;
1564 // mLatestActiveTrack is not cleared even if is the same as track.
1565 return index;
1566}
1567
1568template <typename T>
1569void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1570 for (const sp<T> &track : mActiveTracks) {
1571 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001572 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001573 }
1574 mLastActiveTracksGeneration = mActiveTracksGeneration;
1575 mActiveTracks.clear();
1576 mLatestActiveTrack.clear();
1577 mBatteryCounter.clear();
1578}
1579
1580template <typename T>
1581void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1582 sp<ThreadBase> thread, bool force) {
1583 // Updates ActiveTracks client uids to the thread wakelock.
1584 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1585 thread->updateWakeLockUids_l(getWakeLockUids());
1586 mLastActiveTracksGeneration = mActiveTracksGeneration;
1587 }
1588
1589 // Updates BatteryNotifier uids
1590 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1591 const uid_t uid = it->first;
1592 ssize_t &previous = it->second.first;
1593 ssize_t &current = it->second.second;
1594 if (current > 0) {
1595 if (previous == 0) {
1596 BatteryNotifier::getInstance().noteStartAudio(uid);
1597 }
1598 previous = current;
1599 ++it;
1600 } else if (current == 0) {
1601 if (previous > 0) {
1602 BatteryNotifier::getInstance().noteStopAudio(uid);
1603 }
1604 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1605 } else /* (current < 0) */ {
1606 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1607 }
1608 }
1609}
Eric Laurent83b88082014-06-20 18:31:16 -07001610
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001611template <typename T>
1612void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1613 const char *funcName, const sp<T> &track) const {
1614 if (mLocalLog != nullptr) {
1615 String8 result;
1616 track->appendDump(result, false /* active */);
1617 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1618 }
1619}
1620
Eric Laurent6acd1d42017-01-04 14:23:29 -08001621void AudioFlinger::ThreadBase::broadcast_l()
1622{
1623 // Thread could be blocked waiting for async
1624 // so signal it to handle state changes immediately
1625 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1626 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1627 mSignalPending = true;
1628 mWaitWorkCV.broadcast();
1629}
1630
Eric Laurent81784c32012-11-19 14:55:58 -08001631// ----------------------------------------------------------------------------
1632// Playback
1633// ----------------------------------------------------------------------------
1634
1635AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1636 AudioStreamOut* output,
1637 audio_io_handle_t id,
1638 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001639 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001640 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001641 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001642 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001643 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001644 mMixerBuffer(NULL),
1645 mMixerBufferSize(0),
1646 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1647 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001648 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001649 mEffectBuffer(NULL),
1650 mEffectBufferSize(0),
1651 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1652 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001653 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001654 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001655 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001656 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001657 // mStreamTypes[] initialized in constructor body
1658 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001659 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001660 mMixerStatus(MIXER_IDLE),
1661 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001662 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001663 mBytesRemaining(0),
1664 mCurrentWriteLength(0),
1665 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001666 mWriteAckSequence(0),
1667 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001668 mScreenState(AudioFlinger::mScreenState),
1669 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001670 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001671 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1672 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001673{
Glenn Kastend7dca052015-03-05 16:05:54 -08001674 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1675 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001676
1677 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1678 // it would be safer to explicitly pass initial masterVolume/masterMute as
1679 // parameter.
1680 //
1681 // If the HAL we are using has support for master volume or master mute,
1682 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1683 // and the mute set to false).
1684 mMasterVolume = audioFlinger->masterVolume_l();
1685 mMasterMute = audioFlinger->masterMute_l();
1686 if (mOutput && mOutput->audioHwDev) {
1687 if (mOutput->audioHwDev->canSetMasterVolume()) {
1688 mMasterVolume = 1.0;
1689 }
1690
1691 if (mOutput->audioHwDev->canSetMasterMute()) {
1692 mMasterMute = false;
1693 }
1694 }
1695
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001696 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001697
Eric Laurent223fd5c2014-11-11 13:43:36 -08001698 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001699 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001700 stream = (audio_stream_type_t) (stream + 1)) {
1701 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1702 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1703 }
Eric Laurent81784c32012-11-19 14:55:58 -08001704}
1705
1706AudioFlinger::PlaybackThread::~PlaybackThread()
1707{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001708 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001709 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001710 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001711 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001712}
1713
1714void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1715{
1716 dumpInternals(fd, args);
1717 dumpTracks(fd, args);
1718 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001719 dprintf(fd, " Local log:\n");
1720 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001721}
1722
Glenn Kasten0f11b512014-01-31 16:18:54 -08001723void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001724{
Eric Laurent81784c32012-11-19 14:55:58 -08001725 String8 result;
1726
Marco Nelissenb2208842014-02-07 14:00:50 -08001727 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001728 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1729 const stream_type_t *st = &mStreamTypes[i];
1730 if (i > 0) {
1731 result.appendFormat(", ");
1732 }
1733 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1734 if (st->mute) {
1735 result.append("M");
1736 }
1737 }
1738 result.append("\n");
1739 write(fd, result.string(), result.length());
1740 result.clear();
1741
Eric Laurent81784c32012-11-19 14:55:58 -08001742 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1743 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001744 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001745 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001746
1747 size_t numtracks = mTracks.size();
1748 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001749 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001750 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001751 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001752 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001753 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001754 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001755 Track::appendDumpHeader(result);
1756 for (size_t i = 0; i < numtracks; ++i) {
1757 sp<Track> track = mTracks[i];
1758 if (track != 0) {
1759 bool active = mActiveTracks.indexOf(track) >= 0;
1760 if (active) {
1761 numactiveseen++;
1762 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001763 result.append(prefix);
1764 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001765 }
1766 }
1767 } else {
1768 result.append("\n");
1769 }
1770 if (numactiveseen != numactive) {
1771 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001772 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001773 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001774 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001775 Track::appendDumpHeader(result);
1776 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001777 sp<Track> track = mActiveTracks[i];
1778 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001779 result.append(prefix);
1780 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001781 }
1782 }
1783 }
1784
1785 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001786}
1787
1788void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1789{
Glenn Kasten44182c22015-03-05 17:12:23 -08001790 dumpBase(fd, args);
1791
Elliott Hughes87cebad2014-05-22 10:14:43 -07001792 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001793 dprintf(fd, " Last write occurred (msecs): %llu\n",
1794 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001795 dprintf(fd, " Total writes: %d\n", mNumWrites);
1796 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1797 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1798 dprintf(fd, " Suspend count: %d\n", mSuspended);
1799 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1800 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1801 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1802 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001803 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001804 AudioStreamOut *output = mOutput;
1805 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001806 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1807 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001808 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1809 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1810 if (mPipeSink.get() != nullptr) {
1811 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1812 }
1813 if (output != nullptr) {
1814 dprintf(fd, " Hal stream dump:\n");
1815 (void)output->stream->dump(fd);
1816 }
Eric Laurent81784c32012-11-19 14:55:58 -08001817}
1818
1819// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001820
1821void AudioFlinger::PlaybackThread::onFirstRef()
1822{
Glenn Kastend7dca052015-03-05 16:05:54 -08001823 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001824}
1825
1826// ThreadBase virtuals
1827void AudioFlinger::PlaybackThread::preExit()
1828{
1829 ALOGV(" preExit()");
1830 // FIXME this is using hard-coded strings but in the future, this functionality will be
1831 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001832 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1833 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001834}
1835
1836// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1837sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1838 const sp<AudioFlinger::Client>& client,
1839 audio_stream_type_t streamType,
Eric Laurent21da6472017-11-09 16:29:26 -08001840 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001841 audio_format_t format,
1842 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001843 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001844 size_t *pNotificationFrameCount,
1845 uint32_t notificationsPerBuffer,
1846 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001847 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001848 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001849 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001850 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001851 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001852 status_t *status,
1853 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001854{
Glenn Kasten74935e42013-12-19 08:56:45 -08001855 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001856 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001857 sp<Track> track;
1858 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001859 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001860 audio_output_flags_t requestedFlags = *flags;
1861
1862 if (*pSampleRate == 0) {
1863 *pSampleRate = mSampleRate;
1864 }
1865 uint32_t sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001866
1867 // special case for FAST flag considered OK if fast mixer is present
1868 if (hasFastMixer()) {
1869 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1870 }
1871
1872 // Check if requested flags are compatible with output stream flags
1873 if ((*flags & outputFlags) != *flags) {
1874 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1875 *flags, outputFlags);
1876 *flags = (audio_output_flags_t)(*flags & outputFlags);
1877 }
Eric Laurent81784c32012-11-19 14:55:58 -08001878
Eric Laurent81784c32012-11-19 14:55:58 -08001879 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001880 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001881 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001882 // PCM data
1883 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001884 // TODO: extract as a data library function that checks that a computationally
1885 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001886 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001887 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1888 (channelMask == AUDIO_CHANNEL_OUT_MONO
1889 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001890 // hardware sample rate
1891 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001892 // normal mixer has an associated fast mixer
1893 hasFastMixer() &&
1894 // there are sufficient fast track slots available
1895 (mFastTrackAvailMask != 0)
1896 // FIXME test that MixerThread for this fast track has a capable output HAL
1897 // FIXME add a permission test also?
1898 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001899 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1900 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001901 // read the fast track multiplier property the first time it is needed
1902 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1903 if (ok != 0) {
1904 ALOGE("%s pthread_once failed: %d", __func__, ok);
1905 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001906 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001907 }
Eric Laurent4c415062016-06-17 16:14:16 -07001908
1909 // check compatibility with audio effects.
1910 { // scope for mLock
1911 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001912 for (audio_session_t session : {
1913 AUDIO_SESSION_OUTPUT_STAGE,
1914 AUDIO_SESSION_OUTPUT_MIX,
1915 sessionId,
1916 }) {
1917 sp<EffectChain> chain = getEffectChain_l(session);
1918 if (chain.get() != nullptr) {
1919 audio_output_flags_t old = *flags;
1920 chain->checkOutputFlagCompatibility(flags);
1921 if (old != *flags) {
1922 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1923 (int)session, (int)old, (int)*flags);
1924 }
Eric Laurent4c415062016-06-17 16:14:16 -07001925 }
1926 }
1927 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001928 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001929 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1930 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001931 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001932 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1933 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001934 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001935 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001936 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001937 audio_is_linear_pcm(format),
1938 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001939 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001940 }
1941 }
Eric Laurent21da6472017-11-09 16:29:26 -08001942
1943 if (!audio_has_proportional_frames(format)) {
1944 if (sharedBuffer != 0) {
1945 // Same comment as below about ignoring frameCount parameter for set()
1946 frameCount = sharedBuffer->size();
1947 } else if (frameCount == 0) {
1948 frameCount = mNormalFrameCount;
1949 }
1950 if (notificationFrameCount != frameCount) {
1951 notificationFrameCount = frameCount;
1952 }
1953 } else if (sharedBuffer != 0) {
1954 // FIXME: Ensure client side memory buffers need
1955 // not have additional alignment beyond sample
1956 // (e.g. 16 bit stereo accessed as 32 bit frame).
1957 size_t alignment = audio_bytes_per_sample(format);
1958 if (alignment & 1) {
1959 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
1960 alignment = 1;
1961 }
1962 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1963 size_t frameSize = channelCount * audio_bytes_per_sample(format);
1964 if (channelCount > 1) {
1965 // More than 2 channels does not require stronger alignment than stereo
1966 alignment <<= 1;
1967 }
1968 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
1969 ALOGE("Invalid buffer alignment: address %p, channel count %u",
1970 sharedBuffer->pointer(), channelCount);
1971 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001972 goto Exit;
1973 }
Eric Laurent21da6472017-11-09 16:29:26 -08001974
1975 // When initializing a shared buffer AudioTrack via constructors,
1976 // there's no frameCount parameter.
1977 // But when initializing a shared buffer AudioTrack via set(),
1978 // there _is_ a frameCount parameter. We silently ignore it.
1979 frameCount = sharedBuffer->size() / frameSize;
1980 } else {
1981 size_t minFrameCount = 0;
1982 // For fast tracks we try to respect the application's request for notifications per buffer.
1983 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
1984 if (notificationsPerBuffer > 0) {
1985 // Avoid possible arithmetic overflow during multiplication.
1986 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
1987 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
1988 notificationsPerBuffer, mFrameCount);
1989 } else {
1990 minFrameCount = mFrameCount * notificationsPerBuffer;
1991 }
1992 }
1993 } else {
1994 // For normal PCM streaming tracks, update minimum frame count.
1995 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
1996 // cover audio hardware latency.
1997 // This is probably too conservative, but legacy application code may depend on it.
1998 // If you change this calculation, also review the start threshold which is related.
1999 uint32_t latencyMs = latency_l();
2000 if (latencyMs == 0) {
2001 ALOGE("Error when retrieving output stream latency");
2002 lStatus = UNKNOWN_ERROR;
2003 goto Exit;
2004 }
2005
2006 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2007 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2008
Eric Laurent81784c32012-11-19 14:55:58 -08002009 }
Eric Laurent21da6472017-11-09 16:29:26 -08002010 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002011 frameCount = minFrameCount;
2012 }
Eric Laurent81784c32012-11-19 14:55:58 -08002013 }
Eric Laurent21da6472017-11-09 16:29:26 -08002014
2015 // Make sure that application is notified with sufficient margin before underrun.
2016 // The client can divide the AudioTrack buffer into sub-buffers,
2017 // and expresses its desire to server as the notification frame count.
2018 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2019 size_t maxNotificationFrames;
2020 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2021 // notify every HAL buffer, regardless of the size of the track buffer
2022 maxNotificationFrames = mFrameCount;
2023 } else {
2024 // For normal tracks, use at least double-buffering if no sample rate conversion,
2025 // or at least triple-buffering if there is sample rate conversion
2026 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2027 maxNotificationFrames = frameCount / nBuffering;
2028 // If client requested a fast track but this was denied, then use the smaller maximum.
2029 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2030 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2031 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2032 maxNotificationFrames = maxNotificationFramesFastDenied;
2033 }
2034 }
2035 }
2036 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2037 if (notificationFrameCount == 0) {
2038 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2039 maxNotificationFrames, frameCount);
2040 } else {
2041 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2042 notificationFrameCount, maxNotificationFrames, frameCount);
2043 }
2044 notificationFrameCount = maxNotificationFrames;
2045 }
2046 }
2047
Glenn Kasten74935e42013-12-19 08:56:45 -08002048 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002049 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002050
Glenn Kastenc3df8382014-03-13 15:05:25 -07002051 switch (mType) {
2052
2053 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002054 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002055 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002056 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2057 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002058 sampleRate, format, channelMask, mOutput, mFormat);
2059 lStatus = BAD_VALUE;
2060 goto Exit;
2061 }
2062 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002063 break;
2064
2065 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002066 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002067 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2068 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002069 sampleRate, format, channelMask, mOutput, mFormat);
2070 lStatus = BAD_VALUE;
2071 goto Exit;
2072 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002073 break;
2074
2075 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002076 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002077 ALOGE("createTrack_l() Bad parameter: format %#x \""
2078 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002079 format, mOutput, mFormat);
2080 lStatus = BAD_VALUE;
2081 goto Exit;
2082 }
Andy Hungcd044842014-08-07 11:04:34 -07002083 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002084 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2085 lStatus = BAD_VALUE;
2086 goto Exit;
2087 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002088 break;
2089
Eric Laurent81784c32012-11-19 14:55:58 -08002090 }
2091
2092 lStatus = initCheck();
2093 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002094 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002095 goto Exit;
2096 }
2097
2098 { // scope for mLock
2099 Mutex::Autolock _l(mLock);
2100
2101 // all tracks in same audio session must share the same routing strategy otherwise
2102 // conflicts will happen when tracks are moved from one output to another by audio policy
2103 // manager
2104 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2105 for (size_t i = 0; i < mTracks.size(); ++i) {
2106 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002107 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002108 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2109 if (sessionId == t->sessionId() && strategy != actual) {
2110 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2111 strategy, actual);
2112 lStatus = BAD_VALUE;
2113 goto Exit;
2114 }
2115 }
2116 }
2117
Glenn Kastend79072e2016-01-06 08:41:20 -08002118 track = new Track(this, client, streamType, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002119 channelMask, frameCount,
2120 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002121 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002122
Glenn Kasten03003332013-08-06 15:40:54 -07002123 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2124 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002125 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002126 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002127 goto Exit;
2128 }
2129 mTracks.add(track);
2130
2131 sp<EffectChain> chain = getEffectChain_l(sessionId);
2132 if (chain != 0) {
2133 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2134 track->setMainBuffer(chain->inBuffer());
2135 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2136 chain->incTrackCnt();
2137 }
2138
Eric Laurent05067782016-06-01 18:27:28 -07002139 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002140 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2141 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2142 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002143 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002144 }
2145 }
2146
2147 lStatus = NO_ERROR;
2148
2149Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002150 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002151 return track;
2152}
2153
2154uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2155{
2156 return latency;
2157}
2158
2159uint32_t AudioFlinger::PlaybackThread::latency() const
2160{
2161 Mutex::Autolock _l(mLock);
2162 return latency_l();
2163}
2164uint32_t AudioFlinger::PlaybackThread::latency_l() const
2165{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002166 uint32_t latency;
2167 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2168 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002169 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002170 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002171}
2172
2173void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2174{
2175 Mutex::Autolock _l(mLock);
2176 // Don't apply master volume in SW if our HAL can do it for us.
2177 if (mOutput && mOutput->audioHwDev &&
2178 mOutput->audioHwDev->canSetMasterVolume()) {
2179 mMasterVolume = 1.0;
2180 } else {
2181 mMasterVolume = value;
2182 }
2183}
2184
2185void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2186{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002187 if (isDuplicating()) {
2188 return;
2189 }
Eric Laurent81784c32012-11-19 14:55:58 -08002190 Mutex::Autolock _l(mLock);
2191 // Don't apply master mute in SW if our HAL can do it for us.
2192 if (mOutput && mOutput->audioHwDev &&
2193 mOutput->audioHwDev->canSetMasterMute()) {
2194 mMasterMute = false;
2195 } else {
2196 mMasterMute = muted;
2197 }
2198}
2199
2200void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2201{
2202 Mutex::Autolock _l(mLock);
2203 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002204 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002205}
2206
2207void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2208{
2209 Mutex::Autolock _l(mLock);
2210 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002211 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002212}
2213
2214float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2215{
2216 Mutex::Autolock _l(mLock);
2217 return mStreamTypes[stream].volume;
2218}
2219
2220// addTrack_l() must be called with ThreadBase::mLock held
2221status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2222{
2223 status_t status = ALREADY_EXISTS;
2224
Eric Laurent81784c32012-11-19 14:55:58 -08002225 if (mActiveTracks.indexOf(track) < 0) {
2226 // the track is newly added, make sure it fills up all its
2227 // buffers before playing. This is to ensure the client will
2228 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002229 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002230 TrackBase::track_state state = track->mState;
2231 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002232 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002233 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002234 mLock.lock();
2235 // abort track was stopped/paused while we released the lock
2236 if (state != track->mState) {
2237 if (status == NO_ERROR) {
2238 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002239 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002240 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002241 mLock.lock();
2242 }
2243 return INVALID_OPERATION;
2244 }
2245 // abort if start is rejected by audio policy manager
2246 if (status != NO_ERROR) {
2247 return PERMISSION_DENIED;
2248 }
2249#ifdef ADD_BATTERY_DATA
2250 // to track the speaker usage
2251 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2252#endif
2253 }
2254
Eric Laurent51716182016-02-29 18:00:56 -08002255 // set retry count for buffer fill
2256 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002257 if (track->isStopping_1()) {
2258 track->mRetryCount = kMaxTrackStopRetriesOffload;
2259 } else {
2260 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2261 }
2262 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002263 } else {
2264 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002265 track->mFillingUpStatus =
2266 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002267 }
2268
Eric Laurent81784c32012-11-19 14:55:58 -08002269 track->mResetDone = false;
2270 track->mPresentationCompleteFrames = 0;
2271 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002272 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2273 if (chain != 0) {
2274 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2275 track->sessionId());
2276 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002277 }
2278
2279 status = NO_ERROR;
2280 }
2281
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002282 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002283 return status;
2284}
2285
Eric Laurentbfb1b832013-01-07 09:53:42 -08002286bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002287{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002289 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002290 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2291 track->mState = TrackBase::STOPPED;
2292 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002293 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002294 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002295 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002296 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002297
2298 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002299}
2300
2301void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2302{
2303 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002304
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002305 String8 result;
2306 track->appendDump(result, false /* active */);
2307 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002308
Eric Laurent81784c32012-11-19 14:55:58 -08002309 mTracks.remove(track);
2310 deleteTrackName_l(track->name());
2311 // redundant as track is about to be destroyed, for dumpsys only
2312 track->mName = -1;
2313 if (track->isFastTrack()) {
2314 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002315 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002316 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2317 mFastTrackAvailMask |= 1 << index;
2318 // redundant as track is about to be destroyed, for dumpsys only
2319 track->mFastIndex = -1;
2320 }
2321 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2322 if (chain != 0) {
2323 chain->decTrackCnt();
2324 }
2325}
2326
2327String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2328{
Eric Laurent81784c32012-11-19 14:55:58 -08002329 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002330 String8 out_s8;
2331 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2332 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002333 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002334 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002335}
2336
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002337void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002338 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2339 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002340
Eric Laurent73e26b62015-04-27 16:55:58 -07002341 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002342
2343 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002344 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002345 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002346 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002347 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002348 desc->mChannelMask = mChannelMask;
2349 desc->mSamplingRate = mSampleRate;
2350 desc->mFormat = mFormat;
2351 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002352 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002353 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002354 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002355 break;
2356
Eric Laurent73e26b62015-04-27 16:55:58 -07002357 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002358 default:
2359 break;
2360 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002361 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002362}
2363
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002364void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002365{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002366 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002367}
2368
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002369void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002370{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002371 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002372}
2373
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002374void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002375{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002376 mCallbackThread->setAsyncError();
2377}
2378
Eric Laurent3b4529e2013-09-05 18:09:19 -07002379void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002380{
2381 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002382 // reject out of sequence requests
2383 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2384 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002385 mWaitWorkCV.signal();
2386 }
2387}
2388
Eric Laurent3b4529e2013-09-05 18:09:19 -07002389void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390{
2391 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002392 // reject out of sequence requests
2393 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2394 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395 mWaitWorkCV.signal();
2396 }
2397}
2398
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002399void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002400{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002401 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002402 mSampleRate = mOutput->getSampleRate();
2403 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002404 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002405 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002406 }
Andy Hung9a592762014-07-21 21:56:01 -07002407 if ((mType == MIXER || mType == DUPLICATING)
2408 && !isValidPcmSinkChannelMask(mChannelMask)) {
2409 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2410 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002411 }
Andy Hunge5412692014-05-16 11:25:07 -07002412 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002413
2414 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002415 status_t result = mOutput->stream->getFormat(&mHALFormat);
2416 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002417 // Get format from the shim, which will be different than the HAL format
2418 // if playing compressed audio over HDMI passthrough.
2419 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002420 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002421 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002422 }
Andy Hung6146c082014-03-18 11:56:15 -07002423 if ((mType == MIXER || mType == DUPLICATING)
2424 && !isValidPcmSinkFormat(mFormat)) {
2425 LOG_FATAL("HAL format %#x not supported for mixed output",
2426 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002427 }
Phil Burk062e67a2015-02-11 13:40:50 -08002428 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002429 result = mOutput->stream->getBufferSize(&mBufferSize);
2430 LOG_ALWAYS_FATAL_IF(result != OK,
2431 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002432 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002433 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002434 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002435 mFrameCount);
2436 }
2437
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002438 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2439 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002440 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002441 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002442 }
2443 }
2444
Eric Laurentd1f69b02014-12-15 14:33:13 -08002445 mHwSupportsPause = false;
2446 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002447 bool supportsPause = false, supportsResume = false;
2448 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2449 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002450 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002451 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002452 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002453 } else if (supportsResume) {
2454 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002455 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002456 }
2457 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002458 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2459 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2460 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002461
Andy Hungfbfc3952015-01-15 13:33:51 -08002462 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2463 // For best precision, we use float instead of the associated output
2464 // device format (typically PCM 16 bit).
2465
2466 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2467 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2468 mBufferSize = mFrameSize * mFrameCount;
2469
2470 // TODO: We currently use the associated output device channel mask and sample rate.
2471 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2472 // (if a valid mask) to avoid premature downmix.
2473 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2474 // instead of the output device sample rate to avoid loss of high frequency information.
2475 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2476 }
2477
Andy Hung09a50072014-02-27 14:30:47 -08002478 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002479 double multiplier = 1.0;
2480 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2481 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002482 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2483 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002484
Eric Laurent81784c32012-11-19 14:55:58 -08002485 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2486 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2487 maxNormalFrameCount = maxNormalFrameCount & ~15;
2488 if (maxNormalFrameCount < minNormalFrameCount) {
2489 maxNormalFrameCount = minNormalFrameCount;
2490 }
2491 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2492 if (multiplier <= 1.0) {
2493 multiplier = 1.0;
2494 } else if (multiplier <= 2.0) {
2495 if (2 * mFrameCount <= maxNormalFrameCount) {
2496 multiplier = 2.0;
2497 } else {
2498 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2499 }
2500 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002501 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002502 }
2503 }
2504 mNormalFrameCount = multiplier * mFrameCount;
2505 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002506 if (mType == MIXER || mType == DUPLICATING) {
2507 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2508 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002509 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002510 mNormalFrameCount);
2511
Andy Hung08fb1742015-05-31 23:22:10 -07002512 // Check if we want to throttle the processing to no more than 2x normal rate
2513 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002514 mThreadThrottleTimeMs = 0;
2515 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002516 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2517
Andy Hung010a1a12014-03-13 13:57:33 -07002518 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2519 // Originally this was int16_t[] array, need to remove legacy implications.
2520 free(mSinkBuffer);
2521 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002522 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2523 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2524 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002525 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002526
Andy Hung69aed5f2014-02-25 17:24:40 -08002527 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2528 // drives the output.
2529 free(mMixerBuffer);
2530 mMixerBuffer = NULL;
2531 if (mMixerBufferEnabled) {
2532 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2533 mMixerBufferSize = mNormalFrameCount * mChannelCount
2534 * audio_bytes_per_sample(mMixerBufferFormat);
2535 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2536 }
Andy Hung98ef9782014-03-04 14:46:50 -08002537 free(mEffectBuffer);
2538 mEffectBuffer = NULL;
2539 if (mEffectBufferEnabled) {
2540 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2541 mEffectBufferSize = mNormalFrameCount * mChannelCount
2542 * audio_bytes_per_sample(mEffectBufferFormat);
2543 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2544 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002545
Eric Laurent81784c32012-11-19 14:55:58 -08002546 // force reconfiguration of effect chains and engines to take new buffer size and audio
2547 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002548 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002549 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2550 // matter.
2551 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2552 Vector< sp<EffectChain> > effectChains = mEffectChains;
2553 for (size_t i = 0; i < effectChains.size(); i ++) {
2554 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2555 }
2556}
2557
2558
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002559status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002560{
2561 if (halFrames == NULL || dspFrames == NULL) {
2562 return BAD_VALUE;
2563 }
2564 Mutex::Autolock _l(mLock);
2565 if (initCheck() != NO_ERROR) {
2566 return INVALID_OPERATION;
2567 }
Andy Hung818e7a32016-02-16 18:08:07 -08002568 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002569 *halFrames = framesWritten;
2570
2571 if (isSuspended()) {
2572 // return an estimation of rendered frames when the output is suspended
2573 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002574 *dspFrames = (uint32_t)
2575 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002576 return NO_ERROR;
2577 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002578 status_t status;
2579 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002580 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002581 *dspFrames = (size_t)frames;
2582 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002583 }
2584}
2585
Eric Laurent4c415062016-06-17 16:14:16 -07002586// hasAudioSession_l() must be called with ThreadBase::mLock held
2587uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002588{
Eric Laurent81784c32012-11-19 14:55:58 -08002589 uint32_t result = 0;
2590 if (getEffectChain_l(sessionId) != 0) {
2591 result = EFFECT_SESSION;
2592 }
2593
2594 for (size_t i = 0; i < mTracks.size(); ++i) {
2595 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002596 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002597 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002598 if (track->isFastTrack()) {
2599 result |= FAST_SESSION;
2600 }
Eric Laurent81784c32012-11-19 14:55:58 -08002601 break;
2602 }
2603 }
2604
2605 return result;
2606}
2607
Glenn Kastend848eb42016-03-08 13:42:11 -08002608uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002609{
2610 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2611 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2612 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2613 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2614 }
2615 for (size_t i = 0; i < mTracks.size(); i++) {
2616 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002617 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002618 return AudioSystem::getStrategyForStream(track->streamType());
2619 }
2620 }
2621 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2622}
2623
2624
Phil Burk062e67a2015-02-11 13:40:50 -08002625AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002626{
2627 Mutex::Autolock _l(mLock);
2628 return mOutput;
2629}
2630
Phil Burk062e67a2015-02-11 13:40:50 -08002631AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002632{
2633 Mutex::Autolock _l(mLock);
2634 AudioStreamOut *output = mOutput;
2635 mOutput = NULL;
2636 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2637 // must push a NULL and wait for ack
2638 mOutputSink.clear();
2639 mPipeSink.clear();
2640 mNormalSink.clear();
2641 return output;
2642}
2643
2644// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002645sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002646{
2647 if (mOutput == NULL) {
2648 return NULL;
2649 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002650 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002651}
2652
2653uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2654{
2655 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2656}
2657
2658status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2659{
2660 if (!isValidSyncEvent(event)) {
2661 return BAD_VALUE;
2662 }
2663
2664 Mutex::Autolock _l(mLock);
2665
2666 for (size_t i = 0; i < mTracks.size(); ++i) {
2667 sp<Track> track = mTracks[i];
2668 if (event->triggerSession() == track->sessionId()) {
2669 (void) track->setSyncEvent(event);
2670 return NO_ERROR;
2671 }
2672 }
2673
2674 return NAME_NOT_FOUND;
2675}
2676
2677bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2678{
2679 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2680}
2681
2682void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2683 const Vector< sp<Track> >& tracksToRemove)
2684{
2685 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002686 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002687 for (size_t i = 0 ; i < count ; i++) {
2688 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002689 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002690 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002691 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002692#ifdef ADD_BATTERY_DATA
2693 // to track the speaker usage
2694 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2695#endif
2696 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002697 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002698 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002699 }
Eric Laurent81784c32012-11-19 14:55:58 -08002700 }
2701 }
2702 }
Eric Laurent81784c32012-11-19 14:55:58 -08002703}
2704
2705void AudioFlinger::PlaybackThread::checkSilentMode_l()
2706{
2707 if (!mMasterMute) {
2708 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002709 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2710 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2711 return;
2712 }
Eric Laurent81784c32012-11-19 14:55:58 -08002713 if (property_get("ro.audio.silent", value, "0") > 0) {
2714 char *endptr;
2715 unsigned long ul = strtoul(value, &endptr, 0);
2716 if (*endptr == '\0' && ul != 0) {
2717 ALOGD("Silence is golden");
2718 // The setprop command will not allow a property to be changed after
2719 // the first time it is set, so we don't have to worry about un-muting.
2720 setMasterMute_l(true);
2721 }
2722 }
2723 }
2724}
2725
2726// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002728{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002729 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002730 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002731 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002732 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002733
2734 // If an NBAIO sink is present, use it to write the normal mixer's submix
2735 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002736
Andy Hung010a1a12014-03-13 13:57:33 -07002737 const size_t count = mBytesRemaining / mFrameSize;
2738
Simon Wilson2d590962012-11-29 15:18:50 -08002739 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002740 // update the setpoint when AudioFlinger::mScreenState changes
2741 uint32_t screenState = AudioFlinger::mScreenState;
2742 if (screenState != mScreenState) {
2743 mScreenState = screenState;
2744 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2745 if (pipe != NULL) {
2746 pipe->setAvgFrames((mScreenState & 1) ?
2747 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2748 }
2749 }
Andy Hung010a1a12014-03-13 13:57:33 -07002750 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002751 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002752 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002753 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002754 } else {
2755 bytesWritten = framesWritten;
2756 }
2757 // otherwise use the HAL / AudioStreamOut directly
2758 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002759 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002760
Eric Laurentbfb1b832013-01-07 09:53:42 -08002761 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002762 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2763 mWriteAckSequence += 2;
2764 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002765 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002766 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002767 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002768 // FIXME We should have an implementation of timestamps for direct output threads.
2769 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002770 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002771
Eric Laurentbfb1b832013-01-07 09:53:42 -08002772 if (mUseAsyncWrite &&
2773 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2774 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002775 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002776 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002777 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002778 }
Eric Laurent81784c32012-11-19 14:55:58 -08002779 }
2780
Eric Laurent81784c32012-11-19 14:55:58 -08002781 mNumWrites++;
2782 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002783 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002784 return bytesWritten;
2785}
2786
2787void AudioFlinger::PlaybackThread::threadLoop_drain()
2788{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002789 bool supportsDrain = false;
2790 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002791 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2792 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002793 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2794 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002795 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002796 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002797 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002798 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002799 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002800 }
2801}
2802
2803void AudioFlinger::PlaybackThread::threadLoop_exit()
2804{
Eric Laurent275e8e92014-11-30 15:14:47 -08002805 {
2806 Mutex::Autolock _l(mLock);
2807 for (size_t i = 0; i < mTracks.size(); i++) {
2808 sp<Track> track = mTracks[i];
2809 track->invalidate();
2810 }
Andy Hungdae27702016-10-31 14:01:16 -07002811 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2812 // After we exit there are no more track changes sent to BatteryNotifier
2813 // because that requires an active threadLoop.
2814 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2815 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002816 }
Eric Laurent81784c32012-11-19 14:55:58 -08002817}
2818
2819/*
2820The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002821 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002822 - mActiveSleepTimeUs from activeSleepTimeUs()
2823 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002824 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2825 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002826 - maxPeriod from frame count and sample rate (MIXER only)
2827
2828The parameters that affect these derived values are:
2829 - frame count
2830 - frame size
2831 - sample rate
2832 - device type: A2DP or not
2833 - device latency
2834 - format: PCM or not
2835 - active sleep time
2836 - idle sleep time
2837*/
2838
2839void AudioFlinger::PlaybackThread::cacheParameters_l()
2840{
Andy Hung25c2dac2014-02-27 14:56:00 -08002841 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002842 mActiveSleepTimeUs = activeSleepTimeUs();
2843 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002844
2845 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2846 // truncating audio when going to standby.
2847 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2848 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2849 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2850 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2851 }
2852 }
Eric Laurent81784c32012-11-19 14:55:58 -08002853}
2854
Eric Laurent13084622016-05-17 10:51:49 -07002855bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002856{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002857 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002858 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002859 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002860 size_t size = mTracks.size();
2861 for (size_t i = 0; i < size; i++) {
2862 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002863 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002864 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002865 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002866 }
2867 }
Eric Laurent13084622016-05-17 10:51:49 -07002868 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002869}
2870
Haynes Mathew George05317d22016-05-03 16:34:26 -07002871void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2872{
2873 Mutex::Autolock _l(mLock);
2874 invalidateTracks_l(streamType);
2875}
2876
Eric Laurent81784c32012-11-19 14:55:58 -08002877status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2878{
Glenn Kastend848eb42016-03-08 13:42:11 -08002879 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002880 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2881 status_t result = EffectBufferHalInterface::mirror(
2882 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2883 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2884 &halInBuffer);
2885 if (result != OK) return result;
2886 halOutBuffer = halInBuffer;
2887 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002888
2889 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002890 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002891 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002892 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002893 if (mType != DIRECT) {
2894 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002895 status_t result = EffectBufferHalInterface::allocate(
2896 numSamples * sizeof(int16_t),
2897 &halInBuffer);
2898 if (result != OK) return result;
2899 buffer = halInBuffer->audioBuffer()->s16;
2900 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2901 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002902 }
2903
2904 // Attach all tracks with same session ID to this chain.
2905 for (size_t i = 0; i < mTracks.size(); ++i) {
2906 sp<Track> track = mTracks[i];
2907 if (session == track->sessionId()) {
2908 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2909 buffer);
2910 track->setMainBuffer(buffer);
2911 chain->incTrackCnt();
2912 }
2913 }
2914
2915 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002916 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002917 if (session == track->sessionId()) {
2918 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2919 chain->incActiveTrackCnt();
2920 }
2921 }
2922 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002923 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002924 chain->setInBuffer(halInBuffer);
2925 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002926 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002927 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002928 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2929 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002930 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002931 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002932 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002933 // Effect chain for other sessions are inserted at beginning of effect
2934 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002935 // sessions is not important.
2936 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2937 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2938 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002939 size_t size = mEffectChains.size();
2940 size_t i = 0;
2941 for (i = 0; i < size; i++) {
2942 if (mEffectChains[i]->sessionId() < session) {
2943 break;
2944 }
2945 }
2946 mEffectChains.insertAt(chain, i);
2947 checkSuspendOnAddEffectChain_l(chain);
2948
2949 return NO_ERROR;
2950}
2951
2952size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2953{
Glenn Kastend848eb42016-03-08 13:42:11 -08002954 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002955
2956 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2957
2958 for (size_t i = 0; i < mEffectChains.size(); i++) {
2959 if (chain == mEffectChains[i]) {
2960 mEffectChains.removeAt(i);
2961 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002962 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002963 if (session == track->sessionId()) {
2964 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2965 chain.get(), session);
2966 chain->decActiveTrackCnt();
2967 }
2968 }
2969
2970 // detach all tracks with same session ID from this chain
2971 for (size_t i = 0; i < mTracks.size(); ++i) {
2972 sp<Track> track = mTracks[i];
2973 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002974 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002975 chain->decTrackCnt();
2976 }
2977 }
2978 break;
2979 }
2980 }
2981 return mEffectChains.size();
2982}
2983
2984status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002985 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002986{
2987 Mutex::Autolock _l(mLock);
2988 return attachAuxEffect_l(track, EffectId);
2989}
2990
2991status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002992 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002993{
2994 status_t status = NO_ERROR;
2995
2996 if (EffectId == 0) {
2997 track->setAuxBuffer(0, NULL);
2998 } else {
2999 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3000 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3001 if (effect != 0) {
3002 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3003 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3004 } else {
3005 status = INVALID_OPERATION;
3006 }
3007 } else {
3008 status = BAD_VALUE;
3009 }
3010 }
3011 return status;
3012}
3013
3014void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3015{
3016 for (size_t i = 0; i < mTracks.size(); ++i) {
3017 sp<Track> track = mTracks[i];
3018 if (track->auxEffectId() == effectId) {
3019 attachAuxEffect_l(track, 0);
3020 }
3021 }
3022}
3023
3024bool AudioFlinger::PlaybackThread::threadLoop()
3025{
Glenn Kasten388d5712017-04-07 14:38:41 -07003026 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003027
Eric Laurent81784c32012-11-19 14:55:58 -08003028 Vector< sp<Track> > tracksToRemove;
3029
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003030 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003031 nsecs_t lastWriteFinished = -1; // time last server write completed
3032 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003033
3034 // MIXER
3035 nsecs_t lastWarning = 0;
3036
3037 // DUPLICATING
3038 // FIXME could this be made local to while loop?
3039 writeFrames = 0;
3040
3041 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003042 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003043
3044 if (mType == MIXER) {
3045 sleepTimeShift = 0;
3046 }
3047
3048 CpuStats cpuStats;
3049 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3050
3051 acquireWakeLock();
3052
Glenn Kasteneef598c2017-04-03 14:41:13 -07003053 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3054 // thread associated with this PlaybackThread.
3055 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3056 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003057 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3058 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003059 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003060 const char *logString = NULL;
3061
rago1bb90822017-05-02 18:31:48 -07003062 // Estimated time for next buffer to be written to hal. This is used only on
3063 // suspended mode (for now) to help schedule the wait time until next iteration.
3064 nsecs_t timeLoopNextNs = 0;
3065
Eric Laurent664539d2013-09-23 18:24:31 -07003066 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003067
Eric Laurent81784c32012-11-19 14:55:58 -08003068 while (!exitPending())
3069 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003070 // Log merge requests are performed during AudioFlinger binder transactions, but
3071 // that does not cover audio playback. It's requested here for that reason.
3072 mAudioFlinger->requestLogMerge();
3073
Eric Laurent81784c32012-11-19 14:55:58 -08003074 cpuStats.sample(myName);
3075
3076 Vector< sp<EffectChain> > effectChains;
3077
Eric Laurent81784c32012-11-19 14:55:58 -08003078 { // scope for mLock
3079
3080 Mutex::Autolock _l(mLock);
3081
Eric Laurent021cf962014-05-13 10:18:14 -07003082 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003083
Glenn Kasteneef598c2017-04-03 14:41:13 -07003084 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003085 if (logString != NULL) {
3086 mNBLogWriter->logTimestamp();
3087 mNBLogWriter->log(logString);
3088 logString = NULL;
3089 }
3090
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003091 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003092 // and associate with the sink frames written out. We need
3093 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003094 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003095 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003096 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003097 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003098 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003099 ExtendedTimestamp timestamp; // use private copy to fetch
3100 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003101
3102 // We keep track of the last valid kernel position in case we are in underrun
3103 // and the normal mixer period is the same as the fast mixer period, or there
3104 // is some error from the HAL.
3105 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3106 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3107 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3108 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3109 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3110
3111 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3112 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3113 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3114 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003115 }
3116
3117 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3118 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003119 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003120 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003121 }
3122
Andy Hung818e7a32016-02-16 18:08:07 -08003123 // copy over kernel info
3124 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003125 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3126 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003127 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3128 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003129 }
3130 // mFramesWritten for non-offloaded tracks are contiguous
3131 // even after standby() is called. This is useful for the track frame
3132 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003133 bool serverLocationUpdate = false;
3134 if (mFramesWritten != lastFramesWritten) {
3135 serverLocationUpdate = true;
3136 lastFramesWritten = mFramesWritten;
3137 }
3138 // Only update timestamps if there is a meaningful change.
3139 // Either the kernel timestamp must be valid or we have written something.
3140 if (kernelLocationUpdate || serverLocationUpdate) {
3141 if (serverLocationUpdate) {
3142 // use the time before we called the HAL write - it is a bit more accurate
3143 // to when the server last read data than the current time here.
3144 //
3145 // If we haven't written anything, mLastWriteTime will be -1
3146 // and we use systemTime().
3147 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3148 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3149 ? systemTime() : mLastWriteTime;
3150 }
Andy Hungdae27702016-10-31 14:01:16 -07003151
3152 for (const sp<Track> &t : mActiveTracks) {
3153 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003154 t->updateTrackFrameInfo(
3155 t->mAudioTrackServerProxy->framesReleased(),
3156 mFramesWritten,
3157 mTimestamp);
3158 }
Andy Hunge10393e2015-06-12 13:59:33 -07003159 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003160 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003161#if 0
3162 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003163 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003164 timespec ts;
3165 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003166 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003167 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003168 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003169 }
3170 ++z;
3171#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003172 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003173 if (mSignalPending) {
3174 // A signal was raised while we were unlocked
3175 mSignalPending = false;
3176 } else if (waitingAsyncCallback_l()) {
3177 if (exitPending()) {
3178 break;
3179 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003180 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003181 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003182 releaseWakeLock_l();
3183 released = true;
3184 }
Andy Hung10cbff12017-02-21 17:30:14 -08003185
3186 const int64_t waitNs = computeWaitTimeNs_l();
3187 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3188 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3189 if (status == TIMED_OUT) {
3190 mSignalPending = true; // if timeout recheck everything
3191 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003192 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003193 if (released) {
3194 acquireWakeLock_l();
3195 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003196 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3197 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003198
3199 continue;
3200 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003201 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003202 isSuspended()) {
3203 // put audio hardware into standby after short delay
3204 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003205
3206 threadLoop_standby();
3207
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003208 // This is where we go into standby
3209 if (!mStandby) {
3210 LOG_AUDIO_STATE();
3211 }
Eric Laurent81784c32012-11-19 14:55:58 -08003212 mStandby = true;
3213 }
3214
3215 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3216 // we're about to wait, flush the binder command buffer
3217 IPCThreadState::self()->flushCommands();
3218
3219 clearOutputTracks();
3220
3221 if (exitPending()) {
3222 break;
3223 }
3224
3225 releaseWakeLock_l();
3226 // wait until we have something to do...
3227 ALOGV("%s going to sleep", myName.string());
3228 mWaitWorkCV.wait(mLock);
3229 ALOGV("%s waking up", myName.string());
3230 acquireWakeLock_l();
3231
3232 mMixerStatus = MIXER_IDLE;
3233 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3234 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003235 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003236 checkSilentMode_l();
3237
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003238 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3239 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003240 if (mType == MIXER) {
3241 sleepTimeShift = 0;
3242 }
3243
3244 continue;
3245 }
3246 }
Eric Laurent81784c32012-11-19 14:55:58 -08003247 // mMixerStatusIgnoringFastTracks is also updated internally
3248 mMixerStatus = prepareTracks_l(&tracksToRemove);
3249
Andy Hungdae27702016-10-31 14:01:16 -07003250 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003251
Eric Laurent81784c32012-11-19 14:55:58 -08003252 // prevent any changes in effect chain list and in each effect chain
3253 // during mixing and effect process as the audio buffers could be deleted
3254 // or modified if an effect is created or deleted
3255 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003256 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003257
Eric Laurentbfb1b832013-01-07 09:53:42 -08003258 if (mBytesRemaining == 0) {
3259 mCurrentWriteLength = 0;
3260 if (mMixerStatus == MIXER_TRACKS_READY) {
3261 // threadLoop_mix() sets mCurrentWriteLength
3262 threadLoop_mix();
3263 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3264 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003265 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003266 // must be written to HAL
3267 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003268 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003269 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003270 }
3271 }
Andy Hung98ef9782014-03-04 14:46:50 -08003272 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003273 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003274 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3275 // or mSinkBuffer (if there are no effects).
3276 //
3277 // This is done pre-effects computation; if effects change to
3278 // support higher precision, this needs to move.
3279 //
3280 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003281 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003282 if (mMixerBufferValid) {
3283 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3284 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3285
Andy Hung2ddee192015-12-18 17:34:44 -08003286 // mono blend occurs for mixer threads only (not direct or offloaded)
3287 // and is handled here if we're going directly to the sink.
3288 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003289 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3290 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003291 }
3292
Andy Hung98ef9782014-03-04 14:46:50 -08003293 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3294 mNormalFrameCount * mChannelCount);
3295 }
3296
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297 mBytesRemaining = mCurrentWriteLength;
3298 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003299 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3300 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3301 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3302 mBytesWritten += mBytesRemaining;
3303 mFramesWritten += framesRemaining;
3304 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003305 mBytesRemaining = 0;
3306 }
Eric Laurent81784c32012-11-19 14:55:58 -08003307
Eric Laurentbfb1b832013-01-07 09:53:42 -08003308 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003309 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003310 for (size_t i = 0; i < effectChains.size(); i ++) {
3311 effectChains[i]->process_l();
3312 }
Eric Laurent81784c32012-11-19 14:55:58 -08003313 }
3314 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003315 // Process effect chains for offloaded thread even if no audio
3316 // was read from audio track: process only updates effect state
3317 // and thus does have to be synchronized with audio writes but may have
3318 // to be called while waiting for async write callback
3319 if (mType == OFFLOAD) {
3320 for (size_t i = 0; i < effectChains.size(); i ++) {
3321 effectChains[i]->process_l();
3322 }
3323 }
Eric Laurent81784c32012-11-19 14:55:58 -08003324
Andy Hung98ef9782014-03-04 14:46:50 -08003325 // Only if the Effects buffer is enabled and there is data in the
3326 // Effects buffer (buffer valid), we need to
3327 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003328 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003329 if (mEffectBufferValid) {
3330 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003331
3332 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003333 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3334 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003335 }
3336
Andy Hung98ef9782014-03-04 14:46:50 -08003337 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3338 mNormalFrameCount * mChannelCount);
3339 }
3340
Eric Laurent81784c32012-11-19 14:55:58 -08003341 // enable changes in effect chain
3342 unlockEffectChains(effectChains);
3343
Eric Laurentbfb1b832013-01-07 09:53:42 -08003344 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003345 // mSleepTimeUs == 0 means we must write to audio hardware
3346 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003347 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003348 // We save lastWriteFinished here, as previousLastWriteFinished,
3349 // for throttling. On thread start, previousLastWriteFinished will be
3350 // set to -1, which properly results in no throttling after the first write.
3351 nsecs_t previousLastWriteFinished = lastWriteFinished;
3352 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003353 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003354 // FIXME rewrite to reduce number of system calls
3355 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003356 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003357 lastWriteFinished = systemTime();
3358 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003359 if (ret < 0) {
3360 mBytesRemaining = 0;
3361 } else {
3362 mBytesWritten += ret;
3363 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003364 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003365 }
3366 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3367 (mMixerStatus == MIXER_DRAIN_ALL)) {
3368 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003369 }
Andy Hung08fb1742015-05-31 23:22:10 -07003370 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003371 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003372 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003373 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003374 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003375 ATRACE_NAME("underrun");
3376 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003377 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003378 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003379 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003380 }
Andy Hung08fb1742015-05-31 23:22:10 -07003381
3382 if (mThreadThrottle
3383 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3384 && ret > 0) { // we wrote something
3385 // Limit MixerThread data processing to no more than twice the
3386 // expected processing rate.
3387 //
3388 // This helps prevent underruns with NuPlayer and other applications
3389 // which may set up buffers that are close to the minimum size, or use
3390 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3391 //
3392 // The throttle smooths out sudden large data drains from the device,
3393 // e.g. when it comes out of standby, which often causes problems with
3394 // (1) mixer threads without a fast mixer (which has its own warm-up)
3395 // (2) minimum buffer sized tracks (even if the track is full,
3396 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003397 //
3398 // Total time spent in last processing cycle equals time spent in
3399 // 1. threadLoop_write, as well as time spent in
3400 // 2. threadLoop_mix (significant for heavy mixing, especially
3401 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003402
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003403 // it's OK if deltaMs (and deltaNs) is an overestimate.
3404 nsecs_t deltaNs;
3405 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3406 __builtin_sub_overflow(
3407 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3408 const int32_t deltaMs = deltaNs / 1000000;
3409
Ivan Lozanoea04d392017-11-07 14:37:07 -08003410 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003411 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3412 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003413 // notify of throttle start on verbose log
3414 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3415 "mixer(%p) throttle begin:"
3416 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003417 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003418 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003419 // Throttle must be attributed to the previous mixer loop's write time
3420 // to allow back-to-back throttling.
3421 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003422 } else {
3423 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3424 if (diff > 0) {
3425 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003426 // but prevent spamming for bluetooth
3427 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3428 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003429 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3430 }
Andy Hung08fb1742015-05-31 23:22:10 -07003431 }
3432 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003433 }
Eric Laurent81784c32012-11-19 14:55:58 -08003434
Eric Laurentbfb1b832013-01-07 09:53:42 -08003435 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003436 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003437 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003438 // suspended requires accurate metering of sleep time.
3439 if (isSuspended()) {
3440 // advance by expected sleepTime
3441 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3442 const nsecs_t nowNs = systemTime();
3443
3444 // compute expected next time vs current time.
3445 // (negative deltas are treated as delays).
3446 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3447 if (deltaNs < -kMaxNextBufferDelayNs) {
3448 // Delays longer than the max allowed trigger a reset.
3449 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3450 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3451 timeLoopNextNs = nowNs + deltaNs;
3452 } else if (deltaNs < 0) {
3453 // Delays within the max delay allowed: zero the delta/sleepTime
3454 // to help the system catch up in the next iteration(s)
3455 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3456 deltaNs = 0;
3457 }
3458 // update sleep time (which is >= 0)
3459 mSleepTimeUs = deltaNs / 1000;
3460 }
Eric Laurente93cc032016-05-05 10:15:10 -07003461 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3462 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003463 }
Glenn Kastene7754022014-10-31 12:11:26 -07003464 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003465 }
Eric Laurent81784c32012-11-19 14:55:58 -08003466 }
3467
3468 // Finally let go of removed track(s), without the lock held
3469 // since we can't guarantee the destructors won't acquire that
3470 // same lock. This will also mutate and push a new fast mixer state.
3471 threadLoop_removeTracks(tracksToRemove);
3472 tracksToRemove.clear();
3473
3474 // FIXME I don't understand the need for this here;
3475 // it was in the original code but maybe the
3476 // assignment in saveOutputTracks() makes this unnecessary?
3477 clearOutputTracks();
3478
3479 // Effect chains will be actually deleted here if they were removed from
3480 // mEffectChains list during mixing or effects processing
3481 effectChains.clear();
3482
3483 // FIXME Note that the above .clear() is no longer necessary since effectChains
3484 // is now local to this block, but will keep it for now (at least until merge done).
3485 }
3486
Eric Laurentbfb1b832013-01-07 09:53:42 -08003487 threadLoop_exit();
3488
Eric Laurentcf817a22014-08-04 20:36:31 -07003489 if (!mStandby) {
3490 threadLoop_standby();
3491 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003492 }
3493
3494 releaseWakeLock();
3495
3496 ALOGV("Thread %p type %d exiting", this, mType);
3497 return false;
3498}
3499
Eric Laurentbfb1b832013-01-07 09:53:42 -08003500// removeTracks_l() must be called with ThreadBase::mLock held
3501void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3502{
3503 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003504 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003505 for (size_t i=0 ; i<count ; i++) {
3506 const sp<Track>& track = tracksToRemove.itemAt(i);
3507 mActiveTracks.remove(track);
3508 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3509 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3510 if (chain != 0) {
3511 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3512 track->sessionId());
3513 chain->decActiveTrackCnt();
3514 }
3515 if (track->isTerminated()) {
3516 removeTrack_l(track);
3517 }
3518 }
3519 }
3520
3521}
Eric Laurent81784c32012-11-19 14:55:58 -08003522
Eric Laurentaccc1472013-09-20 09:36:34 -07003523status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3524{
3525 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003526 ExtendedTimestamp ets;
3527 status_t status = mNormalSink->getTimestamp(ets);
3528 if (status == NO_ERROR) {
3529 status = ets.getBestTimestamp(&timestamp);
3530 }
3531 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003532 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003533 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003534 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003535 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003536 timestamp.mPosition = (uint32_t)position64;
3537 return NO_ERROR;
3538 }
3539 }
3540 return INVALID_OPERATION;
3541}
Eric Laurent1c333e22014-05-20 10:48:17 -07003542
Eric Laurent054d9d32015-04-24 08:48:48 -07003543status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3544 audio_patch_handle_t *handle)
3545{
Andy Hungf60abce2016-08-26 11:37:54 -07003546 status_t status;
3547 if (property_get_bool("af.patch_park", false /* default_value */)) {
3548 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3549 // or if HAL does not properly lock against access.
3550 AutoPark<FastMixer> park(mFastMixer);
3551 status = PlaybackThread::createAudioPatch_l(patch, handle);
3552 } else {
3553 status = PlaybackThread::createAudioPatch_l(patch, handle);
3554 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003555 return status;
3556}
3557
Eric Laurent1c333e22014-05-20 10:48:17 -07003558status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3559 audio_patch_handle_t *handle)
3560{
3561 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003562
3563 // store new device and send to effects
3564 audio_devices_t type = AUDIO_DEVICE_NONE;
3565 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3566 type |= patch->sinks[i].ext.device.type;
3567 }
3568
3569#ifdef ADD_BATTERY_DATA
3570 // when changing the audio output device, call addBatteryData to notify
3571 // the change
3572 if (mOutDevice != type) {
3573 uint32_t params = 0;
3574 // check whether speaker is on
3575 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3576 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003577 }
3578
Eric Laurent054d9d32015-04-24 08:48:48 -07003579 audio_devices_t deviceWithoutSpeaker
3580 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3581 // check if any other device (except speaker) is on
3582 if (type & deviceWithoutSpeaker) {
3583 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3584 }
3585
3586 if (params != 0) {
3587 addBatteryData(params);
3588 }
3589 }
3590#endif
3591
3592 for (size_t i = 0; i < mEffectChains.size(); i++) {
3593 mEffectChains[i]->setDevice_l(type);
3594 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003595
3596 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3597 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3598 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003599 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003600 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003601
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003602 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003603 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3604 status = hwDevice->createAudioPatch(patch->num_sources,
3605 patch->sources,
3606 patch->num_sinks,
3607 patch->sinks,
3608 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003609 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003610 char *address;
3611 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3612 //FIXME: we only support address on first sink with HAL version < 3.0
3613 address = audio_device_address_to_parameter(
3614 patch->sinks[0].ext.device.type,
3615 patch->sinks[0].ext.device.address);
3616 } else {
3617 address = (char *)calloc(1, 1);
3618 }
3619 AudioParameter param = AudioParameter(String8(address));
3620 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003621 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003622 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003623 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003624 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003625 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003626 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003627 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3628 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003629 return status;
3630}
3631
Eric Laurent054d9d32015-04-24 08:48:48 -07003632status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3633{
Andy Hungf60abce2016-08-26 11:37:54 -07003634 status_t status;
3635 if (property_get_bool("af.patch_park", false /* default_value */)) {
3636 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3637 // or if HAL does not properly lock against access.
3638 AutoPark<FastMixer> park(mFastMixer);
3639 status = PlaybackThread::releaseAudioPatch_l(handle);
3640 } else {
3641 status = PlaybackThread::releaseAudioPatch_l(handle);
3642 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003643 return status;
3644}
3645
Eric Laurent1c333e22014-05-20 10:48:17 -07003646status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3647{
3648 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003649
3650 mOutDevice = AUDIO_DEVICE_NONE;
3651
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003652 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003653 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3654 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003655 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003656 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003657 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003658 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003659 }
3660 return status;
3661}
3662
Eric Laurent83b88082014-06-20 18:31:16 -07003663void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3664{
3665 Mutex::Autolock _l(mLock);
3666 mTracks.add(track);
3667}
3668
3669void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3670{
3671 Mutex::Autolock _l(mLock);
3672 destroyTrack_l(track);
3673}
3674
3675void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3676{
3677 ThreadBase::getAudioPortConfig(config);
3678 config->role = AUDIO_PORT_ROLE_SOURCE;
3679 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3680 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3681}
3682
Eric Laurent81784c32012-11-19 14:55:58 -08003683// ----------------------------------------------------------------------------
3684
3685AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003686 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3687 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003688 // mAudioMixer below
3689 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003690 mFastMixerFutex(0),
3691 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003692 // mOutputSink below
3693 // mPipeSink below
3694 // mNormalSink below
3695{
3696 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003697 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3698 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003699 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3700 mNormalFrameCount);
3701 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3702
Andy Hungfbfc3952015-01-15 13:33:51 -08003703 if (type == DUPLICATING) {
3704 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3705 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3706 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3707 return;
3708 }
Eric Laurent81784c32012-11-19 14:55:58 -08003709 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003710 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003711 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003712 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003713#if !LOG_NDEBUG
3714 ssize_t index =
3715#else
3716 (void)
3717#endif
3718 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003719 ALOG_ASSERT(index == 0);
3720
3721 // initialize fast mixer depending on configuration
3722 bool initFastMixer;
3723 switch (kUseFastMixer) {
3724 case FastMixer_Never:
3725 initFastMixer = false;
3726 break;
3727 case FastMixer_Always:
3728 initFastMixer = true;
3729 break;
3730 case FastMixer_Static:
3731 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003732 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3733 // where the period is less than an experimentally determined threshold that can be
3734 // scheduled reliably with CFS. However, the BT A2DP HAL is
3735 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3736 initFastMixer = mFrameCount < mNormalFrameCount
3737 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003738 break;
3739 }
Andy Hungfda69402017-02-15 14:33:12 -08003740 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3741 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3742 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003743 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003744 audio_format_t fastMixerFormat;
3745 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3746 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3747 } else {
3748 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3749 }
3750 if (mFormat != fastMixerFormat) {
3751 // change our Sink format to accept our intermediate precision
3752 mFormat = fastMixerFormat;
3753 free(mSinkBuffer);
3754 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3755 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3756 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3757 }
Eric Laurent81784c32012-11-19 14:55:58 -08003758
3759 // create a MonoPipe to connect our submix to FastMixer
3760 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003761#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003762 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003763#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003764 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003765 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003766 format.mFormat = fastMixerFormat;
3767 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3768
Eric Laurent81784c32012-11-19 14:55:58 -08003769 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3770 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3771 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3772 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3773 const NBAIO_Format offers[1] = {format};
3774 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003775#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003776 ssize_t index =
3777#else
3778 (void)
3779#endif
3780 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003781 ALOG_ASSERT(index == 0);
3782 monoPipe->setAvgFrames((mScreenState & 1) ?
3783 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3784 mPipeSink = monoPipe;
3785
Glenn Kasten46909e72013-02-26 09:20:22 -08003786#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003787 if (mTeeSinkOutputEnabled) {
3788 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003789 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3790 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003791 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003792 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003793 ALOG_ASSERT(index == 0);
3794 mTeeSink = teeSink;
3795 PipeReader *teeSource = new PipeReader(*teeSink);
3796 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003797 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003798 ALOG_ASSERT(index == 0);
3799 mTeeSource = teeSource;
3800 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003801#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003802
3803 // create fast mixer and configure it initially with just one fast track for our submix
3804 mFastMixer = new FastMixer();
3805 FastMixerStateQueue *sq = mFastMixer->sq();
3806#ifdef STATE_QUEUE_DUMP
3807 sq->setObserverDump(&mStateQueueObserverDump);
3808 sq->setMutatorDump(&mStateQueueMutatorDump);
3809#endif
3810 FastMixerState *state = sq->begin();
3811 FastTrack *fastTrack = &state->mFastTracks[0];
3812 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3813 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3814 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003815 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3816 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003817 fastTrack->mGeneration++;
3818 state->mFastTracksGen++;
3819 state->mTrackMask = 1;
3820 // fast mixer will use the HAL output sink
3821 state->mOutputSink = mOutputSink.get();
3822 state->mOutputSinkGen++;
3823 state->mFrameCount = mFrameCount;
3824 state->mCommand = FastMixerState::COLD_IDLE;
3825 // already done in constructor initialization list
3826 //mFastMixerFutex = 0;
3827 state->mColdFutexAddr = &mFastMixerFutex;
3828 state->mColdGen++;
3829 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003830#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003831 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003832#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003833 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3834 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003835 sq->end();
3836 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3837
3838 // start the fast mixer
3839 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3840 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003841 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003842 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003843
3844#ifdef AUDIO_WATCHDOG
3845 // create and start the watchdog
3846 mAudioWatchdog = new AudioWatchdog();
3847 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3848 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3849 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003850 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003851#endif
3852
Eric Laurent81784c32012-11-19 14:55:58 -08003853 }
3854
3855 switch (kUseFastMixer) {
3856 case FastMixer_Never:
3857 case FastMixer_Dynamic:
3858 mNormalSink = mOutputSink;
3859 break;
3860 case FastMixer_Always:
3861 mNormalSink = mPipeSink;
3862 break;
3863 case FastMixer_Static:
3864 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3865 break;
3866 }
3867}
3868
3869AudioFlinger::MixerThread::~MixerThread()
3870{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003871 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003872 FastMixerStateQueue *sq = mFastMixer->sq();
3873 FastMixerState *state = sq->begin();
3874 if (state->mCommand == FastMixerState::COLD_IDLE) {
3875 int32_t old = android_atomic_inc(&mFastMixerFutex);
3876 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003877 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003878 }
3879 }
3880 state->mCommand = FastMixerState::EXIT;
3881 sq->end();
3882 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3883 mFastMixer->join();
3884 // Though the fast mixer thread has exited, it's state queue is still valid.
3885 // We'll use that extract the final state which contains one remaining fast track
3886 // corresponding to our sub-mix.
3887 state = sq->begin();
3888 ALOG_ASSERT(state->mTrackMask == 1);
3889 FastTrack *fastTrack = &state->mFastTracks[0];
3890 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3891 delete fastTrack->mBufferProvider;
3892 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003893 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003894#ifdef AUDIO_WATCHDOG
3895 if (mAudioWatchdog != 0) {
3896 mAudioWatchdog->requestExit();
3897 mAudioWatchdog->requestExitAndWait();
3898 mAudioWatchdog.clear();
3899 }
3900#endif
3901 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003902 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003903 delete mAudioMixer;
3904}
3905
3906
3907uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3908{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003909 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003910 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3911 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3912 }
3913 return latency;
3914}
3915
3916
3917void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3918{
3919 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3920}
3921
Eric Laurentbfb1b832013-01-07 09:53:42 -08003922ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003923{
3924 // FIXME we should only do one push per cycle; confirm this is true
3925 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003926 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003927 FastMixerStateQueue *sq = mFastMixer->sq();
3928 FastMixerState *state = sq->begin();
3929 if (state->mCommand != FastMixerState::MIX_WRITE &&
3930 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3931 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003932
3933 // FIXME workaround for first HAL write being CPU bound on some devices
3934 ATRACE_BEGIN("write");
3935 mOutput->write((char *)mSinkBuffer, 0);
3936 ATRACE_END();
3937
Eric Laurent81784c32012-11-19 14:55:58 -08003938 int32_t old = android_atomic_inc(&mFastMixerFutex);
3939 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003940 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003941 }
3942#ifdef AUDIO_WATCHDOG
3943 if (mAudioWatchdog != 0) {
3944 mAudioWatchdog->resume();
3945 }
3946#endif
3947 }
3948 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003949#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003950 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003951 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003952#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003953 sq->end();
3954 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3955 if (kUseFastMixer == FastMixer_Dynamic) {
3956 mNormalSink = mPipeSink;
3957 }
3958 } else {
3959 sq->end(false /*didModify*/);
3960 }
3961 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003962 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003963}
3964
3965void AudioFlinger::MixerThread::threadLoop_standby()
3966{
3967 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003968 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003969 FastMixerStateQueue *sq = mFastMixer->sq();
3970 FastMixerState *state = sq->begin();
3971 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003972 // Report any frames trapped in the Monopipe
3973 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3974 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3975 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3976 "monoPipeWritten:%lld monoPipeLeft:%lld",
3977 (long long)mFramesWritten, (long long)mSuspendedFrames,
3978 (long long)mPipeSink->framesWritten(), pipeFrames);
3979 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3980
Eric Laurent81784c32012-11-19 14:55:58 -08003981 state->mCommand = FastMixerState::COLD_IDLE;
3982 state->mColdFutexAddr = &mFastMixerFutex;
3983 state->mColdGen++;
3984 mFastMixerFutex = 0;
3985 sq->end();
3986 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3987 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3988 if (kUseFastMixer == FastMixer_Dynamic) {
3989 mNormalSink = mOutputSink;
3990 }
3991#ifdef AUDIO_WATCHDOG
3992 if (mAudioWatchdog != 0) {
3993 mAudioWatchdog->pause();
3994 }
3995#endif
3996 } else {
3997 sq->end(false /*didModify*/);
3998 }
3999 }
4000 PlaybackThread::threadLoop_standby();
4001}
4002
Eric Laurentbfb1b832013-01-07 09:53:42 -08004003bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4004{
4005 return false;
4006}
4007
4008bool AudioFlinger::PlaybackThread::shouldStandby_l()
4009{
4010 return !mStandby;
4011}
4012
4013bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4014{
4015 Mutex::Autolock _l(mLock);
4016 return waitingAsyncCallback_l();
4017}
4018
Eric Laurent81784c32012-11-19 14:55:58 -08004019// shared by MIXER and DIRECT, overridden by DUPLICATING
4020void AudioFlinger::PlaybackThread::threadLoop_standby()
4021{
4022 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004023 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004024 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004025 // discard any pending drain or write ack by incrementing sequence
4026 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4027 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004028 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004029 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4030 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004032 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004033}
4034
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004035void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4036{
4037 ALOGV("signal playback thread");
4038 broadcast_l();
4039}
4040
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004041void AudioFlinger::PlaybackThread::onAsyncError()
4042{
4043 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4044 invalidateTracks((audio_stream_type_t)i);
4045 }
4046}
4047
Eric Laurent81784c32012-11-19 14:55:58 -08004048void AudioFlinger::MixerThread::threadLoop_mix()
4049{
Eric Laurent81784c32012-11-19 14:55:58 -08004050 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004051 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004052 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004053 // increase sleep time progressively when application underrun condition clears.
4054 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4055 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4056 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004057 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004058 sleepTimeShift--;
4059 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004060 mSleepTimeUs = 0;
4061 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004062 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004063
Eric Laurent81784c32012-11-19 14:55:58 -08004064}
4065
4066void AudioFlinger::MixerThread::threadLoop_sleepTime()
4067{
4068 // If no tracks are ready, sleep once for the duration of an output
4069 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004070 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004071 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004072 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4073 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4074 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004075 }
4076 // reduce sleep time in case of consecutive application underruns to avoid
4077 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4078 // duration we would end up writing less data than needed by the audio HAL if
4079 // the condition persists.
4080 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4081 sleepTimeShift++;
4082 }
4083 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004084 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004085 }
4086 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004087 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4088 // before effects processing or output.
4089 if (mMixerBufferValid) {
4090 memset(mMixerBuffer, 0, mMixerBufferSize);
4091 } else {
4092 memset(mSinkBuffer, 0, mSinkBufferSize);
4093 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004094 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004095 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4096 "anticipated start");
4097 }
4098 // TODO add standby time extension fct of effect tail
4099}
4100
4101// prepareTracks_l() must be called with ThreadBase::mLock held
4102AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4103 Vector< sp<Track> > *tracksToRemove)
4104{
4105
4106 mixer_state mixerStatus = MIXER_IDLE;
4107 // find out which tracks need to be processed
4108 size_t count = mActiveTracks.size();
4109 size_t mixedTracks = 0;
4110 size_t tracksWithEffect = 0;
4111 // counts only _active_ fast tracks
4112 size_t fastTracks = 0;
4113 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4114
4115 float masterVolume = mMasterVolume;
4116 bool masterMute = mMasterMute;
4117
4118 if (masterMute) {
4119 masterVolume = 0;
4120 }
4121 // Delegate master volume control to effect in output mix effect chain if needed
4122 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4123 if (chain != 0) {
4124 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4125 chain->setVolume_l(&v, &v);
4126 masterVolume = (float)((v + (1 << 23)) >> 24);
4127 chain.clear();
4128 }
4129
4130 // prepare a new state to push
4131 FastMixerStateQueue *sq = NULL;
4132 FastMixerState *state = NULL;
4133 bool didModify = false;
4134 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004135 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004136 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004137 sq = mFastMixer->sq();
4138 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004139 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004140 }
4141
Andy Hung69aed5f2014-02-25 17:24:40 -08004142 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004143 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004144
Eric Laurent81784c32012-11-19 14:55:58 -08004145 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004146 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004147
4148 // this const just means the local variable doesn't change
4149 Track* const track = t.get();
4150
4151 // process fast tracks
4152 if (track->isFastTrack()) {
4153
4154 // It's theoretically possible (though unlikely) for a fast track to be created
4155 // and then removed within the same normal mix cycle. This is not a problem, as
4156 // the track never becomes active so it's fast mixer slot is never touched.
4157 // The converse, of removing an (active) track and then creating a new track
4158 // at the identical fast mixer slot within the same normal mix cycle,
4159 // is impossible because the slot isn't marked available until the end of each cycle.
4160 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004161 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004162 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4163 FastTrack *fastTrack = &state->mFastTracks[j];
4164
4165 // Determine whether the track is currently in underrun condition,
4166 // and whether it had a recent underrun.
4167 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4168 FastTrackUnderruns underruns = ftDump->mUnderruns;
4169 uint32_t recentFull = (underruns.mBitFields.mFull -
4170 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4171 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4172 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4173 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4174 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4175 uint32_t recentUnderruns = recentPartial + recentEmpty;
4176 track->mObservedUnderruns = underruns;
4177 // don't count underruns that occur while stopping or pausing
4178 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004179 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4180 recentUnderruns > 0) {
4181 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4182 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004183 } else {
4184 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004185 }
4186
4187 // This is similar to the state machine for normal tracks,
4188 // with a few modifications for fast tracks.
4189 bool isActive = true;
4190 switch (track->mState) {
4191 case TrackBase::STOPPING_1:
4192 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004193 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004194 track->mState = TrackBase::STOPPING_2;
4195 }
4196 break;
4197 case TrackBase::PAUSING:
4198 // ramp down is not yet implemented
4199 track->setPaused();
4200 break;
4201 case TrackBase::RESUMING:
4202 // ramp up is not yet implemented
4203 track->mState = TrackBase::ACTIVE;
4204 break;
4205 case TrackBase::ACTIVE:
4206 if (recentFull > 0 || recentPartial > 0) {
4207 // track has provided at least some frames recently: reset retry count
4208 track->mRetryCount = kMaxTrackRetries;
4209 }
4210 if (recentUnderruns == 0) {
4211 // no recent underruns: stay active
4212 break;
4213 }
4214 // there has recently been an underrun of some kind
4215 if (track->sharedBuffer() == 0) {
4216 // were any of the recent underruns "empty" (no frames available)?
4217 if (recentEmpty == 0) {
4218 // no, then ignore the partial underruns as they are allowed indefinitely
4219 break;
4220 }
4221 // there has recently been an "empty" underrun: decrement the retry counter
4222 if (--(track->mRetryCount) > 0) {
4223 break;
4224 }
4225 // indicate to client process that the track was disabled because of underrun;
4226 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004227 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004228 // remove from active list, but state remains ACTIVE [confusing but true]
4229 isActive = false;
4230 break;
4231 }
4232 // fall through
4233 case TrackBase::STOPPING_2:
4234 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004235 case TrackBase::STOPPED:
4236 case TrackBase::FLUSHED: // flush() while active
4237 // Check for presentation complete if track is inactive
4238 // We have consumed all the buffers of this track.
4239 // This would be incomplete if we auto-paused on underrun
4240 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004241 uint32_t latency = 0;
4242 status_t result = mOutput->stream->getLatency(&latency);
4243 ALOGE_IF(result != OK,
4244 "Error when retrieving output stream latency: %d", result);
4245 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004246 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004247 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4248 // track stays in active list until presentation is complete
4249 break;
4250 }
4251 }
4252 if (track->isStopping_2()) {
4253 track->mState = TrackBase::STOPPED;
4254 }
4255 if (track->isStopped()) {
4256 // Can't reset directly, as fast mixer is still polling this track
4257 // track->reset();
4258 // So instead mark this track as needing to be reset after push with ack
4259 resetMask |= 1 << i;
4260 }
4261 isActive = false;
4262 break;
4263 case TrackBase::IDLE:
4264 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004265 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004266 }
4267
4268 if (isActive) {
4269 // was it previously inactive?
4270 if (!(state->mTrackMask & (1 << j))) {
4271 ExtendedAudioBufferProvider *eabp = track;
4272 VolumeProvider *vp = track;
4273 fastTrack->mBufferProvider = eabp;
4274 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004275 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004276 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004277 fastTrack->mGeneration++;
4278 state->mTrackMask |= 1 << j;
4279 didModify = true;
4280 // no acknowledgement required for newly active tracks
4281 }
4282 // cache the combined master volume and stream type volume for fast mixer; this
4283 // lacks any synchronization or barrier so VolumeProvider may read a stale value
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 track->mCachedVolume = masterVolume
4287 * mStreamTypes[track->streamType()].volume
4288 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004289 ++fastTracks;
4290 } else {
4291 // was it previously active?
4292 if (state->mTrackMask & (1 << j)) {
4293 fastTrack->mBufferProvider = NULL;
4294 fastTrack->mGeneration++;
4295 state->mTrackMask &= ~(1 << j);
4296 didModify = true;
4297 // If any fast tracks were removed, we must wait for acknowledgement
4298 // because we're about to decrement the last sp<> on those tracks.
4299 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4300 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004301 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4302 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4303 j, track->mState, state->mTrackMask, recentUnderruns,
4304 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004305 }
4306 tracksToRemove->add(track);
4307 // Avoids a misleading display in dumpsys
4308 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4309 }
4310 continue;
4311 }
4312
4313 { // local variable scope to avoid goto warning
4314
4315 audio_track_cblk_t* cblk = track->cblk();
4316
4317 // The first time a track is added we wait
4318 // for all its buffers to be filled before processing it
4319 int name = track->name();
4320 // make sure that we have enough frames to mix one full buffer.
4321 // enforce this condition only once to enable draining the buffer in case the client
4322 // app does not call stop() and relies on underrun to stop:
4323 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4324 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004325 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004326 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004327 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004328
4329 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004330 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004331 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4332 // add frames already consumed but not yet released by the resampler
4333 // because mAudioTrackServerProxy->framesReady() will include these frames
4334 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4335
Eric Laurent81784c32012-11-19 14:55:58 -08004336 uint32_t minFrames = 1;
4337 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4338 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004339 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004340 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004341
4342 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004343 if (ATRACE_ENABLED()) {
4344 // I wish we had formatted trace names
4345 char traceName[16];
4346 strcpy(traceName, "nRdy");
4347 int name = track->name();
4348 if (AudioMixer::TRACK0 <= name &&
4349 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4350 name -= AudioMixer::TRACK0;
4351 traceName[4] = (name / 10) + '0';
4352 traceName[5] = (name % 10) + '0';
4353 } else {
4354 traceName[4] = '?';
4355 traceName[5] = '?';
4356 }
4357 traceName[6] = '\0';
4358 ATRACE_INT(traceName, framesReady);
4359 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004360 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004361 !track->isPaused() && !track->isTerminated())
4362 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004363 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004364
4365 mixedTracks++;
4366
Andy Hung69aed5f2014-02-25 17:24:40 -08004367 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4368 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004369 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004370 if (track->mainBuffer() != mSinkBuffer &&
4371 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004372 if (mEffectBufferEnabled) {
4373 mEffectBufferValid = true; // Later can set directly.
4374 }
Eric Laurent81784c32012-11-19 14:55:58 -08004375 chain = getEffectChain_l(track->sessionId());
4376 // Delegate volume control to effect in track effect chain if needed
4377 if (chain != 0) {
4378 tracksWithEffect++;
4379 } else {
4380 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4381 "session %d",
4382 name, track->sessionId());
4383 }
4384 }
4385
4386
4387 int param = AudioMixer::VOLUME;
4388 if (track->mFillingUpStatus == Track::FS_FILLED) {
4389 // no ramp for the first volume setting
4390 track->mFillingUpStatus = Track::FS_ACTIVE;
4391 if (track->mState == TrackBase::RESUMING) {
4392 track->mState = TrackBase::ACTIVE;
4393 param = AudioMixer::RAMP_VOLUME;
4394 }
4395 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004396 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004397 // FIXME should not make a decision based on mServer
4398 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004399 // If the track is stopped before the first frame was mixed,
4400 // do not apply ramp
4401 param = AudioMixer::RAMP_VOLUME;
4402 }
4403
4404 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004405 uint32_t vl, vr; // in U8.24 integer format
4406 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004407 // read original volumes with volume control
4408 float typeVolume = mStreamTypes[track->streamType()].volume;
4409 float v = masterVolume * typeVolume;
4410
Glenn Kastene4756fe2012-11-29 13:38:14 -08004411 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004412 vl = vr = 0;
4413 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004414 if (track->isPausing()) {
4415 track->setPaused();
4416 }
4417 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004418 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004419 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004420 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4421 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004422 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004423 if (vlf > GAIN_FLOAT_UNITY) {
4424 ALOGV("Track left volume out of range: %.3g", vlf);
4425 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004426 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004427 if (vrf > GAIN_FLOAT_UNITY) {
4428 ALOGV("Track right volume out of range: %.3g", vrf);
4429 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004430 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004431 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004432 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004433 // now apply the master volume and stream type volume and shaper volume
4434 vlf *= v * vh;
4435 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004436 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004437 // then derive vl and vr as U8.24 versions for the effect chain
4438 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4439 vl = (uint32_t) (scaleto8_24 * vlf);
4440 vr = (uint32_t) (scaleto8_24 * vrf);
4441 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004442 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004443 // send level comes from shared memory and so may be corrupt
4444 if (sendLevel > MAX_GAIN_INT) {
4445 ALOGV("Track send level out of range: %04X", sendLevel);
4446 sendLevel = MAX_GAIN_INT;
4447 }
Andy Hung6be49402014-05-30 10:42:03 -07004448 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4449 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004450 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004451
Eric Laurent81784c32012-11-19 14:55:58 -08004452 // Delegate volume control to effect in track effect chain if needed
4453 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4454 // Do not ramp volume if volume is controlled by effect
4455 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004456 // Update remaining floating point volume levels
4457 vlf = (float)vl / (1 << 24);
4458 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004459 track->mHasVolumeController = true;
4460 } else {
4461 // force no volume ramp when volume controller was just disabled or removed
4462 // from effect chain to avoid volume spike
4463 if (track->mHasVolumeController) {
4464 param = AudioMixer::VOLUME;
4465 }
4466 track->mHasVolumeController = false;
4467 }
4468
Eric Laurent7c29ec92017-09-20 17:54:22 -07004469 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4470 // still applied by the mixer.
4471 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4472 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4473 if (v != mLeftVolFloat) {
4474 status_t result = mOutput->stream->setVolume(v, v);
4475 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4476 if (result == OK) {
4477 mLeftVolFloat = v;
4478 }
4479 }
4480 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4481 // remove stream volume contribution from software volume.
4482 if (v != 0.0f && mLeftVolFloat == v) {
4483 vlf = min(1.0f, vlf / v);
4484 vrf = min(1.0f, vrf / v);
4485 vaf = min(1.0f, vaf / v);
4486 }
4487 }
Eric Laurent81784c32012-11-19 14:55:58 -08004488 // XXX: these things DON'T need to be done each time
4489 mAudioMixer->setBufferProvider(name, track);
4490 mAudioMixer->enable(name);
4491
Andy Hung6be49402014-05-30 10:42:03 -07004492 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4493 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4494 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004495 mAudioMixer->setParameter(
4496 name,
4497 AudioMixer::TRACK,
4498 AudioMixer::FORMAT, (void *)track->format());
4499 mAudioMixer->setParameter(
4500 name,
4501 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004502 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004503 mAudioMixer->setParameter(
4504 name,
4505 AudioMixer::TRACK,
4506 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004507 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004508 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004509 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004510 if (reqSampleRate == 0) {
4511 reqSampleRate = mSampleRate;
4512 } else if (reqSampleRate > maxSampleRate) {
4513 reqSampleRate = maxSampleRate;
4514 }
Eric Laurent81784c32012-11-19 14:55:58 -08004515 mAudioMixer->setParameter(
4516 name,
4517 AudioMixer::RESAMPLE,
4518 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004519 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004520
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004521 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004522 mAudioMixer->setParameter(
4523 name,
4524 AudioMixer::TIMESTRETCH,
4525 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004526 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004527
Andy Hung69aed5f2014-02-25 17:24:40 -08004528 /*
4529 * Select the appropriate output buffer for the track.
4530 *
Andy Hung98ef9782014-03-04 14:46:50 -08004531 * Tracks with effects go into their own effects chain buffer
4532 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004533 *
4534 * Other tracks can use mMixerBuffer for higher precision
4535 * channel accumulation. If this buffer is enabled
4536 * (mMixerBufferEnabled true), then selected tracks will accumulate
4537 * into it.
4538 *
4539 */
4540 if (mMixerBufferEnabled
4541 && (track->mainBuffer() == mSinkBuffer
4542 || track->mainBuffer() == mMixerBuffer)) {
4543 mAudioMixer->setParameter(
4544 name,
4545 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004546 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004547 mAudioMixer->setParameter(
4548 name,
4549 AudioMixer::TRACK,
4550 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4551 // TODO: override track->mainBuffer()?
4552 mMixerBufferValid = true;
4553 } else {
4554 mAudioMixer->setParameter(
4555 name,
4556 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004557 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004558 mAudioMixer->setParameter(
4559 name,
4560 AudioMixer::TRACK,
4561 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4562 }
Eric Laurent81784c32012-11-19 14:55:58 -08004563 mAudioMixer->setParameter(
4564 name,
4565 AudioMixer::TRACK,
4566 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4567
4568 // reset retry count
4569 track->mRetryCount = kMaxTrackRetries;
4570
4571 // If one track is ready, set the mixer ready if:
4572 // - the mixer was not ready during previous round OR
4573 // - no other track is not ready
4574 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4575 mixerStatus != MIXER_TRACKS_ENABLED) {
4576 mixerStatus = MIXER_TRACKS_READY;
4577 }
4578 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004579 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004580 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4581 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004582 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004583 } else {
4584 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004585 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004586
Eric Laurent81784c32012-11-19 14:55:58 -08004587 // clear effect chain input buffer if an active track underruns to avoid sending
4588 // previous audio buffer again to effects
4589 chain = getEffectChain_l(track->sessionId());
4590 if (chain != 0) {
4591 chain->clearInputBuffer();
4592 }
4593
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004594 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004595 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4596 track->isStopped() || track->isPaused()) {
4597 // We have consumed all the buffers of this track.
4598 // Remove it from the list of active tracks.
4599 // TODO: use actual buffer filling status instead of latency when available from
4600 // audio HAL
4601 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004602 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004603 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4604 if (track->isStopped()) {
4605 track->reset();
4606 }
4607 tracksToRemove->add(track);
4608 }
4609 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004610 // No buffers for this track. Give it a few chances to
4611 // fill a buffer, then remove it from active list.
4612 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004613 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004614 tracksToRemove->add(track);
4615 // indicate to client process that the track was disabled because of underrun;
4616 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004617 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004618 // If one track is not ready, mark the mixer also not ready if:
4619 // - the mixer was ready during previous round OR
4620 // - no other track is ready
4621 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4622 mixerStatus != MIXER_TRACKS_READY) {
4623 mixerStatus = MIXER_TRACKS_ENABLED;
4624 }
4625 }
4626 mAudioMixer->disable(name);
4627 }
4628
4629 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004630
4631 }
4632
4633 // Push the new FastMixer state if necessary
4634 bool pauseAudioWatchdog = false;
4635 if (didModify) {
4636 state->mFastTracksGen++;
4637 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4638 if (kUseFastMixer == FastMixer_Dynamic &&
4639 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4640 state->mCommand = FastMixerState::COLD_IDLE;
4641 state->mColdFutexAddr = &mFastMixerFutex;
4642 state->mColdGen++;
4643 mFastMixerFutex = 0;
4644 if (kUseFastMixer == FastMixer_Dynamic) {
4645 mNormalSink = mOutputSink;
4646 }
4647 // If we go into cold idle, need to wait for acknowledgement
4648 // so that fast mixer stops doing I/O.
4649 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4650 pauseAudioWatchdog = true;
4651 }
Eric Laurent81784c32012-11-19 14:55:58 -08004652 }
4653 if (sq != NULL) {
4654 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004655 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4656 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4657 // when bringing the output sink into standby.)
4658 //
4659 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4660 //
4661 // This occurs with BT suspend when we idle the FastMixer with
4662 // active tracks, which may be added or removed.
4663 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004664 }
4665#ifdef AUDIO_WATCHDOG
4666 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4667 mAudioWatchdog->pause();
4668 }
4669#endif
4670
4671 // Now perform the deferred reset on fast tracks that have stopped
4672 while (resetMask != 0) {
4673 size_t i = __builtin_ctz(resetMask);
4674 ALOG_ASSERT(i < count);
4675 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004676 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004677 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4678 track->reset();
4679 }
4680
4681 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004682 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004683
Eric Laurent97d547d2014-09-02 14:45:53 -07004684 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4685 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004686 }
4687
4688 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004689 // as long as there are effects we should clear the effects buffer, to avoid
4690 // passing a non-clean buffer to the effect chain
4691 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004692 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004693 // sink or mix buffer must be cleared if all tracks are connected to an
4694 // effect chain as in this case the mixer will not write to the sink or mix buffer
4695 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004696 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4697 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004698 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004699 if (mMixerBufferValid) {
4700 memset(mMixerBuffer, 0, mMixerBufferSize);
4701 // TODO: In testing, mSinkBuffer below need not be cleared because
4702 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4703 // after mixing.
4704 //
4705 // To enforce this guarantee:
4706 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4707 // (mixedTracks == 0 && fastTracks > 0))
4708 // must imply MIXER_TRACKS_READY.
4709 // Later, we may clear buffers regardless, and skip much of this logic.
4710 }
Andy Hung98ef9782014-03-04 14:46:50 -08004711 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004712 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004713 }
4714
4715 // if any fast tracks, then status is ready
4716 mMixerStatusIgnoringFastTracks = mixerStatus;
4717 if (fastTracks > 0) {
4718 mixerStatus = MIXER_TRACKS_READY;
4719 }
4720 return mixerStatus;
4721}
4722
Eric Laurentad7dd962016-09-22 12:38:37 -07004723// trackCountForUid_l() must be called with ThreadBase::mLock held
4724uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4725{
4726 uint32_t trackCount = 0;
4727 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004728 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004729 trackCount++;
4730 }
4731 }
4732 return trackCount;
4733}
4734
Eric Laurent81784c32012-11-19 14:55:58 -08004735// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004736int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004737 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004738{
Eric Laurentad7dd962016-09-22 12:38:37 -07004739 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4740 return -1;
4741 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004742 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004743}
4744
4745// deleteTrackName_l() must be called with ThreadBase::mLock held
4746void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4747{
4748 ALOGV("remove track (%d) and delete from mixer", name);
4749 mAudioMixer->deleteTrackName(name);
4750}
4751
Eric Laurent10351942014-05-08 18:49:52 -07004752// checkForNewParameter_l() must be called with ThreadBase::mLock held
4753bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4754 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004755{
Eric Laurent81784c32012-11-19 14:55:58 -08004756 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004757 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004758
Eric Laurent10351942014-05-08 18:49:52 -07004759 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004760
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004761 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004762
Eric Laurent10351942014-05-08 18:49:52 -07004763 AudioParameter param = AudioParameter(keyValuePair);
4764 int value;
4765 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4766 reconfig = true;
4767 }
4768 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004769 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004770 status = BAD_VALUE;
4771 } else {
4772 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004773 reconfig = true;
4774 }
Eric Laurent10351942014-05-08 18:49:52 -07004775 }
4776 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004777 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004778 status = BAD_VALUE;
4779 } else {
4780 // no need to save value, since it's constant
4781 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004782 }
Eric Laurent10351942014-05-08 18:49:52 -07004783 }
4784 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4785 // do not accept frame count changes if tracks are open as the track buffer
4786 // size depends on frame count and correct behavior would not be guaranteed
4787 // if frame count is changed after track creation
4788 if (!mTracks.isEmpty()) {
4789 status = INVALID_OPERATION;
4790 } else {
4791 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004792 }
Eric Laurent10351942014-05-08 18:49:52 -07004793 }
4794 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004795#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004796 // when changing the audio output device, call addBatteryData to notify
4797 // the change
4798 if (mOutDevice != value) {
4799 uint32_t params = 0;
4800 // check whether speaker is on
4801 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4802 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004803 }
Eric Laurent10351942014-05-08 18:49:52 -07004804
4805 audio_devices_t deviceWithoutSpeaker
4806 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4807 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004808 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004809 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4810 }
4811
4812 if (params != 0) {
4813 addBatteryData(params);
4814 }
4815 }
Eric Laurent81784c32012-11-19 14:55:58 -08004816#endif
4817
Eric Laurent10351942014-05-08 18:49:52 -07004818 // forward device change to effects that have requested to be
4819 // aware of attached audio device.
4820 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004821 a2dpDeviceChanged =
4822 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004823 mOutDevice = value;
4824 for (size_t i = 0; i < mEffectChains.size(); i++) {
4825 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004826 }
4827 }
Eric Laurent10351942014-05-08 18:49:52 -07004828 }
Eric Laurent81784c32012-11-19 14:55:58 -08004829
Eric Laurent10351942014-05-08 18:49:52 -07004830 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004831 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004832 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004833 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004834 mStandby = true;
4835 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004836 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004837 }
Eric Laurent10351942014-05-08 18:49:52 -07004838 if (status == NO_ERROR && reconfig) {
4839 readOutputParameters_l();
4840 delete mAudioMixer;
4841 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4842 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004843 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004844 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004845 if (name < 0) {
4846 break;
4847 }
4848 mTracks[i]->mName = name;
4849 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004850 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004851 }
Eric Laurent81784c32012-11-19 14:55:58 -08004852 }
4853
Eric Laurent42537be2016-01-08 17:16:42 -08004854 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004855}
4856
4857
4858void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4859{
Eric Laurent81784c32012-11-19 14:55:58 -08004860 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004861 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004862 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004863 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004864
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004865 if (hasFastMixer()) {
4866 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4867
4868 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4869 // while we are dumping it. It may be inconsistent, but it won't mutate!
4870 // This is a large object so we place it on the heap.
4871 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4872 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4873 copy->dump(fd);
4874 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004875
4876#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004877 // Similar for state queue
4878 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4879 observerCopy.dump(fd);
4880 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4881 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004882#endif
4883
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004884#ifdef AUDIO_WATCHDOG
4885 if (mAudioWatchdog != 0) {
4886 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4887 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4888 wdCopy.dump(fd);
4889 }
4890#endif
4891
4892 } else {
4893 dprintf(fd, " No FastMixer\n");
4894 }
4895
Glenn Kasten46909e72013-02-26 09:20:22 -08004896#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004897 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004898 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004899#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004900
Eric Laurent81784c32012-11-19 14:55:58 -08004901}
4902
4903uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4904{
4905 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4906}
4907
4908uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4909{
4910 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4911}
4912
4913void AudioFlinger::MixerThread::cacheParameters_l()
4914{
4915 PlaybackThread::cacheParameters_l();
4916
4917 // FIXME: Relaxed timing because of a certain device that can't meet latency
4918 // Should be reduced to 2x after the vendor fixes the driver issue
4919 // increase threshold again due to low power audio mode. The way this warning
4920 // threshold is calculated and its usefulness should be reconsidered anyway.
4921 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4922}
4923
4924// ----------------------------------------------------------------------------
4925
4926AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004927 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4928 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004929{
4930}
4931
Eric Laurentbfb1b832013-01-07 09:53:42 -08004932AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4933 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004934 ThreadBase::type_t type, bool systemReady)
4935 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08004936 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004937{
4938}
4939
Eric Laurent81784c32012-11-19 14:55:58 -08004940AudioFlinger::DirectOutputThread::~DirectOutputThread()
4941{
4942}
4943
Eric Laurent5850c4c2016-11-10 13:04:31 -08004944void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004945{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004946 float left, right;
4947
4948 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4949 left = right = 0;
4950 } else {
4951 float typeVolume = mStreamTypes[track->streamType()].volume;
4952 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004953 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004954
Andy Hung10cbff12017-02-21 17:30:14 -08004955 // Get volumeshaper scaling
4956 std::pair<float /* volume */, bool /* active */>
4957 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004958 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004959 v *= vh.first;
4960 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004961
Glenn Kastenc56f3422014-03-21 17:53:17 -07004962 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4963 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4964 if (left > GAIN_FLOAT_UNITY) {
4965 left = GAIN_FLOAT_UNITY;
4966 }
4967 left *= v;
4968 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4969 if (right > GAIN_FLOAT_UNITY) {
4970 right = GAIN_FLOAT_UNITY;
4971 }
4972 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004973 }
4974
4975 if (lastTrack) {
4976 if (left != mLeftVolFloat || right != mRightVolFloat) {
4977 mLeftVolFloat = left;
4978 mRightVolFloat = right;
4979
4980 // Convert volumes from float to 8.24
4981 uint32_t vl = (uint32_t)(left * (1 << 24));
4982 uint32_t vr = (uint32_t)(right * (1 << 24));
4983
4984 // Delegate volume control to effect in track effect chain if needed
4985 // only one effect chain can be present on DirectOutputThread, so if
4986 // there is one, the track is connected to it
4987 if (!mEffectChains.isEmpty()) {
4988 mEffectChains[0]->setVolume_l(&vl, &vr);
4989 left = (float)vl / (1 << 24);
4990 right = (float)vr / (1 << 24);
4991 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004992 status_t result = mOutput->stream->setVolume(left, right);
4993 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004994 }
4995 }
4996}
4997
Phil Burk43b4dcc2015-06-09 16:53:44 -07004998void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4999{
5000 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005001 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005002
Eric Laurent0f0631e2015-07-06 18:01:25 -07005003 if (previousTrack != 0 && latestTrack != 0) {
5004 if (mType == DIRECT) {
5005 if (previousTrack.get() != latestTrack.get()) {
5006 mFlushPending = true;
5007 }
5008 } else /* mType == OFFLOAD */ {
5009 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5010 mFlushPending = true;
5011 }
5012 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005013 }
5014 PlaybackThread::onAddNewTrack_l();
5015}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005016
Eric Laurent81784c32012-11-19 14:55:58 -08005017AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5018 Vector< sp<Track> > *tracksToRemove
5019)
5020{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005021 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005022 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005023 bool doHwPause = false;
5024 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005025
5026 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005027 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005028 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005029 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005030 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005031 continue;
5032 }
5033
Eric Laurent5850c4c2016-11-10 13:04:31 -08005034 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005035#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005036 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005037#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005038 // Only consider last track started for volume and mixer state control.
5039 // In theory an older track could underrun and restart after the new one starts
5040 // but as we only care about the transition phase between two tracks on a
5041 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005042 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005043 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005044
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005045 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005046 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005047 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005048 doHwPause = true;
5049 mHwPaused = true;
5050 }
5051 tracksToRemove->add(track);
5052 } else if (track->isFlushPending()) {
5053 track->flushAck();
5054 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005055 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005056 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005057 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005058 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005059 if (last) {
5060 mLeftVolFloat = mRightVolFloat = -1.0;
5061 if (mHwPaused) {
5062 doHwResume = true;
5063 mHwPaused = false;
5064 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005065 }
5066 }
5067
Eric Laurent81784c32012-11-19 14:55:58 -08005068 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005069 // for all its buffers to be filled before processing it.
5070 // Allow draining the buffer in case the client
5071 // app does not call stop() and relies on underrun to stop:
5072 // hence the test on (track->mRetryCount > 1).
5073 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005074 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005075 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005076 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005077 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005078 minFrames = mNormalFrameCount;
5079 } else {
5080 minFrames = 1;
5081 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005082
Eric Laurentab5cdba2014-06-09 17:22:27 -07005083 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5084 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005085 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005086 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005087
5088 if (track->mFillingUpStatus == Track::FS_FILLED) {
5089 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005090 if (last) {
5091 // make sure processVolume_l() will apply new volume even if 0
5092 mLeftVolFloat = mRightVolFloat = -1.0;
5093 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005094 if (!mHwSupportsPause) {
5095 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005096 }
5097 }
5098
5099 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005100 processVolume_l(track, last);
5101 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005102 sp<Track> previousTrack = mPreviousTrack.promote();
5103 if (previousTrack != 0) {
5104 if (track != previousTrack.get()) {
5105 // Flush any data still being written from last track
5106 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005107 // Invalidate previous track to force a seek when resuming.
5108 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005109 }
5110 }
5111 mPreviousTrack = track;
5112
Eric Laurentd595b7c2013-04-03 17:27:56 -07005113 // reset retry count
5114 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005115 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005116 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005117 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005118 doHwResume = true;
5119 mHwPaused = false;
5120 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005121 }
Eric Laurent81784c32012-11-19 14:55:58 -08005122 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005123 // clear effect chain input buffer if the last active track started underruns
5124 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005125 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005126 mEffectChains[0]->clearInputBuffer();
5127 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005128 if (track->isStopping_1()) {
5129 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005130 if (last && mHwPaused) {
5131 doHwResume = true;
5132 mHwPaused = false;
5133 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005134 }
5135 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5136 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005137 // We have consumed all the buffers of this track.
5138 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005139 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005140 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005141 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5142 } else {
5143 audioHALFrames = 0;
5144 }
5145
Andy Hung818e7a32016-02-16 18:08:07 -08005146 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005147 if (mStandby || !last ||
5148 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005149 if (track->isStopping_2()) {
5150 track->mState = TrackBase::STOPPED;
5151 }
Eric Laurent81784c32012-11-19 14:55:58 -08005152 if (track->isStopped()) {
5153 track->reset();
5154 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005155 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005156 }
5157 } else {
5158 // No buffers for this track. Give it a few chances to
5159 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005160 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005161 if (--(track->mRetryCount) <= 0) {
5162 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005163 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005164 // indicate to client process that the track was disabled because of underrun;
5165 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005166 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005167 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005168 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5169 "minFrames = %u, mFormat = %#x",
5170 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005171 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005172 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005173 doHwPause = true;
5174 mHwPaused = true;
5175 }
Eric Laurent81784c32012-11-19 14:55:58 -08005176 }
5177 }
5178 }
5179 }
5180
Eric Laurentd1f69b02014-12-15 14:33:13 -08005181 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005182 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005183 for (size_t i = 0; i < mTracks.size(); i++) {
5184 if (mTracks[i]->isFlushPending()) {
5185 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005186 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005187 }
5188 }
5189 }
5190
5191 // make sure the pause/flush/resume sequence is executed in the right order.
5192 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5193 // before flush and then resume HW. This can happen in case of pause/flush/resume
5194 // if resume is received before pause is executed.
5195 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005196 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005197 status_t result = mOutput->stream->pause();
5198 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005199 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005200 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005201 flushHw_l();
5202 }
5203 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005204 status_t result = mOutput->stream->resume();
5205 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005206 }
Eric Laurent81784c32012-11-19 14:55:58 -08005207 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005208 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005209
5210 return mixerStatus;
5211}
5212
5213void AudioFlinger::DirectOutputThread::threadLoop_mix()
5214{
Eric Laurent81784c32012-11-19 14:55:58 -08005215 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005216 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005217 // output audio to hardware
5218 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005219 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005220 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005221 status_t status = mActiveTrack->getNextBuffer(&buffer);
5222 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005223 // no need to pad with 0 for compressed audio
5224 if (audio_has_proportional_frames(mFormat)) {
5225 memset(curBuf, 0, frameCount * mFrameSize);
5226 }
Eric Laurent81784c32012-11-19 14:55:58 -08005227 break;
5228 }
5229 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5230 frameCount -= buffer.frameCount;
5231 curBuf += buffer.frameCount * mFrameSize;
5232 mActiveTrack->releaseBuffer(&buffer);
5233 }
Andy Hung2098f272014-02-27 14:00:06 -08005234 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005235 mSleepTimeUs = 0;
5236 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005237 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005238}
5239
5240void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5241{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005242 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005243 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005244 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005245 return;
5246 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005247 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005248 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005249 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005250 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005251 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005252 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005253 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005254 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005255 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005256 }
5257}
5258
Eric Laurentd1f69b02014-12-15 14:33:13 -08005259void AudioFlinger::DirectOutputThread::threadLoop_exit()
5260{
5261 {
5262 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005263 for (size_t i = 0; i < mTracks.size(); i++) {
5264 if (mTracks[i]->isFlushPending()) {
5265 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005266 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005267 }
5268 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005269 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005270 flushHw_l();
5271 }
5272 }
5273 PlaybackThread::threadLoop_exit();
5274}
5275
5276// must be called with thread mutex locked
5277bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5278{
5279 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005280 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005281
vivek mehta9cd7ad12016-03-17 00:18:29 -07005282 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5283 return !mStandby;
5284 }
5285
Eric Laurentd1f69b02014-12-15 14:33:13 -08005286 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5287 // after a timeout and we will enter standby then.
5288 if (mTracks.size() > 0) {
5289 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005290 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5291 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005292 }
5293
Eric Laurent5cff4032015-05-26 13:49:58 -07005294 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005295}
5296
Eric Laurent81784c32012-11-19 14:55:58 -08005297// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005298int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005299 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005300{
Eric Laurentad7dd962016-09-22 12:38:37 -07005301 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5302 return -1;
5303 }
Eric Laurent81784c32012-11-19 14:55:58 -08005304 return 0;
5305}
5306
5307// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005308void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005309{
5310}
5311
Eric Laurent10351942014-05-08 18:49:52 -07005312// checkForNewParameter_l() must be called with ThreadBase::mLock held
5313bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5314 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005315{
5316 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005317 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005318
Eric Laurent10351942014-05-08 18:49:52 -07005319 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005320
Eric Laurent10351942014-05-08 18:49:52 -07005321 AudioParameter param = AudioParameter(keyValuePair);
5322 int value;
5323 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5324 // forward device change to effects that have requested to be
5325 // aware of attached audio device.
5326 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005327 a2dpDeviceChanged =
5328 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005329 mOutDevice = value;
5330 for (size_t i = 0; i < mEffectChains.size(); i++) {
5331 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005332 }
5333 }
Eric Laurent81784c32012-11-19 14:55:58 -08005334 }
Eric Laurent10351942014-05-08 18:49:52 -07005335 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5336 // do not accept frame count changes if tracks are open as the track buffer
5337 // size depends on frame count and correct behavior would not be garantied
5338 // if frame count is changed after track creation
5339 if (!mTracks.isEmpty()) {
5340 status = INVALID_OPERATION;
5341 } else {
5342 reconfig = true;
5343 }
5344 }
5345 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005346 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005347 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005348 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005349 mStandby = true;
5350 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005351 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005352 }
5353 if (status == NO_ERROR && reconfig) {
5354 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005355 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005356 }
5357 }
5358
Eric Laurent42537be2016-01-08 17:16:42 -08005359 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005360}
5361
5362uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5363{
5364 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005365 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005366 time = PlaybackThread::activeSleepTimeUs();
5367 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005368 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005369 }
5370 return time;
5371}
5372
5373uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5374{
5375 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005376 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005377 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5378 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005379 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005380 }
5381 return time;
5382}
5383
5384uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5385{
5386 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005387 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005388 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5389 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005390 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005391 }
5392 return time;
5393}
5394
5395void AudioFlinger::DirectOutputThread::cacheParameters_l()
5396{
5397 PlaybackThread::cacheParameters_l();
5398
5399 // use shorter standby delay as on normal output to release
5400 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005401 // no delay on outputs with HW A/V sync
5402 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005403 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005404 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005405 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005406 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005407 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005408 }
Eric Laurent81784c32012-11-19 14:55:58 -08005409}
5410
Eric Laurente659ef42014-09-29 13:06:46 -07005411void AudioFlinger::DirectOutputThread::flushHw_l()
5412{
Phil Burk062e67a2015-02-11 13:40:50 -08005413 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005414 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005415 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005416}
5417
Andy Hung10cbff12017-02-21 17:30:14 -08005418int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5419 // If a VolumeShaper is active, we must wake up periodically to update volume.
5420 const int64_t NS_PER_MS = 1000000;
5421 return mVolumeShaperActive ?
5422 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5423}
5424
Eric Laurent81784c32012-11-19 14:55:58 -08005425// ----------------------------------------------------------------------------
5426
Eric Laurentbfb1b832013-01-07 09:53:42 -08005427AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005428 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005429 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005430 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005431 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005432 mDrainSequence(0),
5433 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005434{
5435}
5436
5437AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5438{
5439}
5440
5441void AudioFlinger::AsyncCallbackThread::onFirstRef()
5442{
5443 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5444}
5445
5446bool AudioFlinger::AsyncCallbackThread::threadLoop()
5447{
5448 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005449 uint32_t writeAckSequence;
5450 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005451 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005452
5453 {
5454 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005455 while (!((mWriteAckSequence & 1) ||
5456 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005457 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005458 exitPending())) {
5459 mWaitWorkCV.wait(mLock);
5460 }
5461
Eric Laurentbfb1b832013-01-07 09:53:42 -08005462 if (exitPending()) {
5463 break;
5464 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005465 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5466 mWriteAckSequence, mDrainSequence);
5467 writeAckSequence = mWriteAckSequence;
5468 mWriteAckSequence &= ~1;
5469 drainSequence = mDrainSequence;
5470 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005471 asyncError = mAsyncError;
5472 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005473 }
5474 {
Eric Laurent4de95592013-09-26 15:28:21 -07005475 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5476 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005477 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005478 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005479 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005480 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005481 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005483 if (asyncError) {
5484 playbackThread->onAsyncError();
5485 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005486 }
5487 }
5488 }
5489 return false;
5490}
5491
5492void AudioFlinger::AsyncCallbackThread::exit()
5493{
5494 ALOGV("AsyncCallbackThread::exit");
5495 Mutex::Autolock _l(mLock);
5496 requestExit();
5497 mWaitWorkCV.broadcast();
5498}
5499
Eric Laurent3b4529e2013-09-05 18:09:19 -07005500void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005501{
5502 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005503 // bit 0 is cleared
5504 mWriteAckSequence = sequence << 1;
5505}
5506
5507void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5508{
5509 Mutex::Autolock _l(mLock);
5510 // ignore unexpected callbacks
5511 if (mWriteAckSequence & 2) {
5512 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005513 mWaitWorkCV.signal();
5514 }
5515}
5516
Eric Laurent3b4529e2013-09-05 18:09:19 -07005517void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005518{
5519 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005520 // bit 0 is cleared
5521 mDrainSequence = sequence << 1;
5522}
5523
5524void AudioFlinger::AsyncCallbackThread::resetDraining()
5525{
5526 Mutex::Autolock _l(mLock);
5527 // ignore unexpected callbacks
5528 if (mDrainSequence & 2) {
5529 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005530 mWaitWorkCV.signal();
5531 }
5532}
5533
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005534void AudioFlinger::AsyncCallbackThread::setAsyncError()
5535{
5536 Mutex::Autolock _l(mLock);
5537 mAsyncError = true;
5538 mWaitWorkCV.signal();
5539}
5540
Eric Laurentbfb1b832013-01-07 09:53:42 -08005541
5542// ----------------------------------------------------------------------------
5543AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005544 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5545 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005546 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5547 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005548{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005549 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005550 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005551 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005552}
5553
Eric Laurentbfb1b832013-01-07 09:53:42 -08005554void AudioFlinger::OffloadThread::threadLoop_exit()
5555{
5556 if (mFlushPending || mHwPaused) {
5557 // If a flush is pending or track was paused, just discard buffered data
5558 flushHw_l();
5559 } else {
5560 mMixerStatus = MIXER_DRAIN_ALL;
5561 threadLoop_drain();
5562 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005563 if (mUseAsyncWrite) {
5564 ALOG_ASSERT(mCallbackThread != 0);
5565 mCallbackThread->exit();
5566 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005567 PlaybackThread::threadLoop_exit();
5568}
5569
5570AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5571 Vector< sp<Track> > *tracksToRemove
5572)
5573{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005574 size_t count = mActiveTracks.size();
5575
5576 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005577 bool doHwPause = false;
5578 bool doHwResume = false;
5579
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005580 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005581
Eric Laurentbfb1b832013-01-07 09:53:42 -08005582 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005583 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005584 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005585#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005586 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005587#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005588 // Only consider last track started for volume and mixer state control.
5589 // In theory an older track could underrun and restart after the new one starts
5590 // but as we only care about the transition phase between two tracks on a
5591 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005592 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005593 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005594
Haynes Mathew George7844f672014-01-15 12:32:55 -08005595 if (track->isInvalid()) {
5596 ALOGW("An invalidated track shouldn't be in active list");
5597 tracksToRemove->add(track);
5598 continue;
5599 }
5600
5601 if (track->mState == TrackBase::IDLE) {
5602 ALOGW("An idle track shouldn't be in active list");
5603 continue;
5604 }
5605
Eric Laurentbfb1b832013-01-07 09:53:42 -08005606 if (track->isPausing()) {
5607 track->setPaused();
5608 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005609 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005610 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005611 mHwPaused = true;
5612 }
5613 // If we were part way through writing the mixbuffer to
5614 // the HAL we must save this until we resume
5615 // BUG - this will be wrong if a different track is made active,
5616 // in that case we want to discard the pending data in the
5617 // mixbuffer and tell the client to present it again when the
5618 // track is resumed
5619 mPausedWriteLength = mCurrentWriteLength;
5620 mPausedBytesRemaining = mBytesRemaining;
5621 mBytesRemaining = 0; // stop writing
5622 }
5623 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005624 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005625 if (track->isStopping_1()) {
5626 track->mRetryCount = kMaxTrackStopRetriesOffload;
5627 } else {
5628 track->mRetryCount = kMaxTrackRetriesOffload;
5629 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005630 track->flushAck();
5631 if (last) {
5632 mFlushPending = true;
5633 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005634 } else if (track->isResumePending()){
5635 track->resumeAck();
5636 if (last) {
5637 if (mPausedBytesRemaining) {
5638 // Need to continue write that was interrupted
5639 mCurrentWriteLength = mPausedWriteLength;
5640 mBytesRemaining = mPausedBytesRemaining;
5641 mPausedBytesRemaining = 0;
5642 }
5643 if (mHwPaused) {
5644 doHwResume = true;
5645 mHwPaused = false;
5646 // threadLoop_mix() will handle the case that we need to
5647 // resume an interrupted write
5648 }
5649 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005650 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005651
Eric Laurent3df841a2016-07-15 15:15:40 -07005652 mLeftVolFloat = mRightVolFloat = -1.0;
5653
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005654 // Do not handle new data in this iteration even if track->framesReady()
5655 mixerStatus = MIXER_TRACKS_ENABLED;
5656 }
5657 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005658 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005659 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005660 if (track->mFillingUpStatus == Track::FS_FILLED) {
5661 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005662 if (last) {
5663 // make sure processVolume_l() will apply new volume even if 0
5664 mLeftVolFloat = mRightVolFloat = -1.0;
5665 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005666 }
5667
5668 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005669 sp<Track> previousTrack = mPreviousTrack.promote();
5670 if (previousTrack != 0) {
5671 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005672 // Flush any data still being written from last track
5673 mBytesRemaining = 0;
5674 if (mPausedBytesRemaining) {
5675 // Last track was paused so we also need to flush saved
5676 // mixbuffer state and invalidate track so that it will
5677 // re-submit that unwritten data when it is next resumed
5678 mPausedBytesRemaining = 0;
5679 // Invalidate is a bit drastic - would be more efficient
5680 // to have a flag to tell client that some of the
5681 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005682 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005683 }
5684 // flush data already sent to the DSP if changing audio session as audio
5685 // comes from a different source. Also invalidate previous track to force a
5686 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005687 if (previousTrack->sessionId() != track->sessionId()) {
5688 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005689 }
5690 }
5691 }
5692 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005693 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005694 if (track->isStopping_1()) {
5695 track->mRetryCount = kMaxTrackStopRetriesOffload;
5696 } else {
5697 track->mRetryCount = kMaxTrackRetriesOffload;
5698 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005699 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005700 mixerStatus = MIXER_TRACKS_READY;
5701 }
5702 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005703 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005704 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005705 if (--(track->mRetryCount) <= 0) {
5706 // Hardware buffer can hold a large amount of audio so we must
5707 // wait for all current track's data to drain before we say
5708 // that the track is stopped.
5709 if (mBytesRemaining == 0) {
5710 // Only start draining when all data in mixbuffer
5711 // has been written
5712 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5713 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5714 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5715 if (last && !mStandby) {
5716 // do not modify drain sequence if we are already draining. This happens
5717 // when resuming from pause after drain.
5718 if ((mDrainSequence & 1) == 0) {
5719 mSleepTimeUs = 0;
5720 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5721 mixerStatus = MIXER_DRAIN_TRACK;
5722 mDrainSequence += 2;
5723 }
5724 if (mHwPaused) {
5725 // It is possible to move from PAUSED to STOPPING_1 without
5726 // a resume so we must ensure hardware is running
5727 doHwResume = true;
5728 mHwPaused = false;
5729 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005730 }
5731 }
Eric Laurente93cc032016-05-05 10:15:10 -07005732 } else if (last) {
5733 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5734 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005735 }
5736 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005737 // Drain has completed or we are in standby, signal presentation complete
5738 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005739 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005740 uint32_t latency = 0;
5741 status_t result = mOutput->stream->getLatency(&latency);
5742 ALOGE_IF(result != OK,
5743 "Error when retrieving output stream latency: %d", result);
5744 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005745 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005746 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005747 track->presentationComplete(framesWritten, audioHALFrames);
5748 track->reset();
5749 tracksToRemove->add(track);
5750 }
5751 } else {
5752 // No buffers for this track. Give it a few chances to
5753 // fill a buffer, then remove it from active list.
5754 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005755 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005756 uint64_t position = 0;
5757 struct timespec unused;
5758 // The running check restarts the retry counter at least once.
5759 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5760 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5761 running = true;
5762 mOffloadUnderrunPosition = position;
5763 }
5764 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005765 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5766 (long long)position, (long long)mOffloadUnderrunPosition);
5767 }
5768 if (running) { // still running, give us more time.
5769 track->mRetryCount = kMaxTrackRetriesOffload;
5770 } else {
5771 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5772 track->name());
5773 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005774 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005775 // it will then automatically call start() when data is available
5776 track->disable();
5777 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005778 } else if (last){
5779 mixerStatus = MIXER_TRACKS_ENABLED;
5780 }
5781 }
5782 }
5783 // compute volume for this track
5784 processVolume_l(track, last);
5785 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005786
Eric Laurentea0fade2013-10-04 16:23:48 -07005787 // make sure the pause/flush/resume sequence is executed in the right order.
5788 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5789 // before flush and then resume HW. This can happen in case of pause/flush/resume
5790 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005791 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005792 status_t result = mOutput->stream->pause();
5793 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005794 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005795 if (mFlushPending) {
5796 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005797 }
Eric Laurentfd477972013-10-25 18:10:40 -07005798 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005799 status_t result = mOutput->stream->resume();
5800 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005801 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005802
Eric Laurentbfb1b832013-01-07 09:53:42 -08005803 // remove all the tracks that need to be...
5804 removeTracks_l(*tracksToRemove);
5805
5806 return mixerStatus;
5807}
5808
Eric Laurentbfb1b832013-01-07 09:53:42 -08005809// must be called with thread mutex locked
5810bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5811{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005812 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5813 mWriteAckSequence, mDrainSequence);
5814 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005815 return true;
5816 }
5817 return false;
5818}
5819
Eric Laurentbfb1b832013-01-07 09:53:42 -08005820bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5821{
5822 Mutex::Autolock _l(mLock);
5823 return waitingAsyncCallback_l();
5824}
5825
5826void AudioFlinger::OffloadThread::flushHw_l()
5827{
Eric Laurente659ef42014-09-29 13:06:46 -07005828 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005829 // Flush anything still waiting in the mixbuffer
5830 mCurrentWriteLength = 0;
5831 mBytesRemaining = 0;
5832 mPausedWriteLength = 0;
5833 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005834 // reset bytes written count to reflect that DSP buffers are empty after flush.
5835 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005836 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005837
Eric Laurentbfb1b832013-01-07 09:53:42 -08005838 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005839 // discard any pending drain or write ack by incrementing sequence
5840 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5841 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005842 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005843 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5844 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005845 }
5846}
5847
Haynes Mathew George05317d22016-05-03 16:34:26 -07005848void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5849{
5850 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005851 if (PlaybackThread::invalidateTracks_l(streamType)) {
5852 mFlushPending = true;
5853 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005854}
5855
Eric Laurentbfb1b832013-01-07 09:53:42 -08005856// ----------------------------------------------------------------------------
5857
Eric Laurent81784c32012-11-19 14:55:58 -08005858AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005859 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005860 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005861 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005862 mWaitTimeMs(UINT_MAX)
5863{
5864 addOutputTrack(mainThread);
5865}
5866
5867AudioFlinger::DuplicatingThread::~DuplicatingThread()
5868{
5869 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5870 mOutputTracks[i]->destroy();
5871 }
5872}
5873
5874void AudioFlinger::DuplicatingThread::threadLoop_mix()
5875{
5876 // mix buffers...
5877 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005878 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005879 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005880 if (mMixerBufferValid) {
5881 memset(mMixerBuffer, 0, mMixerBufferSize);
5882 } else {
5883 memset(mSinkBuffer, 0, mSinkBufferSize);
5884 }
Eric Laurent81784c32012-11-19 14:55:58 -08005885 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005886 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005887 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005888 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005889 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005890}
5891
5892void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5893{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005894 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005895 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005896 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005897 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005898 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005899 }
5900 } else if (mBytesWritten != 0) {
5901 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5902 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005903 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005904 } else {
5905 // flush remaining overflow buffers in output tracks
5906 writeFrames = 0;
5907 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005908 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005909 }
5910}
5911
Eric Laurentbfb1b832013-01-07 09:53:42 -08005912ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005913{
5914 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005915 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005916 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005917 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005918 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005919}
5920
5921void AudioFlinger::DuplicatingThread::threadLoop_standby()
5922{
5923 // DuplicatingThread implements standby by stopping all tracks
5924 for (size_t i = 0; i < outputTracks.size(); i++) {
5925 outputTracks[i]->stop();
5926 }
5927}
5928
5929void AudioFlinger::DuplicatingThread::saveOutputTracks()
5930{
5931 outputTracks = mOutputTracks;
5932}
5933
5934void AudioFlinger::DuplicatingThread::clearOutputTracks()
5935{
5936 outputTracks.clear();
5937}
5938
5939void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5940{
5941 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005942 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5943 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5944 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5945 const size_t frameCount =
5946 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5947 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5948 // from different OutputTracks and their associated MixerThreads (e.g. one may
5949 // nearly empty and the other may be dropping data).
5950
5951 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005952 this,
5953 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005954 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005955 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005956 frameCount,
5957 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005958 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5959 if (status != NO_ERROR) {
5960 ALOGE("addOutputTrack() initCheck failed %d", status);
5961 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005962 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005963 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5964 mOutputTracks.add(outputTrack);
5965 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5966 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005967}
5968
5969void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5970{
5971 Mutex::Autolock _l(mLock);
5972 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5973 if (mOutputTracks[i]->thread() == thread) {
5974 mOutputTracks[i]->destroy();
5975 mOutputTracks.removeAt(i);
5976 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005977 if (thread->getOutput() == mOutput) {
5978 mOutput = NULL;
5979 }
Eric Laurent81784c32012-11-19 14:55:58 -08005980 return;
5981 }
5982 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005983 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005984}
5985
5986// caller must hold mLock
5987void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5988{
5989 mWaitTimeMs = UINT_MAX;
5990 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5991 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5992 if (strong != 0) {
5993 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5994 if (waitTimeMs < mWaitTimeMs) {
5995 mWaitTimeMs = waitTimeMs;
5996 }
5997 }
5998 }
5999}
6000
6001
6002bool AudioFlinger::DuplicatingThread::outputsReady(
6003 const SortedVector< sp<OutputTrack> > &outputTracks)
6004{
6005 for (size_t i = 0; i < outputTracks.size(); i++) {
6006 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6007 if (thread == 0) {
6008 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6009 outputTracks[i].get());
6010 return false;
6011 }
6012 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6013 // see note at standby() declaration
6014 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6015 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6016 thread.get());
6017 return false;
6018 }
6019 }
6020 return true;
6021}
6022
6023uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6024{
6025 return (mWaitTimeMs * 1000) / 2;
6026}
6027
6028void AudioFlinger::DuplicatingThread::cacheParameters_l()
6029{
6030 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6031 updateWaitTime_l();
6032
6033 MixerThread::cacheParameters_l();
6034}
6035
Eric Laurent6acd1d42017-01-04 14:23:29 -08006036
Eric Laurent81784c32012-11-19 14:55:58 -08006037// ----------------------------------------------------------------------------
6038// Record
6039// ----------------------------------------------------------------------------
6040
6041AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6042 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006043 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006044 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006045 audio_devices_t inDevice,
6046 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006047#ifdef TEE_SINK
6048 , const sp<NBAIO_Sink>& teeSink
6049#endif
6050 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006051 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006052 mInput(input),
6053 mActiveTracks(&this->mLocalLog),
6054 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006055 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006056 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08006057#ifdef TEE_SINK
6058 , mTeeSink(teeSink)
6059#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006060 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6061 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006062 // mFastCapture below
6063 , mFastCaptureFutex(0)
6064 // mInputSource
6065 // mPipeSink
6066 // mPipeSource
6067 , mPipeFramesP2(0)
6068 // mPipeMemory
6069 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006070 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006071 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006072{
Glenn Kastend7dca052015-03-05 16:05:54 -08006073 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6074 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006075
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006076 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006077
6078 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006079 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006080 size_t numCounterOffers = 0;
6081 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006082#if !LOG_NDEBUG
6083 ssize_t index =
6084#else
6085 (void)
6086#endif
6087 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006088 ALOG_ASSERT(index == 0);
6089
6090 // initialize fast capture depending on configuration
6091 bool initFastCapture;
6092 switch (kUseFastCapture) {
6093 case FastCapture_Never:
6094 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006095 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006096 break;
6097 case FastCapture_Always:
6098 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006099 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006100 break;
6101 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006102 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006103 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6104 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6105 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006106 break;
6107 // case FastCapture_Dynamic:
6108 }
6109
6110 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006111 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006112 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006113 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6114 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006115 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006116 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006117 const sp<MemoryDealer> roHeap(readOnlyHeap());
6118 sp<IMemory> pipeMemory;
6119 if ((roHeap == 0) ||
6120 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006121 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6122 ALOGE("not enough memory for pipe buffer size=%zu; "
6123 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6124 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6125 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006126 goto failed;
6127 }
6128 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6129 memset(pipeBuffer, 0, pipeSize);
6130 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6131 const NBAIO_Format offers[1] = {format};
6132 size_t numCounterOffers = 0;
6133 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6134 ALOG_ASSERT(index == 0);
6135 mPipeSink = pipe;
6136 PipeReader *pipeReader = new PipeReader(*pipe);
6137 numCounterOffers = 0;
6138 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6139 ALOG_ASSERT(index == 0);
6140 mPipeSource = pipeReader;
6141 mPipeFramesP2 = pipeFramesP2;
6142 mPipeMemory = pipeMemory;
6143
6144 // create fast capture
6145 mFastCapture = new FastCapture();
6146 FastCaptureStateQueue *sq = mFastCapture->sq();
6147#ifdef STATE_QUEUE_DUMP
6148 // FIXME
6149#endif
6150 FastCaptureState *state = sq->begin();
6151 state->mCblk = NULL;
6152 state->mInputSource = mInputSource.get();
6153 state->mInputSourceGen++;
6154 state->mPipeSink = pipe;
6155 state->mPipeSinkGen++;
6156 state->mFrameCount = mFrameCount;
6157 state->mCommand = FastCaptureState::COLD_IDLE;
6158 // already done in constructor initialization list
6159 //mFastCaptureFutex = 0;
6160 state->mColdFutexAddr = &mFastCaptureFutex;
6161 state->mColdGen++;
6162 state->mDumpState = &mFastCaptureDumpState;
6163#ifdef TEE_SINK
6164 // FIXME
6165#endif
6166 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6167 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6168 sq->end();
6169 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6170
6171 // start the fast capture
6172 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6173 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006174 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006175 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006176#ifdef AUDIO_WATCHDOG
6177 // FIXME
6178#endif
6179
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006180 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006181 }
6182failed: ;
6183
6184 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006185}
6186
Eric Laurent81784c32012-11-19 14:55:58 -08006187AudioFlinger::RecordThread::~RecordThread()
6188{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006189 if (mFastCapture != 0) {
6190 FastCaptureStateQueue *sq = mFastCapture->sq();
6191 FastCaptureState *state = sq->begin();
6192 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6193 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6194 if (old == -1) {
6195 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6196 }
6197 }
6198 state->mCommand = FastCaptureState::EXIT;
6199 sq->end();
6200 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6201 mFastCapture->join();
6202 mFastCapture.clear();
6203 }
6204 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006205 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006206 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006207}
6208
6209void AudioFlinger::RecordThread::onFirstRef()
6210{
Glenn Kastend7dca052015-03-05 16:05:54 -08006211 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006212}
6213
Eric Laurent555530a2017-02-07 18:17:24 -08006214void AudioFlinger::RecordThread::preExit()
6215{
6216 ALOGV(" preExit()");
6217 Mutex::Autolock _l(mLock);
6218 for (size_t i = 0; i < mTracks.size(); i++) {
6219 sp<RecordTrack> track = mTracks[i];
6220 track->invalidate();
6221 }
6222 mActiveTracks.clear();
6223 mStartStopCond.broadcast();
6224}
6225
Eric Laurent81784c32012-11-19 14:55:58 -08006226bool AudioFlinger::RecordThread::threadLoop()
6227{
Eric Laurent81784c32012-11-19 14:55:58 -08006228 nsecs_t lastWarning = 0;
6229
6230 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006231
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006232reacquire_wakelock:
6233 sp<RecordTrack> activeTrack;
6234 {
6235 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006236 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006237 }
6238
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006239 // used to request a deferred sleep, to be executed later while mutex is unlocked
6240 uint32_t sleepUs = 0;
6241
6242 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006243 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006244 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006245
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006246 // activeTracks accumulates a copy of a subset of mActiveTracks
6247 Vector< sp<RecordTrack> > activeTracks;
6248
Glenn Kasten735f45f2014-08-18 15:51:59 -07006249 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006250 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006251
Glenn Kasten735f45f2014-08-18 15:51:59 -07006252 // reference to a fast track which is about to be removed
6253 sp<RecordTrack> fastTrackToRemove;
6254
Eric Laurent81784c32012-11-19 14:55:58 -08006255 { // scope for mLock
6256 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006257
Eric Laurent021cf962014-05-13 10:18:14 -07006258 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006259
Eric Laurent000a4192014-01-29 15:17:32 -08006260 // check exitPending here because checkForNewParameters_l() and
6261 // checkForNewParameters_l() can temporarily release mLock
6262 if (exitPending()) {
6263 break;
6264 }
6265
Eric Laurent5c25d562016-07-13 17:17:45 -07006266 // sleep with mutex unlocked
6267 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006268 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006269 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6270 ATRACE_END();
6271 sleepUs = 0;
6272 continue;
6273 }
6274
Glenn Kasten2b806402013-11-20 16:37:38 -08006275 // if no active track(s), then standby and release wakelock
6276 size_t size = mActiveTracks.size();
6277 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006278 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006279 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006280 releaseWakeLock_l();
6281 ALOGV("RecordThread: loop stopping");
6282 // go to sleep
6283 mWaitWorkCV.wait(mLock);
6284 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006285 goto reacquire_wakelock;
6286 }
6287
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006288 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006289 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006290 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006291
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006292 activeTrack = mActiveTracks[i];
6293 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006294 if (activeTrack->isFastTrack()) {
6295 ALOG_ASSERT(fastTrackToRemove == 0);
6296 fastTrackToRemove = activeTrack;
6297 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006298 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006299 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006300 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006301 continue;
6302 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006303
6304 TrackBase::track_state activeTrackState = activeTrack->mState;
6305 switch (activeTrackState) {
6306
6307 case TrackBase::PAUSING:
6308 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006309 doBroadcast = true;
6310 size--;
6311 continue;
6312
6313 case TrackBase::STARTING_1:
6314 sleepUs = 10000;
6315 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006316 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006317 continue;
6318
6319 case TrackBase::STARTING_2:
6320 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006321 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006322 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006323 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006324 break;
6325
6326 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006327 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006328 break;
6329
6330 case TrackBase::IDLE:
6331 i++;
6332 continue;
6333
6334 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006335 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006336 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006337
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006338 activeTracks.add(activeTrack);
6339 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006340
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006341 if (activeTrack->isFastTrack()) {
6342 ALOG_ASSERT(!mFastTrackAvail);
6343 ALOG_ASSERT(fastTrack == 0);
6344 fastTrack = activeTrack;
6345 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006346 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006347
Andy Hungdae27702016-10-31 14:01:16 -07006348 mActiveTracks.updatePowerState(this);
6349
Eric Laurent5c25d562016-07-13 17:17:45 -07006350 if (allStopped) {
6351 standbyIfNotAlreadyInStandby();
6352 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006353 if (doBroadcast) {
6354 mStartStopCond.broadcast();
6355 }
6356
6357 // sleep if there are no active tracks to process
6358 if (activeTracks.size() == 0) {
6359 if (sleepUs == 0) {
6360 sleepUs = kRecordThreadSleepUs;
6361 }
6362 continue;
6363 }
6364 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006365
Eric Laurent81784c32012-11-19 14:55:58 -08006366 lockEffectChains_l(effectChains);
6367 }
6368
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006369 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006370
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006371 size_t size = effectChains.size();
6372 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006373 // thread mutex is not locked, but effect chain is locked
6374 effectChains[i]->process_l();
6375 }
6376
Glenn Kasten735f45f2014-08-18 15:51:59 -07006377 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006378 if (mFastCapture != 0) {
6379 FastCaptureStateQueue *sq = mFastCapture->sq();
6380 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006381 bool didModify = false;
6382 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006383 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6384 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6385 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6386 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6387 if (old == -1) {
6388 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6389 }
6390 }
6391 state->mCommand = FastCaptureState::READ_WRITE;
6392#if 0 // FIXME
6393 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006394 FastThreadDumpState::kSamplingNforLowRamDevice :
6395 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006396#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006397 didModify = true;
6398 }
6399 audio_track_cblk_t *cblkOld = state->mCblk;
6400 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6401 if (cblkNew != cblkOld) {
6402 state->mCblk = cblkNew;
6403 // block until acked if removing a fast track
6404 if (cblkOld != NULL) {
6405 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6406 }
6407 didModify = true;
6408 }
6409 sq->end(didModify);
6410 if (didModify) {
6411 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006412#if 0
6413 if (kUseFastCapture == FastCapture_Dynamic) {
6414 mNormalSource = mPipeSource;
6415 }
6416#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006417 }
6418 }
6419
Glenn Kasten735f45f2014-08-18 15:51:59 -07006420 // now run the fast track destructor with thread mutex unlocked
6421 fastTrackToRemove.clear();
6422
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006423 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6424 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6425 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6426 // If destination is non-contiguous, first read past the nominal end of buffer, then
6427 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006428
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006429 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006430 ssize_t framesRead;
6431
6432 // If an NBAIO source is present, use it to read the normal capture's data
6433 if (mPipeSource != 0) {
6434 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006435 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006436 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006437 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006438 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6439 // buffer size or at least for 20ms.
6440 size_t sleepFrames = max(
6441 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6442 if (framesRead <= (ssize_t) sleepFrames) {
6443 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6444 }
6445 if (framesRead < 0) {
6446 status_t status = (status_t) framesRead;
6447 switch (status) {
6448 case OVERRUN:
6449 ALOGW("overrun on read from pipe");
6450 framesRead = 0;
6451 break;
6452 case NEGOTIATE:
6453 ALOGE("re-negotiation is needed");
6454 framesRead = -1; // Will cause an attempt to recover.
6455 break;
6456 default:
6457 ALOGE("unknown error %d on read from pipe", status);
6458 break;
6459 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006460 }
6461 // otherwise use the HAL / AudioStreamIn directly
6462 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006463 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006464 size_t bytesRead;
6465 status_t result = mInput->stream->read(
6466 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006467 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006468 if (result < 0) {
6469 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006470 } else {
6471 framesRead = bytesRead / mFrameSize;
6472 }
6473 }
6474
Andy Hung3f0c9022016-01-15 17:49:46 -08006475 // Update server timestamp with server stats
6476 // systemTime() is optional if the hardware supports timestamps.
6477 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6478 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6479
6480 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006481 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006482 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006483 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006484 if (ret == NO_ERROR) {
6485 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6486 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6487 // Note: In general record buffers should tend to be empty in
6488 // a properly running pipeline.
6489 //
6490 // Also, it is not advantageous to call get_presentation_position during the read
6491 // as the read obtains a lock, preventing the timestamp call from executing.
6492 }
6493 }
6494 // Use this to track timestamp information
6495 // ALOGD("%s", mTimestamp.toString().c_str());
6496
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006497 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006498 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006499 // Force input into standby so that it tries to recover at next read attempt
6500 inputStandBy();
6501 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006502 }
6503 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006504 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006505 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006506 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006507
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006508 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006509 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006510 }
6511 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006512 {
6513 size_t part1 = mRsmpInFramesP2 - rear;
6514 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006515 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006516 (framesRead - part1) * mFrameSize);
6517 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006518 }
6519 rear = mRsmpInRear += framesRead;
6520
6521 size = activeTracks.size();
6522 // loop over each active track
6523 for (size_t i = 0; i < size; i++) {
6524 activeTrack = activeTracks[i];
6525
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006526 // skip fast tracks, as those are handled directly by FastCapture
6527 if (activeTrack->isFastTrack()) {
6528 continue;
6529 }
6530
Andy Hung73c02e42015-03-29 01:13:58 -07006531 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006532 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6533
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006534 enum {
6535 OVERRUN_UNKNOWN,
6536 OVERRUN_TRUE,
6537 OVERRUN_FALSE
6538 } overrun = OVERRUN_UNKNOWN;
6539
6540 // loop over getNextBuffer to handle circular sink
6541 for (;;) {
6542
6543 activeTrack->mSink.frameCount = ~0;
6544 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6545 size_t framesOut = activeTrack->mSink.frameCount;
6546 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6547
Andy Hung73c02e42015-03-29 01:13:58 -07006548 // check available frames and handle overrun conditions
6549 // if the record track isn't draining fast enough.
6550 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006551 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006552 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6553 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006554 overrun = OVERRUN_TRUE;
6555 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006556 if (framesOut == 0 || framesIn == 0) {
6557 break;
6558 }
6559
Andy Hung6770c6f2015-04-07 13:43:36 -07006560 // Don't allow framesOut to be larger than what is possible with resampling
6561 // from framesIn.
6562 // This isn't strictly necessary but helps limit buffer resizing in
6563 // RecordBufferConverter. TODO: remove when no longer needed.
6564 framesOut = min(framesOut,
6565 destinationFramesPossible(
6566 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006567 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6568 framesOut = activeTrack->mRecordBufferConverter->convert(
6569 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006570
6571 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6572 overrun = OVERRUN_FALSE;
6573 }
6574
6575 if (activeTrack->mFramesToDrop == 0) {
6576 if (framesOut > 0) {
6577 activeTrack->mSink.frameCount = framesOut;
6578 activeTrack->releaseBuffer(&activeTrack->mSink);
6579 }
6580 } else {
6581 // FIXME could do a partial drop of framesOut
6582 if (activeTrack->mFramesToDrop > 0) {
6583 activeTrack->mFramesToDrop -= framesOut;
6584 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006585 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006586 }
6587 } else {
6588 activeTrack->mFramesToDrop += framesOut;
6589 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6590 activeTrack->mSyncStartEvent->isCancelled()) {
6591 ALOGW("Synced record %s, session %d, trigger session %d",
6592 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6593 activeTrack->sessionId(),
6594 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006595 activeTrack->mSyncStartEvent->triggerSession() :
6596 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006597 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006598 }
6599 }
6600 }
6601
6602 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006603 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006604 }
6605 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006606
6607 switch (overrun) {
6608 case OVERRUN_TRUE:
6609 // client isn't retrieving buffers fast enough
6610 if (!activeTrack->setOverflow()) {
6611 nsecs_t now = systemTime();
6612 // FIXME should lastWarning per track?
6613 if ((now - lastWarning) > kWarningThrottleNs) {
6614 ALOGW("RecordThread: buffer overflow");
6615 lastWarning = now;
6616 }
6617 }
6618 break;
6619 case OVERRUN_FALSE:
6620 activeTrack->clearOverflow();
6621 break;
6622 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006623 break;
6624 }
6625
Andy Hung3f0c9022016-01-15 17:49:46 -08006626 // update frame information and push timestamp out
6627 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006628 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006629 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6630 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006631 }
6632
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006633unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006634 // enable changes in effect chain
6635 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006636 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006637 }
6638
Glenn Kasten93e471f2013-08-19 08:40:07 -07006639 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006640
6641 {
6642 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006643 for (size_t i = 0; i < mTracks.size(); i++) {
6644 sp<RecordTrack> track = mTracks[i];
6645 track->invalidate();
6646 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006647 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006648 mStartStopCond.broadcast();
6649 }
6650
6651 releaseWakeLock();
6652
6653 ALOGV("RecordThread %p exiting", this);
6654 return false;
6655}
6656
Glenn Kasten93e471f2013-08-19 08:40:07 -07006657void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006658{
6659 if (!mStandby) {
6660 inputStandBy();
6661 mStandby = true;
6662 }
6663}
6664
6665void AudioFlinger::RecordThread::inputStandBy()
6666{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006667 // Idle the fast capture if it's currently running
6668 if (mFastCapture != 0) {
6669 FastCaptureStateQueue *sq = mFastCapture->sq();
6670 FastCaptureState *state = sq->begin();
6671 if (!(state->mCommand & FastCaptureState::IDLE)) {
6672 state->mCommand = FastCaptureState::COLD_IDLE;
6673 state->mColdFutexAddr = &mFastCaptureFutex;
6674 state->mColdGen++;
6675 mFastCaptureFutex = 0;
6676 sq->end();
6677 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6678 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6679#if 0
6680 if (kUseFastCapture == FastCapture_Dynamic) {
6681 // FIXME
6682 }
6683#endif
6684#ifdef AUDIO_WATCHDOG
6685 // FIXME
6686#endif
6687 } else {
6688 sq->end(false /*didModify*/);
6689 }
6690 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006691 status_t result = mInput->stream->standby();
6692 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006693
6694 // If going into standby, flush the pipe source.
6695 if (mPipeSource.get() != nullptr) {
6696 const ssize_t flushed = mPipeSource->flush();
6697 if (flushed > 0) {
6698 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6699 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6700 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6701 }
6702 }
Eric Laurent81784c32012-11-19 14:55:58 -08006703}
6704
Glenn Kasten05997e22014-03-13 15:08:33 -07006705// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006706sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006707 const sp<AudioFlinger::Client>& client,
6708 uint32_t sampleRate,
6709 audio_format_t format,
6710 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006711 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006712 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006713 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006714 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006715 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006716 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006717 status_t *status,
6718 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006719{
Glenn Kasten74935e42013-12-19 08:56:45 -08006720 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006721 sp<RecordTrack> track;
6722 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006723 audio_input_flags_t inputFlags = mInput->flags;
6724
6725 // special case for FAST flag considered OK if fast capture is present
6726 if (hasFastCapture()) {
6727 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6728 }
6729
6730 // Check if requested flags are compatible with output stream flags
6731 if ((*flags & inputFlags) != *flags) {
6732 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6733 " input flags (%08x)",
6734 *flags, inputFlags);
6735 *flags = (audio_input_flags_t)(*flags & inputFlags);
6736 }
Eric Laurent81784c32012-11-19 14:55:58 -08006737
Glenn Kasten90e58b12013-07-31 16:16:02 -07006738 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006739 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006740 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006741 // we formerly checked for a callback handler (non-0 tid),
6742 // but that is no longer required for TRANSFER_OBTAIN mode
6743 //
Glenn Kasten74105912014-07-03 12:28:53 -07006744 // frame count is not specified, or is exactly the pipe depth
6745 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006746 // PCM data
6747 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006748 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006749 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006750 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006751 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006752 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006753 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006754 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006755 hasFastCapture() &&
6756 // there are sufficient fast track slots available
6757 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006758 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006759 // check compatibility with audio effects.
6760 Mutex::Autolock _l(mLock);
6761 // Do not accept FAST flag if the session has software effects
6762 sp<EffectChain> chain = getEffectChain_l(sessionId);
6763 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006764 audio_input_flags_t old = *flags;
6765 chain->checkInputFlagCompatibility(flags);
6766 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006767 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6768 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006769 }
6770 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006771 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006772 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6773 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006774 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006775 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6776 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006777 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006778 this, frameCount, mFrameCount, mPipeFramesP2,
6779 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006780 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006781 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006782 }
6783 }
6784
6785 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006786 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006787 // fast track: frame count is exactly the pipe depth
6788 frameCount = mPipeFramesP2;
6789 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6790 *notificationFrames = mFrameCount;
6791 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006792 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6793 // or 20 ms if there is a fast capture
6794 // TODO This could be a roundupRatio inline, and const
6795 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6796 * sampleRate + mSampleRate - 1) / mSampleRate;
6797 // minimum number of notification periods is at least kMinNotifications,
6798 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6799 static const size_t kMinNotifications = 3;
6800 static const uint32_t kMinMs = 30;
6801 // TODO This could be a roundupRatio inline
6802 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6803 // TODO This could be a roundupRatio inline
6804 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6805 maxNotificationFrames;
6806 const size_t minFrameCount = maxNotificationFrames *
6807 max(kMinNotifications, minNotificationsByMs);
6808 frameCount = max(frameCount, minFrameCount);
6809 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6810 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006811 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006812 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006813 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006814
Glenn Kasten15e57982013-09-24 11:52:37 -07006815 lStatus = initCheck();
6816 if (lStatus != NO_ERROR) {
6817 ALOGE("createRecordTrack_l() audio driver not initialized");
6818 goto Exit;
6819 }
Eric Laurent81784c32012-11-19 14:55:58 -08006820
6821 { // scope for mLock
6822 Mutex::Autolock _l(mLock);
6823
6824 track = new RecordTrack(this, client, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07006825 format, channelMask, frameCount,
6826 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006827 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006828
Glenn Kasten03003332013-08-06 15:40:54 -07006829 lStatus = track->initCheck();
6830 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006831 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006832 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006833 goto Exit;
6834 }
6835 mTracks.add(track);
6836
Eric Laurent05067782016-06-01 18:27:28 -07006837 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006838 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6839 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6840 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006841 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006842 }
Eric Laurent81784c32012-11-19 14:55:58 -08006843 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006844
Eric Laurent81784c32012-11-19 14:55:58 -08006845 lStatus = NO_ERROR;
6846
6847Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006848 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006849 return track;
6850}
6851
6852status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6853 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006854 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006855{
6856 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6857 sp<ThreadBase> strongMe = this;
6858 status_t status = NO_ERROR;
6859
6860 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006861 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006862 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006863 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006864 triggerSession,
6865 recordTrack->sessionId(),
6866 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006867 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006868 // Sync event can be cancelled by the trigger session if the track is not in a
6869 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006870 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006871 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006872 } else {
6873 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006874 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006875 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006876 }
6877 }
6878
6879 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006880 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006881 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006882 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6883 if (recordTrack->mState == TrackBase::PAUSING) {
6884 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006885 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006886 } else {
6887 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006888 }
6889 return status;
6890 }
6891
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006892 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6893 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6894 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006895 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006896 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006897 status_t status = NO_ERROR;
6898 if (recordTrack->isExternalTrack()) {
6899 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006900 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006901 mLock.lock();
6902 // FIXME should verify that recordTrack is still in mActiveTracks
6903 if (status != NO_ERROR) {
6904 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006905 recordTrack->clearSyncStartEvent();
6906 ALOGV("RecordThread::start error %d", status);
6907 return status;
6908 }
Eric Laurent81784c32012-11-19 14:55:58 -08006909 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006910 // Catch up with current buffer indices if thread is already running.
6911 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6912 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6913 // see previously buffered data before it called start(), but with greater risk of overrun.
6914
Andy Hung73c02e42015-03-29 01:13:58 -07006915 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006916 // clear any converter state as new data will be discontinuous
6917 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006918 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006919 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006920 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006921 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006922 ALOGV("Record failed to start");
6923 status = BAD_VALUE;
6924 goto startError;
6925 }
Eric Laurent81784c32012-11-19 14:55:58 -08006926 return status;
6927 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006928
Eric Laurent81784c32012-11-19 14:55:58 -08006929startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006930 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006931 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006932 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006933 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006934 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006935 return status;
6936}
6937
Eric Laurent81784c32012-11-19 14:55:58 -08006938void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6939{
6940 sp<SyncEvent> strongEvent = event.promote();
6941
6942 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006943 sp<RefBase> ptr = strongEvent->cookie().promote();
6944 if (ptr != 0) {
6945 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6946 recordTrack->handleSyncStartEvent(strongEvent);
6947 }
Eric Laurent81784c32012-11-19 14:55:58 -08006948 }
6949}
6950
Glenn Kastena8356f62013-07-25 14:37:52 -07006951bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006952 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006953 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006954 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006955 return false;
6956 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006957 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006958 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006959 // signal thread to stop
6960 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006961 // do not wait for mStartStopCond if exiting
6962 if (exitPending()) {
6963 return true;
6964 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006965 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006966 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006967 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006968 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006969 ALOGV("Record stopped OK");
6970 return true;
6971 }
6972 return false;
6973}
6974
Glenn Kasten0f11b512014-01-31 16:18:54 -08006975bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006976{
6977 return false;
6978}
6979
Glenn Kasten0f11b512014-01-31 16:18:54 -08006980status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006981{
6982#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6983 if (!isValidSyncEvent(event)) {
6984 return BAD_VALUE;
6985 }
6986
Glenn Kastend848eb42016-03-08 13:42:11 -08006987 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006988 status_t ret = NAME_NOT_FOUND;
6989
6990 Mutex::Autolock _l(mLock);
6991
6992 for (size_t i = 0; i < mTracks.size(); i++) {
6993 sp<RecordTrack> track = mTracks[i];
6994 if (eventSession == track->sessionId()) {
6995 (void) track->setSyncEvent(event);
6996 ret = NO_ERROR;
6997 }
6998 }
6999 return ret;
7000#else
7001 return BAD_VALUE;
7002#endif
7003}
7004
7005// destroyTrack_l() must be called with ThreadBase::mLock held
7006void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7007{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007008 track->terminate();
7009 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007010 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007011 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007012 removeTrack_l(track);
7013 }
7014}
7015
7016void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7017{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007018 String8 result;
7019 track->appendDump(result, false /* active */);
7020 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7021
Eric Laurent81784c32012-11-19 14:55:58 -08007022 mTracks.remove(track);
7023 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007024 if (track->isFastTrack()) {
7025 ALOG_ASSERT(!mFastTrackAvail);
7026 mFastTrackAvail = true;
7027 }
Eric Laurent81784c32012-11-19 14:55:58 -08007028}
7029
7030void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7031{
7032 dumpInternals(fd, args);
7033 dumpTracks(fd, args);
7034 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007035 dprintf(fd, " Local log:\n");
7036 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007037}
7038
7039void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7040{
Glenn Kasten44182c22015-03-05 17:12:23 -08007041 dumpBase(fd, args);
7042
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007043 AudioStreamIn *input = mInput;
7044 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7045 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7046 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007047 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007048 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007049 }
Andy Hungbfa64962017-06-12 14:43:19 -07007050
7051 if (input != nullptr) {
7052 dprintf(fd, " Hal stream dump:\n");
7053 (void)input->stream->dump(fd);
7054 }
7055
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007056 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007057 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007058
Glenn Kasten2f90c512015-12-02 11:40:09 -08007059 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7060 // while we are dumping it. It may be inconsistent, but it won't mutate!
7061 // This is a large object so we place it on the heap.
7062 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7063 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7064 copy->dump(fd);
7065 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007066}
7067
Glenn Kasten0f11b512014-01-31 16:18:54 -08007068void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007069{
Eric Laurent81784c32012-11-19 14:55:58 -08007070 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007071 size_t numtracks = mTracks.size();
7072 size_t numactive = mActiveTracks.size();
7073 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007074 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007075 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007076 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007077 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007078 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08007079 RecordTrack::appendDumpHeader(result);
7080 for (size_t i = 0; i < numtracks ; ++i) {
7081 sp<RecordTrack> track = mTracks[i];
7082 if (track != 0) {
7083 bool active = mActiveTracks.indexOf(track) >= 0;
7084 if (active) {
7085 numactiveseen++;
7086 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007087 result.append(prefix);
7088 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007089 }
Eric Laurent81784c32012-11-19 14:55:58 -08007090 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007091 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007092 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007093 }
7094
Marco Nelissenb2208842014-02-07 14:00:50 -08007095 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007096 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007097 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007098 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08007099 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007100 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007101 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007102 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007103 result.append(prefix);
7104 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007105 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007106 }
Eric Laurent81784c32012-11-19 14:55:58 -08007107
7108 }
7109 write(fd, result.string(), result.size());
7110}
7111
Andy Hung73c02e42015-03-29 01:13:58 -07007112
7113void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7114{
7115 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7116 RecordThread *recordThread = (RecordThread *) threadBase.get();
7117 mRsmpInFront = recordThread->mRsmpInRear;
7118 mRsmpInUnrel = 0;
7119}
7120
7121void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7122 size_t *framesAvailable, bool *hasOverrun)
7123{
7124 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7125 RecordThread *recordThread = (RecordThread *) threadBase.get();
7126 const int32_t rear = recordThread->mRsmpInRear;
7127 const int32_t front = mRsmpInFront;
7128 const ssize_t filled = rear - front;
7129
7130 size_t framesIn;
7131 bool overrun = false;
7132 if (filled < 0) {
7133 // should not happen, but treat like a massive overrun and re-sync
7134 framesIn = 0;
7135 mRsmpInFront = rear;
7136 overrun = true;
7137 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7138 framesIn = (size_t) filled;
7139 } else {
7140 // client is not keeping up with server, but give it latest data
7141 framesIn = recordThread->mRsmpInFrames;
7142 mRsmpInFront = /* front = */ rear - framesIn;
7143 overrun = true;
7144 }
7145 if (framesAvailable != NULL) {
7146 *framesAvailable = framesIn;
7147 }
7148 if (hasOverrun != NULL) {
7149 *hasOverrun = overrun;
7150 }
7151}
7152
Eric Laurent81784c32012-11-19 14:55:58 -08007153// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007154status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007155 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007156{
Andy Hung73c02e42015-03-29 01:13:58 -07007157 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007158 if (threadBase == 0) {
7159 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007160 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007161 return NOT_ENOUGH_DATA;
7162 }
7163 RecordThread *recordThread = (RecordThread *) threadBase.get();
7164 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007165 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007166 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007167 // FIXME should not be P2 (don't want to increase latency)
7168 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007169 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007170 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007171 front &= recordThread->mRsmpInFramesP2 - 1;
7172 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007173 if (part1 > (size_t) filled) {
7174 part1 = filled;
7175 }
7176 size_t ask = buffer->frameCount;
7177 ALOG_ASSERT(ask > 0);
7178 if (part1 > ask) {
7179 part1 = ask;
7180 }
7181 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007182 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007183 buffer->raw = NULL;
7184 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007185 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007186 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007187 }
7188
Andy Hung57446612015-04-19 23:56:46 -07007189 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007190 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007191 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007192 return NO_ERROR;
7193}
7194
7195// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007196void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7197 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007198{
Glenn Kasten85948432013-08-19 12:09:05 -07007199 size_t stepCount = buffer->frameCount;
7200 if (stepCount == 0) {
7201 return;
7202 }
Andy Hung73c02e42015-03-29 01:13:58 -07007203 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7204 mRsmpInUnrel -= stepCount;
7205 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007206 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007207 buffer->frameCount = 0;
7208}
7209
Eric Laurentd8365c52017-07-16 15:27:05 -07007210void AudioFlinger::RecordThread::checkBtNrec()
7211{
7212 Mutex::Autolock _l(mLock);
7213 checkBtNrec_l();
7214}
7215
7216void AudioFlinger::RecordThread::checkBtNrec_l()
7217{
7218 // disable AEC and NS if the device is a BT SCO headset supporting those
7219 // pre processings
7220 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7221 mAudioFlinger->btNrecIsOff();
7222 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7223 for (size_t i = 0; i < mEffectChains.size(); i++) {
7224 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7225 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7226 }
7227 }
7228}
7229
Andy Hung97a893e2015-03-29 01:03:07 -07007230
Eric Laurent10351942014-05-08 18:49:52 -07007231bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7232 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007233{
7234 bool reconfig = false;
7235
Eric Laurent10351942014-05-08 18:49:52 -07007236 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007237
Eric Laurent10351942014-05-08 18:49:52 -07007238 audio_format_t reqFormat = mFormat;
7239 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007240 // 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 -07007241 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7242
7243 AudioParameter param = AudioParameter(keyValuePair);
7244 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007245
7246 // scope for AutoPark extends to end of method
7247 AutoPark<FastCapture> park(mFastCapture);
7248
Eric Laurent10351942014-05-08 18:49:52 -07007249 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7250 // channel count change can be requested. Do we mandate the first client defines the
7251 // HAL sampling rate and channel count or do we allow changes on the fly?
7252 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7253 samplingRate = value;
7254 reconfig = true;
7255 }
7256 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007257 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007258 status = BAD_VALUE;
7259 } else {
7260 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007261 reconfig = true;
7262 }
Eric Laurent10351942014-05-08 18:49:52 -07007263 }
7264 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7265 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007266 if (!audio_is_input_channel(mask) ||
7267 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007268 status = BAD_VALUE;
7269 } else {
7270 channelMask = mask;
7271 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007272 }
Eric Laurent10351942014-05-08 18:49:52 -07007273 }
7274 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7275 // do not accept frame count changes if tracks are open as the track buffer
7276 // size depends on frame count and correct behavior would not be guaranteed
7277 // if frame count is changed after track creation
7278 if (mActiveTracks.size() > 0) {
7279 status = INVALID_OPERATION;
7280 } else {
7281 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007282 }
Eric Laurent10351942014-05-08 18:49:52 -07007283 }
7284 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7285 // forward device change to effects that have requested to be
7286 // aware of attached audio device.
7287 for (size_t i = 0; i < mEffectChains.size(); i++) {
7288 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007289 }
Eric Laurent81784c32012-11-19 14:55:58 -08007290
Eric Laurent10351942014-05-08 18:49:52 -07007291 // store input device and output device but do not forward output device to audio HAL.
7292 // Note that status is ignored by the caller for output device
7293 // (see AudioFlinger::setParameters()
7294 if (audio_is_output_devices(value)) {
7295 mOutDevice = value;
7296 status = BAD_VALUE;
7297 } else {
7298 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007299 if (value != AUDIO_DEVICE_NONE) {
7300 mPrevInDevice = value;
7301 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007302 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007303 }
Eric Laurent10351942014-05-08 18:49:52 -07007304 }
7305 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7306 mAudioSource != (audio_source_t)value) {
7307 // forward device change to effects that have requested to be
7308 // aware of attached audio device.
7309 for (size_t i = 0; i < mEffectChains.size(); i++) {
7310 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007311 }
Eric Laurent10351942014-05-08 18:49:52 -07007312 mAudioSource = (audio_source_t)value;
7313 }
Glenn Kastene198c362013-08-13 09:13:36 -07007314
Eric Laurent10351942014-05-08 18:49:52 -07007315 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007316 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007317 if (status == INVALID_OPERATION) {
7318 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007319 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007320 }
7321 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007322 if (status == BAD_VALUE) {
7323 uint32_t sRate;
7324 audio_channel_mask_t channelMask;
7325 audio_format_t format;
7326 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7327 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7328 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7329 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7330 status = NO_ERROR;
7331 }
Eric Laurent81784c32012-11-19 14:55:58 -08007332 }
Eric Laurent10351942014-05-08 18:49:52 -07007333 if (status == NO_ERROR) {
7334 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007335 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007336 }
7337 }
Eric Laurent81784c32012-11-19 14:55:58 -08007338 }
Eric Laurent10351942014-05-08 18:49:52 -07007339
Eric Laurent81784c32012-11-19 14:55:58 -08007340 return reconfig;
7341}
7342
7343String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7344{
Eric Laurent81784c32012-11-19 14:55:58 -08007345 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007346 if (initCheck() == NO_ERROR) {
7347 String8 out_s8;
7348 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7349 return out_s8;
7350 }
Eric Laurent81784c32012-11-19 14:55:58 -08007351 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007352 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007353}
7354
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007355void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007356 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7357
7358 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007359
7360 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007361 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007362 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007363 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007364 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007365 desc->mChannelMask = mChannelMask;
7366 desc->mSamplingRate = mSampleRate;
7367 desc->mFormat = mFormat;
7368 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007369 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007370 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007371 break;
7372
Eric Laurent73e26b62015-04-27 16:55:58 -07007373 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007374 default:
7375 break;
7376 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007377 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007378}
7379
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007380void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007381{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007382 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7383 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007384 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007385 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007386 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007387 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7388 result = mInput->stream->getFrameSize(&mFrameSize);
7389 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7390 result = mInput->stream->getBufferSize(&mBufferSize);
7391 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007392 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007393 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7394 "mBufferSize=%lld, mFrameCount=%lld",
7395 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7396 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007397 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007398 // 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 -07007399 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007400 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007401 // A larger value should allow more old data to be read after a track calls start(),
7402 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007403 //
7404 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007405 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007406 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007407 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007408 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007409
7410 // TODO optimize audio capture buffer sizes ...
7411 // Here we calculate the size of the sliding buffer used as a source
7412 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7413 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7414 // be better to have it derived from the pipe depth in the long term.
7415 // The current value is higher than necessary. However it should not add to latency.
7416
Glenn Kasten85948432013-08-19 12:09:05 -07007417 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007418 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7419 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007420 // if posix_memalign fails, will segv here.
7421 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007422
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007423 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7424 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007425}
7426
Glenn Kasten5f972c02014-01-13 09:59:31 -08007427uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007428{
7429 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007430 uint32_t result;
7431 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7432 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007433 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007434 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007435}
7436
Eric Laurent4c415062016-06-17 16:14:16 -07007437// hasAudioSession_l() must be called with ThreadBase::mLock held
7438uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007439{
Eric Laurent81784c32012-11-19 14:55:58 -08007440 uint32_t result = 0;
7441 if (getEffectChain_l(sessionId) != 0) {
7442 result = EFFECT_SESSION;
7443 }
7444
7445 for (size_t i = 0; i < mTracks.size(); ++i) {
7446 if (sessionId == mTracks[i]->sessionId()) {
7447 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007448 if (mTracks[i]->isFastTrack()) {
7449 result |= FAST_SESSION;
7450 }
Eric Laurent81784c32012-11-19 14:55:58 -08007451 break;
7452 }
7453 }
7454
7455 return result;
7456}
7457
Glenn Kastend848eb42016-03-08 13:42:11 -08007458KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007459{
Glenn Kastend848eb42016-03-08 13:42:11 -08007460 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007461 Mutex::Autolock _l(mLock);
7462 for (size_t j = 0; j < mTracks.size(); ++j) {
7463 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007464 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007465 if (ids.indexOfKey(sessionId) < 0) {
7466 ids.add(sessionId, true);
7467 }
7468 }
7469 return ids;
7470}
7471
7472AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7473{
7474 Mutex::Autolock _l(mLock);
7475 AudioStreamIn *input = mInput;
7476 mInput = NULL;
7477 return input;
7478}
7479
7480// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007481sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007482{
7483 if (mInput == NULL) {
7484 return NULL;
7485 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007486 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007487}
7488
7489status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7490{
7491 // only one chain per input thread
7492 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007493 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007494 return INVALID_OPERATION;
7495 }
7496 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007497 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007498 chain->setInBuffer(NULL);
7499 chain->setOutBuffer(NULL);
7500
7501 checkSuspendOnAddEffectChain_l(chain);
7502
Eric Laurent1b928682014-10-02 19:41:47 -07007503 // make sure enabled pre processing effects state is communicated to the HAL as we
7504 // just moved them to a new input stream.
7505 chain->syncHalEffectsState();
7506
Eric Laurent81784c32012-11-19 14:55:58 -08007507 mEffectChains.add(chain);
7508
7509 return NO_ERROR;
7510}
7511
7512size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7513{
7514 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7515 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007516 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007517 chain.get(), mEffectChains.size(), this);
7518 if (mEffectChains.size() == 1) {
7519 mEffectChains.removeAt(0);
7520 }
7521 return 0;
7522}
7523
Eric Laurent1c333e22014-05-20 10:48:17 -07007524status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7525 audio_patch_handle_t *handle)
7526{
7527 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007528
7529 // store new device and send to effects
7530 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007531 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007532 for (size_t i = 0; i < mEffectChains.size(); i++) {
7533 mEffectChains[i]->setDevice_l(mInDevice);
7534 }
7535
Eric Laurentd8365c52017-07-16 15:27:05 -07007536 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007537
7538 // store new source and send to effects
7539 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7540 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007541 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007542 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007543 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007544 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007545
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007546 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007547 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7548 status = hwDevice->createAudioPatch(patch->num_sources,
7549 patch->sources,
7550 patch->num_sinks,
7551 patch->sinks,
7552 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007553 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007554 char *address;
7555 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7556 address = audio_device_address_to_parameter(
7557 patch->sources[0].ext.device.type,
7558 patch->sources[0].ext.device.address);
7559 } else {
7560 address = (char *)calloc(1, 1);
7561 }
7562 AudioParameter param = AudioParameter(String8(address));
7563 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007564 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007565 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007566 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007567 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007568 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007569 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007570 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007571
Eric Laurente8726fe2015-06-26 09:39:24 -07007572 if (mInDevice != mPrevInDevice) {
7573 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7574 mPrevInDevice = mInDevice;
7575 }
Eric Laurent296fb132015-05-01 11:38:42 -07007576
Eric Laurent1c333e22014-05-20 10:48:17 -07007577 return status;
7578}
7579
7580status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7581{
7582 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007583
7584 mInDevice = AUDIO_DEVICE_NONE;
7585
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007586 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007587 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7588 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007589 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007590 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007591 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007592 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007593 }
7594 return status;
7595}
7596
Eric Laurent83b88082014-06-20 18:31:16 -07007597void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7598{
7599 Mutex::Autolock _l(mLock);
7600 mTracks.add(record);
7601}
7602
7603void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7604{
7605 Mutex::Autolock _l(mLock);
7606 destroyTrack_l(record);
7607}
7608
7609void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7610{
7611 ThreadBase::getAudioPortConfig(config);
7612 config->role = AUDIO_PORT_ROLE_SINK;
7613 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7614 config->ext.mix.usecase.source = mAudioSource;
7615}
Eric Laurent1c333e22014-05-20 10:48:17 -07007616
Eric Laurent6acd1d42017-01-04 14:23:29 -08007617// ----------------------------------------------------------------------------
7618// Mmap
7619// ----------------------------------------------------------------------------
7620
7621AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7622 : mThread(thread)
7623{
Phil Burk9fabbf82017-08-03 12:02:00 -07007624 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007625}
7626
7627AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7628{
Phil Burk9fabbf82017-08-03 12:02:00 -07007629 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007630}
7631
7632status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7633 struct audio_mmap_buffer_info *info)
7634{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007635 return mThread->createMmapBuffer(minSizeFrames, info);
7636}
7637
7638status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7639{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007640 return mThread->getMmapPosition(position);
7641}
7642
Eric Laurenta54f1282017-07-01 19:39:32 -07007643status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007644 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007645
7646{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007647 return mThread->start(client, handle);
7648}
7649
7650status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7651{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007652 return mThread->stop(handle);
7653}
7654
Eric Laurent18b57012017-02-13 16:23:52 -08007655status_t AudioFlinger::MmapThreadHandle::standby()
7656{
Eric Laurent18b57012017-02-13 16:23:52 -08007657 return mThread->standby();
7658}
7659
Eric Laurent6acd1d42017-01-04 14:23:29 -08007660
7661AudioFlinger::MmapThread::MmapThread(
7662 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7663 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7664 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7665 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007666 mSessionId(AUDIO_SESSION_NONE),
7667 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007668 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
7669 mActiveTracks(&this->mLocalLog)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007670{
Eric Laurent18b57012017-02-13 16:23:52 -08007671 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007672 readHalParameters_l();
7673}
7674
7675AudioFlinger::MmapThread::~MmapThread()
7676{
Eric Laurent18b57012017-02-13 16:23:52 -08007677 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007678}
7679
7680void AudioFlinger::MmapThread::onFirstRef()
7681{
7682 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7683}
7684
7685void AudioFlinger::MmapThread::disconnect()
7686{
7687 for (const sp<MmapTrack> &t : mActiveTracks) {
7688 stop(t->portId());
7689 }
Phil Burk9fabbf82017-08-03 12:02:00 -07007690 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08007691 if (isOutput()) {
7692 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7693 } else {
7694 AudioSystem::releaseInput(mId, mSessionId);
7695 }
7696}
7697
7698
7699void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7700 audio_stream_type_t streamType __unused,
7701 audio_session_t sessionId,
7702 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007703 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007704 audio_port_handle_t portId)
7705{
7706 mAttr = *attr;
7707 mSessionId = sessionId;
7708 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007709 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007710 mPortId = portId;
7711}
7712
7713status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7714 struct audio_mmap_buffer_info *info)
7715{
7716 if (mHalStream == 0) {
7717 return NO_INIT;
7718 }
Eric Laurent18b57012017-02-13 16:23:52 -08007719 mStandby = true;
7720 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007721 return mHalStream->createMmapBuffer(minSizeFrames, info);
7722}
7723
7724status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7725{
7726 if (mHalStream == 0) {
7727 return NO_INIT;
7728 }
7729 return mHalStream->getMmapPosition(position);
7730}
7731
Eric Laurenta54f1282017-07-01 19:39:32 -07007732status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007733 audio_port_handle_t *handle)
7734{
Eric Laurenta54f1282017-07-01 19:39:32 -07007735 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7736 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007737 if (mHalStream == 0) {
7738 return NO_INIT;
7739 }
7740
7741 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007742
Eric Laurenta54f1282017-07-01 19:39:32 -07007743 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007744 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007745 ret = mHalStream->start();
7746 if (ret != NO_ERROR) {
7747 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7748 return ret;
7749 }
Eric Laurent18b57012017-02-13 16:23:52 -08007750 mStandby = false;
Eric Laurenta54f1282017-07-01 19:39:32 -07007751 return NO_ERROR;
7752 }
7753
Phil Burk81ad5ec2017-09-01 10:45:41 -07007754 if (!isOutput() && !recordingAllowed(client.packageName, client.clientPid, client.clientUid)) {
7755 return PERMISSION_DENIED;
7756 }
7757
Eric Laurenta54f1282017-07-01 19:39:32 -07007758 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7759
7760 audio_io_handle_t io = mId;
7761 if (isOutput()) {
7762 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7763 config.sample_rate = mSampleRate;
7764 config.channel_mask = mChannelMask;
7765 config.format = mFormat;
7766 audio_stream_type_t stream = streamType();
7767 audio_output_flags_t flags =
7768 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007769 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007770 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7771 mSessionId,
7772 &stream,
7773 client.clientUid,
7774 &config,
7775 flags,
7776 &deviceId,
7777 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007778 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007779 audio_config_base_t config;
7780 config.sample_rate = mSampleRate;
7781 config.channel_mask = mChannelMask;
7782 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007783 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007784 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7785 mSessionId,
7786 client.clientPid,
7787 client.clientUid,
7788 &config,
7789 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7790 &deviceId,
7791 &portId);
7792 }
7793 // APM should not chose a different input or output stream for the same set of attributes
7794 // and audo configuration
7795 if (ret != NO_ERROR || io != mId) {
7796 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7797 __FUNCTION__, ret, io, mId);
7798 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007799 }
7800
7801 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007802 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007803 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007804 ret = AudioSystem::startInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007805 }
7806
7807 // abort if start is rejected by audio policy manager
7808 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007809 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007810 if (mActiveTracks.size() != 0) {
7811 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007812 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007813 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007814 AudioSystem::releaseInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007815 }
Eric Laurent18b57012017-02-13 16:23:52 -08007816 } else {
7817 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007818 }
7819 return PERMISSION_DENIED;
7820 }
7821
Eric Laurenta54f1282017-07-01 19:39:32 -07007822 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, mSessionId,
7823 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007824
7825 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07007826 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007827 if (chain != 0) {
7828 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7829 chain->incTrackCnt();
7830 chain->incActiveTrackCnt();
7831 }
7832
7833 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007834 broadcast_l();
7835
Eric Laurenta54f1282017-07-01 19:39:32 -07007836 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007837
7838 return NO_ERROR;
7839}
7840
7841status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7842{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007843 ALOGV("%s handle %d", __FUNCTION__, handle);
7844
7845 if (mHalStream == 0) {
7846 return NO_INIT;
7847 }
7848
Eric Laurenta54f1282017-07-01 19:39:32 -07007849 if (handle == mPortId) {
7850 mHalStream->stop();
7851 return NO_ERROR;
7852 }
7853
Eric Laurent6acd1d42017-01-04 14:23:29 -08007854 sp<MmapTrack> track;
7855 for (const sp<MmapTrack> &t : mActiveTracks) {
7856 if (handle == t->portId()) {
7857 track = t;
7858 break;
7859 }
7860 }
7861 if (track == 0) {
7862 return BAD_VALUE;
7863 }
7864
7865 mActiveTracks.remove(track);
7866
7867 if (isOutput()) {
7868 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007869 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007870 } else {
7871 AudioSystem::stopInput(mId, track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007872 AudioSystem::releaseInput(mId, track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007873 }
7874
7875 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7876 if (chain != 0) {
7877 chain->decActiveTrackCnt();
7878 chain->decTrackCnt();
7879 }
7880
7881 broadcast_l();
7882
Eric Laurent6acd1d42017-01-04 14:23:29 -08007883 return NO_ERROR;
7884}
7885
Eric Laurent18b57012017-02-13 16:23:52 -08007886status_t AudioFlinger::MmapThread::standby()
7887{
7888 ALOGV("%s", __FUNCTION__);
7889
7890 if (mHalStream == 0) {
7891 return NO_INIT;
7892 }
7893 if (mActiveTracks.size() != 0) {
7894 return INVALID_OPERATION;
7895 }
7896 mHalStream->standby();
7897 mStandby = true;
7898 releaseWakeLock();
7899 return NO_ERROR;
7900}
7901
Eric Laurent6acd1d42017-01-04 14:23:29 -08007902
7903void AudioFlinger::MmapThread::readHalParameters_l()
7904{
7905 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7906 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7907 mFormat = mHALFormat;
7908 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7909 result = mHalStream->getFrameSize(&mFrameSize);
7910 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7911 result = mHalStream->getBufferSize(&mBufferSize);
7912 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7913 mFrameCount = mBufferSize / mFrameSize;
7914}
7915
7916bool AudioFlinger::MmapThread::threadLoop()
7917{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007918 checkSilentMode_l();
7919
7920 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7921
7922 while (!exitPending())
7923 {
7924 Mutex::Autolock _l(mLock);
7925 Vector< sp<EffectChain> > effectChains;
7926
7927 if (mSignalPending) {
7928 // A signal was raised while we were unlocked
7929 mSignalPending = false;
7930 } else {
7931 if (mConfigEvents.isEmpty()) {
7932 // we're about to wait, flush the binder command buffer
7933 IPCThreadState::self()->flushCommands();
7934
7935 if (exitPending()) {
7936 break;
7937 }
7938
Eric Laurent6acd1d42017-01-04 14:23:29 -08007939 // wait until we have something to do...
7940 ALOGV("%s going to sleep", myName.string());
7941 mWaitWorkCV.wait(mLock);
7942 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007943
7944 checkSilentMode_l();
7945
7946 continue;
7947 }
7948 }
7949
7950 processConfigEvents_l();
7951
7952 processVolume_l();
7953
7954 checkInvalidTracks_l();
7955
7956 mActiveTracks.updatePowerState(this);
7957
7958 lockEffectChains_l(effectChains);
7959 for (size_t i = 0; i < effectChains.size(); i ++) {
7960 effectChains[i]->process_l();
7961 }
7962 // enable changes in effect chain
7963 unlockEffectChains(effectChains);
7964 // Effect chains will be actually deleted here if they were removed from
7965 // mEffectChains list during mixing or effects processing
7966 }
7967
7968 threadLoop_exit();
7969
7970 if (!mStandby) {
7971 threadLoop_standby();
7972 mStandby = true;
7973 }
7974
Eric Laurent6acd1d42017-01-04 14:23:29 -08007975 ALOGV("Thread %p type %d exiting", this, mType);
7976 return false;
7977}
7978
7979// checkForNewParameter_l() must be called with ThreadBase::mLock held
7980bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7981 status_t& status)
7982{
7983 AudioParameter param = AudioParameter(keyValuePair);
7984 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07007985 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007986 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07007987 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007988 // forward device change to effects that have requested to be
7989 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07007990 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007991 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07007992 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007993 }
7994 }
Eric Laurente6e9a482017-07-25 19:26:02 -07007995 if (audio_is_output_devices(device)) {
7996 mOutDevice = device;
7997 if (!isOutput()) {
7998 sendToHal = false;
7999 }
8000 } else {
8001 mInDevice = device;
8002 if (device != AUDIO_DEVICE_NONE) {
8003 mPrevInDevice = value;
8004 }
8005 // TODO: implement and call checkBtNrec_l();
8006 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008007 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008008 if (sendToHal) {
8009 status = mHalStream->setParameters(keyValuePair);
8010 } else {
8011 status = NO_ERROR;
8012 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008013
8014 return false;
8015}
8016
8017String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8018{
8019 Mutex::Autolock _l(mLock);
8020 String8 out_s8;
8021 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8022 return out_s8;
8023 }
8024 return String8();
8025}
8026
8027void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8028 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8029
8030 desc->mIoHandle = mId;
8031
8032 switch (event) {
8033 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008034 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008035 case AUDIO_INPUT_CONFIG_CHANGED:
8036 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008037 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008038 case AUDIO_OUTPUT_CONFIG_CHANGED:
8039 desc->mPatch = mPatch;
8040 desc->mChannelMask = mChannelMask;
8041 desc->mSamplingRate = mSampleRate;
8042 desc->mFormat = mFormat;
8043 desc->mFrameCount = mFrameCount;
8044 desc->mFrameCountHAL = mFrameCount;
8045 desc->mLatency = 0;
8046 break;
8047
8048 case AUDIO_INPUT_CLOSED:
8049 case AUDIO_OUTPUT_CLOSED:
8050 default:
8051 break;
8052 }
8053 mAudioFlinger->ioConfigChanged(event, desc, pid);
8054}
8055
8056status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8057 audio_patch_handle_t *handle)
8058{
8059 status_t status = NO_ERROR;
8060
8061 // store new device and send to effects
8062 audio_devices_t type = AUDIO_DEVICE_NONE;
8063 audio_port_handle_t deviceId;
8064 if (isOutput()) {
8065 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8066 type |= patch->sinks[i].ext.device.type;
8067 }
8068 deviceId = patch->sinks[0].id;
8069 } else {
8070 type = patch->sources[0].ext.device.type;
8071 deviceId = patch->sources[0].id;
8072 }
8073
8074 for (size_t i = 0; i < mEffectChains.size(); i++) {
8075 mEffectChains[i]->setDevice_l(type);
8076 }
8077
8078 if (isOutput()) {
8079 mOutDevice = type;
8080 } else {
8081 mInDevice = type;
8082 // store new source and send to effects
8083 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8084 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8085 for (size_t i = 0; i < mEffectChains.size(); i++) {
8086 mEffectChains[i]->setAudioSource_l(mAudioSource);
8087 }
8088 }
8089 }
8090
8091 if (mAudioHwDev->supportsAudioPatches()) {
8092 status = mHalDevice->createAudioPatch(patch->num_sources,
8093 patch->sources,
8094 patch->num_sinks,
8095 patch->sinks,
8096 handle);
8097 } else {
8098 char *address;
8099 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8100 //FIXME: we only support address on first sink with HAL version < 3.0
8101 address = audio_device_address_to_parameter(
8102 patch->sinks[0].ext.device.type,
8103 patch->sinks[0].ext.device.address);
8104 } else {
8105 address = (char *)calloc(1, 1);
8106 }
8107 AudioParameter param = AudioParameter(String8(address));
8108 free(address);
8109 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8110 if (!isOutput()) {
8111 param.addInt(String8(AudioParameter::keyInputSource),
8112 (int)patch->sinks[0].ext.mix.usecase.source);
8113 }
8114 status = mHalStream->setParameters(param.toString());
8115 *handle = AUDIO_PATCH_HANDLE_NONE;
8116 }
8117
8118 if (isOutput() && mPrevOutDevice != mOutDevice) {
8119 mPrevOutDevice = type;
8120 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008121 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008122 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008123 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008124 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008125 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008126 }
8127 if (!isOutput() && mPrevInDevice != mInDevice) {
8128 mPrevInDevice = type;
8129 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008130 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008131 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008132 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008133 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008134 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008135 }
8136 return status;
8137}
8138
8139status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8140{
8141 status_t status = NO_ERROR;
8142
8143 mInDevice = AUDIO_DEVICE_NONE;
8144
8145 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8146 supportsAudioPatches : false;
8147
8148 if (supportsAudioPatches) {
8149 status = mHalDevice->releaseAudioPatch(handle);
8150 } else {
8151 AudioParameter param;
8152 param.addInt(String8(AudioParameter::keyRouting), 0);
8153 status = mHalStream->setParameters(param.toString());
8154 }
8155 return status;
8156}
8157
8158void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8159{
8160 ThreadBase::getAudioPortConfig(config);
8161 if (isOutput()) {
8162 config->role = AUDIO_PORT_ROLE_SOURCE;
8163 config->ext.mix.hw_module = mAudioHwDev->handle();
8164 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8165 } else {
8166 config->role = AUDIO_PORT_ROLE_SINK;
8167 config->ext.mix.hw_module = mAudioHwDev->handle();
8168 config->ext.mix.usecase.source = mAudioSource;
8169 }
8170}
8171
8172status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8173{
8174 audio_session_t session = chain->sessionId();
8175
8176 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8177 // Attach all tracks with same session ID to this chain.
8178 // indicate all active tracks in the chain
8179 for (const sp<MmapTrack> &track : mActiveTracks) {
8180 if (session == track->sessionId()) {
8181 chain->incTrackCnt();
8182 chain->incActiveTrackCnt();
8183 }
8184 }
8185
8186 chain->setThread(this);
8187 chain->setInBuffer(nullptr);
8188 chain->setOutBuffer(nullptr);
8189 chain->syncHalEffectsState();
8190
8191 mEffectChains.add(chain);
8192 checkSuspendOnAddEffectChain_l(chain);
8193 return NO_ERROR;
8194}
8195
8196size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8197{
8198 audio_session_t session = chain->sessionId();
8199
8200 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8201
8202 for (size_t i = 0; i < mEffectChains.size(); i++) {
8203 if (chain == mEffectChains[i]) {
8204 mEffectChains.removeAt(i);
8205 // detach all active tracks from the chain
8206 // detach all tracks with same session ID from this chain
8207 for (const sp<MmapTrack> &track : mActiveTracks) {
8208 if (session == track->sessionId()) {
8209 chain->decActiveTrackCnt();
8210 chain->decTrackCnt();
8211 }
8212 }
8213 break;
8214 }
8215 }
8216 return mEffectChains.size();
8217}
8218
8219// hasAudioSession_l() must be called with ThreadBase::mLock held
8220uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8221{
8222 uint32_t result = 0;
8223 if (getEffectChain_l(sessionId) != 0) {
8224 result = EFFECT_SESSION;
8225 }
8226
8227 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8228 sp<MmapTrack> track = mActiveTracks[i];
8229 if (sessionId == track->sessionId()) {
8230 result |= TRACK_SESSION;
8231 if (track->isFastTrack()) {
8232 result |= FAST_SESSION;
8233 }
8234 break;
8235 }
8236 }
8237
8238 return result;
8239}
8240
8241void AudioFlinger::MmapThread::threadLoop_standby()
8242{
8243 mHalStream->standby();
8244}
8245
8246void AudioFlinger::MmapThread::threadLoop_exit()
8247{
Phil Burk7dce7282017-09-27 13:51:41 -07008248 // Do not call callback->onTearDown() because it is redundant for thread exit
8249 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008250}
8251
8252status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8253{
8254 return BAD_VALUE;
8255}
8256
8257bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8258{
8259 return false;
8260}
8261
8262status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8263 const effect_descriptor_t *desc, audio_session_t sessionId)
8264{
8265 // No global effect sessions on mmap threads
8266 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8267 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8268 desc->name, mThreadName);
8269 return BAD_VALUE;
8270 }
8271
8272 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8273 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8274 desc->name);
8275 return BAD_VALUE;
8276 }
8277 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008278 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8279 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008280 return BAD_VALUE;
8281 }
8282
8283 // Only allow effects without processing load or latency
8284 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8285 return BAD_VALUE;
8286 }
8287
8288 return NO_ERROR;
8289
8290}
8291
8292void AudioFlinger::MmapThread::checkInvalidTracks_l()
8293{
8294 for (const sp<MmapTrack> &track : mActiveTracks) {
8295 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008296 sp<MmapStreamCallback> callback = mCallback.promote();
8297 if (callback != 0) {
8298 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008299 }
8300 break;
8301 }
8302 }
8303}
8304
8305void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8306{
8307 dumpInternals(fd, args);
8308 dumpTracks(fd, args);
8309 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008310 dprintf(fd, " Local log:\n");
8311 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008312}
8313
8314void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8315{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008316 dumpBase(fd, args);
8317
8318 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8319 mAttr.content_type, mAttr.usage, mAttr.source);
8320 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8321 if (mActiveTracks.size() == 0) {
8322 dprintf(fd, " No active clients\n");
8323 }
8324}
8325
8326void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8327{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008328 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008329 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008330 dprintf(fd, " %zu Tracks\n", numtracks);
8331 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008332 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008333 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008334 MmapTrack::appendDumpHeader(result);
8335 for (size_t i = 0; i < numtracks ; ++i) {
8336 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008337 result.append(prefix);
8338 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008339 }
8340 } else {
8341 dprintf(fd, "\n");
8342 }
8343 write(fd, result.string(), result.size());
8344}
8345
8346AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8347 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8348 AudioHwDevice *hwDev, AudioStreamOut *output,
8349 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8350 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8351 mStreamType(AUDIO_STREAM_MUSIC),
8352 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8353{
8354 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8355 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8356 mMasterVolume = audioFlinger->masterVolume_l();
8357 mMasterMute = audioFlinger->masterMute_l();
8358 if (mAudioHwDev) {
8359 if (mAudioHwDev->canSetMasterVolume()) {
8360 mMasterVolume = 1.0;
8361 }
8362
8363 if (mAudioHwDev->canSetMasterMute()) {
8364 mMasterMute = false;
8365 }
8366 }
8367}
8368
8369void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8370 audio_stream_type_t streamType,
8371 audio_session_t sessionId,
8372 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008373 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008374 audio_port_handle_t portId)
8375{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008376 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008377 mStreamType = streamType;
8378}
8379
8380AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8381{
8382 Mutex::Autolock _l(mLock);
8383 AudioStreamOut *output = mOutput;
8384 mOutput = NULL;
8385 return output;
8386}
8387
8388void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8389{
8390 Mutex::Autolock _l(mLock);
8391 // Don't apply master volume in SW if our HAL can do it for us.
8392 if (mAudioHwDev &&
8393 mAudioHwDev->canSetMasterVolume()) {
8394 mMasterVolume = 1.0;
8395 } else {
8396 mMasterVolume = value;
8397 }
8398}
8399
8400void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8401{
8402 Mutex::Autolock _l(mLock);
8403 // Don't apply master mute in SW if our HAL can do it for us.
8404 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8405 mMasterMute = false;
8406 } else {
8407 mMasterMute = muted;
8408 }
8409}
8410
8411void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8412{
8413 Mutex::Autolock _l(mLock);
8414 if (stream == mStreamType) {
8415 mStreamVolume = value;
8416 broadcast_l();
8417 }
8418}
8419
8420float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8421{
8422 Mutex::Autolock _l(mLock);
8423 if (stream == mStreamType) {
8424 return mStreamVolume;
8425 }
8426 return 0.0f;
8427}
8428
8429void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8430{
8431 Mutex::Autolock _l(mLock);
8432 if (stream == mStreamType) {
8433 mStreamMute= muted;
8434 broadcast_l();
8435 }
8436}
8437
8438void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8439{
8440 Mutex::Autolock _l(mLock);
8441 if (streamType == mStreamType) {
8442 for (const sp<MmapTrack> &track : mActiveTracks) {
8443 track->invalidate();
8444 }
8445 broadcast_l();
8446 }
8447}
8448
8449void AudioFlinger::MmapPlaybackThread::processVolume_l()
8450{
8451 float volume;
8452
8453 if (mMasterMute || mStreamMute) {
8454 volume = 0;
8455 } else {
8456 volume = mMasterVolume * mStreamVolume;
8457 }
8458
8459 if (volume != mHalVolFloat) {
8460 mHalVolFloat = volume;
8461
8462 // Convert volumes from float to 8.24
8463 uint32_t vol = (uint32_t)(volume * (1 << 24));
8464
8465 // Delegate volume control to effect in track effect chain if needed
8466 // only one effect chain can be present on DirectOutputThread, so if
8467 // there is one, the track is connected to it
8468 if (!mEffectChains.isEmpty()) {
8469 mEffectChains[0]->setVolume_l(&vol, &vol);
8470 volume = (float)vol / (1 << 24);
8471 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008472 // Try to use HW volume control and fall back to SW control if not implemented
8473 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8474 sp<MmapStreamCallback> callback = mCallback.promote();
8475 if (callback != 0) {
8476 int channelCount;
8477 if (isOutput()) {
8478 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8479 } else {
8480 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8481 }
8482 Vector<float> values;
8483 for (int i = 0; i < channelCount; i++) {
8484 values.add(volume);
8485 }
8486 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008487 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008488 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008489 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008490 }
8491 }
8492}
8493
8494void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8495{
8496 if (!mMasterMute) {
8497 char value[PROPERTY_VALUE_MAX];
8498 if (property_get("ro.audio.silent", value, "0") > 0) {
8499 char *endptr;
8500 unsigned long ul = strtoul(value, &endptr, 0);
8501 if (*endptr == '\0' && ul != 0) {
8502 ALOGD("Silence is golden");
8503 // The setprop command will not allow a property to be changed after
8504 // the first time it is set, so we don't have to worry about un-muting.
8505 setMasterMute_l(true);
8506 }
8507 }
8508 }
8509}
8510
8511void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8512{
8513 MmapThread::dumpInternals(fd, args);
8514
Glenn Kastend3bb6452016-12-05 18:14:37 -08008515 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8516 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008517 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8518}
8519
8520AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8521 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8522 AudioHwDevice *hwDev, AudioStreamIn *input,
8523 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8524 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8525 mInput(input)
8526{
8527 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8528 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8529}
8530
8531AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8532{
8533 Mutex::Autolock _l(mLock);
8534 AudioStreamIn *input = mInput;
8535 mInput = NULL;
8536 return input;
8537}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008538} // namespace android