blob: b2a1e18a57e2152417f8701f700bae01369f5f2a [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) {
rago94a1ee82017-07-21 15:11:02 -07002540 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002541 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;
rago94a1ee82017-07-21 15:11:02 -07002887 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002888 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002889 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002890 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002891 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002892 if (mType != DIRECT) {
2893 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002894 status_t result = EffectBufferHalInterface::allocate(
rago94a1ee82017-07-21 15:11:02 -07002895 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08002896 &halInBuffer);
2897 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07002898#ifdef FLOAT_EFFECT_CHAIN
2899 buffer = halInBuffer->audioBuffer()->f32;
2900#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08002901 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07002902#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08002903 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2904 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002905 }
2906
2907 // Attach all tracks with same session ID to this chain.
2908 for (size_t i = 0; i < mTracks.size(); ++i) {
2909 sp<Track> track = mTracks[i];
2910 if (session == track->sessionId()) {
2911 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2912 buffer);
2913 track->setMainBuffer(buffer);
2914 chain->incTrackCnt();
2915 }
2916 }
2917
2918 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002919 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002920 if (session == track->sessionId()) {
2921 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2922 chain->incActiveTrackCnt();
2923 }
2924 }
2925 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002926 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002927 chain->setInBuffer(halInBuffer);
2928 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002929 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002930 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002931 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2932 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002933 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002934 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002935 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002936 // Effect chain for other sessions are inserted at beginning of effect
2937 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002938 // sessions is not important.
2939 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2940 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2941 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002942 size_t size = mEffectChains.size();
2943 size_t i = 0;
2944 for (i = 0; i < size; i++) {
2945 if (mEffectChains[i]->sessionId() < session) {
2946 break;
2947 }
2948 }
2949 mEffectChains.insertAt(chain, i);
2950 checkSuspendOnAddEffectChain_l(chain);
2951
2952 return NO_ERROR;
2953}
2954
2955size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2956{
Glenn Kastend848eb42016-03-08 13:42:11 -08002957 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002958
2959 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2960
2961 for (size_t i = 0; i < mEffectChains.size(); i++) {
2962 if (chain == mEffectChains[i]) {
2963 mEffectChains.removeAt(i);
2964 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002965 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002966 if (session == track->sessionId()) {
2967 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2968 chain.get(), session);
2969 chain->decActiveTrackCnt();
2970 }
2971 }
2972
2973 // detach all tracks with same session ID from this chain
2974 for (size_t i = 0; i < mTracks.size(); ++i) {
2975 sp<Track> track = mTracks[i];
2976 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07002977 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002978 chain->decTrackCnt();
2979 }
2980 }
2981 break;
2982 }
2983 }
2984 return mEffectChains.size();
2985}
2986
2987status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002988 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002989{
2990 Mutex::Autolock _l(mLock);
2991 return attachAuxEffect_l(track, EffectId);
2992}
2993
2994status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002995 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002996{
2997 status_t status = NO_ERROR;
2998
2999 if (EffectId == 0) {
3000 track->setAuxBuffer(0, NULL);
3001 } else {
3002 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3003 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3004 if (effect != 0) {
3005 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3006 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3007 } else {
3008 status = INVALID_OPERATION;
3009 }
3010 } else {
3011 status = BAD_VALUE;
3012 }
3013 }
3014 return status;
3015}
3016
3017void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3018{
3019 for (size_t i = 0; i < mTracks.size(); ++i) {
3020 sp<Track> track = mTracks[i];
3021 if (track->auxEffectId() == effectId) {
3022 attachAuxEffect_l(track, 0);
3023 }
3024 }
3025}
3026
3027bool AudioFlinger::PlaybackThread::threadLoop()
3028{
Glenn Kasten388d5712017-04-07 14:38:41 -07003029 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003030
Eric Laurent81784c32012-11-19 14:55:58 -08003031 Vector< sp<Track> > tracksToRemove;
3032
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003033 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003034 nsecs_t lastWriteFinished = -1; // time last server write completed
3035 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003036
3037 // MIXER
3038 nsecs_t lastWarning = 0;
3039
3040 // DUPLICATING
3041 // FIXME could this be made local to while loop?
3042 writeFrames = 0;
3043
3044 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003045 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003046
3047 if (mType == MIXER) {
3048 sleepTimeShift = 0;
3049 }
3050
3051 CpuStats cpuStats;
3052 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3053
3054 acquireWakeLock();
3055
Glenn Kasteneef598c2017-04-03 14:41:13 -07003056 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3057 // thread associated with this PlaybackThread.
3058 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3059 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003060 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3061 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003062 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003063 const char *logString = NULL;
3064
rago1bb90822017-05-02 18:31:48 -07003065 // Estimated time for next buffer to be written to hal. This is used only on
3066 // suspended mode (for now) to help schedule the wait time until next iteration.
3067 nsecs_t timeLoopNextNs = 0;
3068
Eric Laurent664539d2013-09-23 18:24:31 -07003069 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003070
Eric Laurent81784c32012-11-19 14:55:58 -08003071 while (!exitPending())
3072 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003073 // Log merge requests are performed during AudioFlinger binder transactions, but
3074 // that does not cover audio playback. It's requested here for that reason.
3075 mAudioFlinger->requestLogMerge();
3076
Eric Laurent81784c32012-11-19 14:55:58 -08003077 cpuStats.sample(myName);
3078
3079 Vector< sp<EffectChain> > effectChains;
3080
Eric Laurent81784c32012-11-19 14:55:58 -08003081 { // scope for mLock
3082
3083 Mutex::Autolock _l(mLock);
3084
Eric Laurent021cf962014-05-13 10:18:14 -07003085 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003086
Glenn Kasteneef598c2017-04-03 14:41:13 -07003087 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003088 if (logString != NULL) {
3089 mNBLogWriter->logTimestamp();
3090 mNBLogWriter->log(logString);
3091 logString = NULL;
3092 }
3093
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003094 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003095 // and associate with the sink frames written out. We need
3096 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003097 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003098 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003099 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003100 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003101 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003102 ExtendedTimestamp timestamp; // use private copy to fetch
3103 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003104
3105 // We keep track of the last valid kernel position in case we are in underrun
3106 // and the normal mixer period is the same as the fast mixer period, or there
3107 // is some error from the HAL.
3108 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3109 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3110 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3111 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3112 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3113
3114 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3115 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3116 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3117 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003118 }
3119
3120 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3121 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003122 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003123 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003124 }
3125
Andy Hung818e7a32016-02-16 18:08:07 -08003126 // copy over kernel info
3127 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003128 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3129 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003130 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3131 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003132 }
3133 // mFramesWritten for non-offloaded tracks are contiguous
3134 // even after standby() is called. This is useful for the track frame
3135 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003136 bool serverLocationUpdate = false;
3137 if (mFramesWritten != lastFramesWritten) {
3138 serverLocationUpdate = true;
3139 lastFramesWritten = mFramesWritten;
3140 }
3141 // Only update timestamps if there is a meaningful change.
3142 // Either the kernel timestamp must be valid or we have written something.
3143 if (kernelLocationUpdate || serverLocationUpdate) {
3144 if (serverLocationUpdate) {
3145 // use the time before we called the HAL write - it is a bit more accurate
3146 // to when the server last read data than the current time here.
3147 //
3148 // If we haven't written anything, mLastWriteTime will be -1
3149 // and we use systemTime().
3150 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3151 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3152 ? systemTime() : mLastWriteTime;
3153 }
Andy Hungdae27702016-10-31 14:01:16 -07003154
3155 for (const sp<Track> &t : mActiveTracks) {
3156 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003157 t->updateTrackFrameInfo(
3158 t->mAudioTrackServerProxy->framesReleased(),
3159 mFramesWritten,
3160 mTimestamp);
3161 }
Andy Hunge10393e2015-06-12 13:59:33 -07003162 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003163 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003164#if 0
3165 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003166 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003167 timespec ts;
3168 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003169 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003170 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003171 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003172 }
3173 ++z;
3174#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003175 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003176 if (mSignalPending) {
3177 // A signal was raised while we were unlocked
3178 mSignalPending = false;
3179 } else if (waitingAsyncCallback_l()) {
3180 if (exitPending()) {
3181 break;
3182 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003183 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003184 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003185 releaseWakeLock_l();
3186 released = true;
3187 }
Andy Hung10cbff12017-02-21 17:30:14 -08003188
3189 const int64_t waitNs = computeWaitTimeNs_l();
3190 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3191 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3192 if (status == TIMED_OUT) {
3193 mSignalPending = true; // if timeout recheck everything
3194 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003195 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003196 if (released) {
3197 acquireWakeLock_l();
3198 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003199 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3200 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003201
3202 continue;
3203 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003204 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003205 isSuspended()) {
3206 // put audio hardware into standby after short delay
3207 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003208
3209 threadLoop_standby();
3210
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003211 // This is where we go into standby
3212 if (!mStandby) {
3213 LOG_AUDIO_STATE();
3214 }
Eric Laurent81784c32012-11-19 14:55:58 -08003215 mStandby = true;
3216 }
3217
3218 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3219 // we're about to wait, flush the binder command buffer
3220 IPCThreadState::self()->flushCommands();
3221
3222 clearOutputTracks();
3223
3224 if (exitPending()) {
3225 break;
3226 }
3227
3228 releaseWakeLock_l();
3229 // wait until we have something to do...
3230 ALOGV("%s going to sleep", myName.string());
3231 mWaitWorkCV.wait(mLock);
3232 ALOGV("%s waking up", myName.string());
3233 acquireWakeLock_l();
3234
3235 mMixerStatus = MIXER_IDLE;
3236 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3237 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003238 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003239 checkSilentMode_l();
3240
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003241 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3242 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003243 if (mType == MIXER) {
3244 sleepTimeShift = 0;
3245 }
3246
3247 continue;
3248 }
3249 }
Eric Laurent81784c32012-11-19 14:55:58 -08003250 // mMixerStatusIgnoringFastTracks is also updated internally
3251 mMixerStatus = prepareTracks_l(&tracksToRemove);
3252
Andy Hungdae27702016-10-31 14:01:16 -07003253 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003254
Eric Laurent81784c32012-11-19 14:55:58 -08003255 // prevent any changes in effect chain list and in each effect chain
3256 // during mixing and effect process as the audio buffers could be deleted
3257 // or modified if an effect is created or deleted
3258 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003259 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003260
Eric Laurentbfb1b832013-01-07 09:53:42 -08003261 if (mBytesRemaining == 0) {
3262 mCurrentWriteLength = 0;
3263 if (mMixerStatus == MIXER_TRACKS_READY) {
3264 // threadLoop_mix() sets mCurrentWriteLength
3265 threadLoop_mix();
3266 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3267 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003268 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003269 // must be written to HAL
3270 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003271 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003272 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003273 }
3274 }
Andy Hung98ef9782014-03-04 14:46:50 -08003275 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003276 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003277 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3278 // or mSinkBuffer (if there are no effects).
3279 //
3280 // This is done pre-effects computation; if effects change to
3281 // support higher precision, this needs to move.
3282 //
3283 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003284 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003285 if (mMixerBufferValid) {
3286 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3287 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3288
Andy Hung2ddee192015-12-18 17:34:44 -08003289 // mono blend occurs for mixer threads only (not direct or offloaded)
3290 // and is handled here if we're going directly to the sink.
3291 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003292 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3293 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003294 }
3295
Andy Hung98ef9782014-03-04 14:46:50 -08003296 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3297 mNormalFrameCount * mChannelCount);
3298 }
3299
Eric Laurentbfb1b832013-01-07 09:53:42 -08003300 mBytesRemaining = mCurrentWriteLength;
3301 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003302 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3303 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3304 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3305 mBytesWritten += mBytesRemaining;
3306 mFramesWritten += framesRemaining;
3307 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003308 mBytesRemaining = 0;
3309 }
Eric Laurent81784c32012-11-19 14:55:58 -08003310
Eric Laurentbfb1b832013-01-07 09:53:42 -08003311 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003312 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003313 for (size_t i = 0; i < effectChains.size(); i ++) {
3314 effectChains[i]->process_l();
3315 }
Eric Laurent81784c32012-11-19 14:55:58 -08003316 }
3317 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003318 // Process effect chains for offloaded thread even if no audio
3319 // was read from audio track: process only updates effect state
3320 // and thus does have to be synchronized with audio writes but may have
3321 // to be called while waiting for async write callback
3322 if (mType == OFFLOAD) {
3323 for (size_t i = 0; i < effectChains.size(); i ++) {
3324 effectChains[i]->process_l();
3325 }
3326 }
Eric Laurent81784c32012-11-19 14:55:58 -08003327
Andy Hung98ef9782014-03-04 14:46:50 -08003328 // Only if the Effects buffer is enabled and there is data in the
3329 // Effects buffer (buffer valid), we need to
3330 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003331 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003332 if (mEffectBufferValid) {
3333 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003334
3335 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003336 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3337 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003338 }
3339
Andy Hung98ef9782014-03-04 14:46:50 -08003340 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3341 mNormalFrameCount * mChannelCount);
3342 }
3343
Eric Laurent81784c32012-11-19 14:55:58 -08003344 // enable changes in effect chain
3345 unlockEffectChains(effectChains);
3346
Eric Laurentbfb1b832013-01-07 09:53:42 -08003347 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003348 // mSleepTimeUs == 0 means we must write to audio hardware
3349 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003350 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003351 // We save lastWriteFinished here, as previousLastWriteFinished,
3352 // for throttling. On thread start, previousLastWriteFinished will be
3353 // set to -1, which properly results in no throttling after the first write.
3354 nsecs_t previousLastWriteFinished = lastWriteFinished;
3355 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003356 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003357 // FIXME rewrite to reduce number of system calls
3358 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003359 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003360 lastWriteFinished = systemTime();
3361 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003362 if (ret < 0) {
3363 mBytesRemaining = 0;
3364 } else {
3365 mBytesWritten += ret;
3366 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003367 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003368 }
3369 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3370 (mMixerStatus == MIXER_DRAIN_ALL)) {
3371 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003372 }
Andy Hung08fb1742015-05-31 23:22:10 -07003373 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003374 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003375 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003376 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003377 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003378 ATRACE_NAME("underrun");
3379 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003380 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003381 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003382 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003383 }
Andy Hung08fb1742015-05-31 23:22:10 -07003384
3385 if (mThreadThrottle
3386 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3387 && ret > 0) { // we wrote something
3388 // Limit MixerThread data processing to no more than twice the
3389 // expected processing rate.
3390 //
3391 // This helps prevent underruns with NuPlayer and other applications
3392 // which may set up buffers that are close to the minimum size, or use
3393 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3394 //
3395 // The throttle smooths out sudden large data drains from the device,
3396 // e.g. when it comes out of standby, which often causes problems with
3397 // (1) mixer threads without a fast mixer (which has its own warm-up)
3398 // (2) minimum buffer sized tracks (even if the track is full,
3399 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003400 //
3401 // Total time spent in last processing cycle equals time spent in
3402 // 1. threadLoop_write, as well as time spent in
3403 // 2. threadLoop_mix (significant for heavy mixing, especially
3404 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003405
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003406 // it's OK if deltaMs (and deltaNs) is an overestimate.
3407 nsecs_t deltaNs;
3408 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3409 __builtin_sub_overflow(
3410 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3411 const int32_t deltaMs = deltaNs / 1000000;
3412
Ivan Lozanoea04d392017-11-07 14:37:07 -08003413 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003414 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3415 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003416 // notify of throttle start on verbose log
3417 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3418 "mixer(%p) throttle begin:"
3419 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003420 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003421 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003422 // Throttle must be attributed to the previous mixer loop's write time
3423 // to allow back-to-back throttling.
3424 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003425 } else {
3426 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3427 if (diff > 0) {
3428 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003429 // but prevent spamming for bluetooth
3430 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3431 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003432 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3433 }
Andy Hung08fb1742015-05-31 23:22:10 -07003434 }
3435 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003436 }
Eric Laurent81784c32012-11-19 14:55:58 -08003437
Eric Laurentbfb1b832013-01-07 09:53:42 -08003438 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003439 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003440 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003441 // suspended requires accurate metering of sleep time.
3442 if (isSuspended()) {
3443 // advance by expected sleepTime
3444 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3445 const nsecs_t nowNs = systemTime();
3446
3447 // compute expected next time vs current time.
3448 // (negative deltas are treated as delays).
3449 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3450 if (deltaNs < -kMaxNextBufferDelayNs) {
3451 // Delays longer than the max allowed trigger a reset.
3452 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3453 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3454 timeLoopNextNs = nowNs + deltaNs;
3455 } else if (deltaNs < 0) {
3456 // Delays within the max delay allowed: zero the delta/sleepTime
3457 // to help the system catch up in the next iteration(s)
3458 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3459 deltaNs = 0;
3460 }
3461 // update sleep time (which is >= 0)
3462 mSleepTimeUs = deltaNs / 1000;
3463 }
Eric Laurente93cc032016-05-05 10:15:10 -07003464 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3465 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003466 }
Glenn Kastene7754022014-10-31 12:11:26 -07003467 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003468 }
Eric Laurent81784c32012-11-19 14:55:58 -08003469 }
3470
3471 // Finally let go of removed track(s), without the lock held
3472 // since we can't guarantee the destructors won't acquire that
3473 // same lock. This will also mutate and push a new fast mixer state.
3474 threadLoop_removeTracks(tracksToRemove);
3475 tracksToRemove.clear();
3476
3477 // FIXME I don't understand the need for this here;
3478 // it was in the original code but maybe the
3479 // assignment in saveOutputTracks() makes this unnecessary?
3480 clearOutputTracks();
3481
3482 // Effect chains will be actually deleted here if they were removed from
3483 // mEffectChains list during mixing or effects processing
3484 effectChains.clear();
3485
3486 // FIXME Note that the above .clear() is no longer necessary since effectChains
3487 // is now local to this block, but will keep it for now (at least until merge done).
3488 }
3489
Eric Laurentbfb1b832013-01-07 09:53:42 -08003490 threadLoop_exit();
3491
Eric Laurentcf817a22014-08-04 20:36:31 -07003492 if (!mStandby) {
3493 threadLoop_standby();
3494 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003495 }
3496
3497 releaseWakeLock();
3498
3499 ALOGV("Thread %p type %d exiting", this, mType);
3500 return false;
3501}
3502
Eric Laurentbfb1b832013-01-07 09:53:42 -08003503// removeTracks_l() must be called with ThreadBase::mLock held
3504void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3505{
3506 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003507 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003508 for (size_t i=0 ; i<count ; i++) {
3509 const sp<Track>& track = tracksToRemove.itemAt(i);
3510 mActiveTracks.remove(track);
3511 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3512 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3513 if (chain != 0) {
3514 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3515 track->sessionId());
3516 chain->decActiveTrackCnt();
3517 }
3518 if (track->isTerminated()) {
3519 removeTrack_l(track);
3520 }
3521 }
3522 }
3523
3524}
Eric Laurent81784c32012-11-19 14:55:58 -08003525
Eric Laurentaccc1472013-09-20 09:36:34 -07003526status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3527{
3528 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003529 ExtendedTimestamp ets;
3530 status_t status = mNormalSink->getTimestamp(ets);
3531 if (status == NO_ERROR) {
3532 status = ets.getBestTimestamp(&timestamp);
3533 }
3534 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003535 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003536 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003537 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003538 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003539 timestamp.mPosition = (uint32_t)position64;
3540 return NO_ERROR;
3541 }
3542 }
3543 return INVALID_OPERATION;
3544}
Eric Laurent1c333e22014-05-20 10:48:17 -07003545
Eric Laurent054d9d32015-04-24 08:48:48 -07003546status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3547 audio_patch_handle_t *handle)
3548{
Andy Hungf60abce2016-08-26 11:37:54 -07003549 status_t status;
3550 if (property_get_bool("af.patch_park", false /* default_value */)) {
3551 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3552 // or if HAL does not properly lock against access.
3553 AutoPark<FastMixer> park(mFastMixer);
3554 status = PlaybackThread::createAudioPatch_l(patch, handle);
3555 } else {
3556 status = PlaybackThread::createAudioPatch_l(patch, handle);
3557 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003558 return status;
3559}
3560
Eric Laurent1c333e22014-05-20 10:48:17 -07003561status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3562 audio_patch_handle_t *handle)
3563{
3564 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003565
3566 // store new device and send to effects
3567 audio_devices_t type = AUDIO_DEVICE_NONE;
3568 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3569 type |= patch->sinks[i].ext.device.type;
3570 }
3571
3572#ifdef ADD_BATTERY_DATA
3573 // when changing the audio output device, call addBatteryData to notify
3574 // the change
3575 if (mOutDevice != type) {
3576 uint32_t params = 0;
3577 // check whether speaker is on
3578 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3579 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003580 }
3581
Eric Laurent054d9d32015-04-24 08:48:48 -07003582 audio_devices_t deviceWithoutSpeaker
3583 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3584 // check if any other device (except speaker) is on
3585 if (type & deviceWithoutSpeaker) {
3586 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3587 }
3588
3589 if (params != 0) {
3590 addBatteryData(params);
3591 }
3592 }
3593#endif
3594
3595 for (size_t i = 0; i < mEffectChains.size(); i++) {
3596 mEffectChains[i]->setDevice_l(type);
3597 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003598
3599 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3600 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3601 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003602 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003603 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003604
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003605 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003606 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3607 status = hwDevice->createAudioPatch(patch->num_sources,
3608 patch->sources,
3609 patch->num_sinks,
3610 patch->sinks,
3611 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003612 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003613 char *address;
3614 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3615 //FIXME: we only support address on first sink with HAL version < 3.0
3616 address = audio_device_address_to_parameter(
3617 patch->sinks[0].ext.device.type,
3618 patch->sinks[0].ext.device.address);
3619 } else {
3620 address = (char *)calloc(1, 1);
3621 }
3622 AudioParameter param = AudioParameter(String8(address));
3623 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003624 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003625 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003626 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003627 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003628 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003629 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003630 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3631 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003632 return status;
3633}
3634
Eric Laurent054d9d32015-04-24 08:48:48 -07003635status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3636{
Andy Hungf60abce2016-08-26 11:37:54 -07003637 status_t status;
3638 if (property_get_bool("af.patch_park", false /* default_value */)) {
3639 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3640 // or if HAL does not properly lock against access.
3641 AutoPark<FastMixer> park(mFastMixer);
3642 status = PlaybackThread::releaseAudioPatch_l(handle);
3643 } else {
3644 status = PlaybackThread::releaseAudioPatch_l(handle);
3645 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003646 return status;
3647}
3648
Eric Laurent1c333e22014-05-20 10:48:17 -07003649status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3650{
3651 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003652
3653 mOutDevice = AUDIO_DEVICE_NONE;
3654
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003655 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003656 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3657 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003658 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003659 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003660 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003661 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003662 }
3663 return status;
3664}
3665
Eric Laurent83b88082014-06-20 18:31:16 -07003666void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3667{
3668 Mutex::Autolock _l(mLock);
3669 mTracks.add(track);
3670}
3671
3672void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3673{
3674 Mutex::Autolock _l(mLock);
3675 destroyTrack_l(track);
3676}
3677
3678void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3679{
3680 ThreadBase::getAudioPortConfig(config);
3681 config->role = AUDIO_PORT_ROLE_SOURCE;
3682 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3683 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3684}
3685
Eric Laurent81784c32012-11-19 14:55:58 -08003686// ----------------------------------------------------------------------------
3687
3688AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003689 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3690 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003691 // mAudioMixer below
3692 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003693 mFastMixerFutex(0),
3694 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003695 // mOutputSink below
3696 // mPipeSink below
3697 // mNormalSink below
3698{
3699 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003700 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3701 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003702 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3703 mNormalFrameCount);
3704 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3705
Andy Hungfbfc3952015-01-15 13:33:51 -08003706 if (type == DUPLICATING) {
3707 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3708 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3709 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3710 return;
3711 }
Eric Laurent81784c32012-11-19 14:55:58 -08003712 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003713 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003714 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003715 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003716#if !LOG_NDEBUG
3717 ssize_t index =
3718#else
3719 (void)
3720#endif
3721 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003722 ALOG_ASSERT(index == 0);
3723
3724 // initialize fast mixer depending on configuration
3725 bool initFastMixer;
3726 switch (kUseFastMixer) {
3727 case FastMixer_Never:
3728 initFastMixer = false;
3729 break;
3730 case FastMixer_Always:
3731 initFastMixer = true;
3732 break;
3733 case FastMixer_Static:
3734 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003735 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3736 // where the period is less than an experimentally determined threshold that can be
3737 // scheduled reliably with CFS. However, the BT A2DP HAL is
3738 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3739 initFastMixer = mFrameCount < mNormalFrameCount
3740 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003741 break;
3742 }
Andy Hungfda69402017-02-15 14:33:12 -08003743 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3744 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3745 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003746 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003747 audio_format_t fastMixerFormat;
3748 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3749 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3750 } else {
3751 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3752 }
3753 if (mFormat != fastMixerFormat) {
3754 // change our Sink format to accept our intermediate precision
3755 mFormat = fastMixerFormat;
3756 free(mSinkBuffer);
3757 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3758 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3759 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3760 }
Eric Laurent81784c32012-11-19 14:55:58 -08003761
3762 // create a MonoPipe to connect our submix to FastMixer
3763 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003764#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003765 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003766#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003767 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003768 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003769 format.mFormat = fastMixerFormat;
3770 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3771
Eric Laurent81784c32012-11-19 14:55:58 -08003772 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3773 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3774 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3775 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3776 const NBAIO_Format offers[1] = {format};
3777 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003778#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003779 ssize_t index =
3780#else
3781 (void)
3782#endif
3783 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003784 ALOG_ASSERT(index == 0);
3785 monoPipe->setAvgFrames((mScreenState & 1) ?
3786 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3787 mPipeSink = monoPipe;
3788
Glenn Kasten46909e72013-02-26 09:20:22 -08003789#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003790 if (mTeeSinkOutputEnabled) {
3791 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003792 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3793 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003794 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003795 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003796 ALOG_ASSERT(index == 0);
3797 mTeeSink = teeSink;
3798 PipeReader *teeSource = new PipeReader(*teeSink);
3799 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003800 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003801 ALOG_ASSERT(index == 0);
3802 mTeeSource = teeSource;
3803 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003804#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003805
3806 // create fast mixer and configure it initially with just one fast track for our submix
3807 mFastMixer = new FastMixer();
3808 FastMixerStateQueue *sq = mFastMixer->sq();
3809#ifdef STATE_QUEUE_DUMP
3810 sq->setObserverDump(&mStateQueueObserverDump);
3811 sq->setMutatorDump(&mStateQueueMutatorDump);
3812#endif
3813 FastMixerState *state = sq->begin();
3814 FastTrack *fastTrack = &state->mFastTracks[0];
3815 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3816 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3817 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003818 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3819 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003820 fastTrack->mGeneration++;
3821 state->mFastTracksGen++;
3822 state->mTrackMask = 1;
3823 // fast mixer will use the HAL output sink
3824 state->mOutputSink = mOutputSink.get();
3825 state->mOutputSinkGen++;
3826 state->mFrameCount = mFrameCount;
3827 state->mCommand = FastMixerState::COLD_IDLE;
3828 // already done in constructor initialization list
3829 //mFastMixerFutex = 0;
3830 state->mColdFutexAddr = &mFastMixerFutex;
3831 state->mColdGen++;
3832 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003833#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003834 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003835#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003836 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3837 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003838 sq->end();
3839 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3840
3841 // start the fast mixer
3842 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3843 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003844 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003845 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003846
3847#ifdef AUDIO_WATCHDOG
3848 // create and start the watchdog
3849 mAudioWatchdog = new AudioWatchdog();
3850 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3851 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3852 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003853 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003854#endif
3855
Eric Laurent81784c32012-11-19 14:55:58 -08003856 }
3857
3858 switch (kUseFastMixer) {
3859 case FastMixer_Never:
3860 case FastMixer_Dynamic:
3861 mNormalSink = mOutputSink;
3862 break;
3863 case FastMixer_Always:
3864 mNormalSink = mPipeSink;
3865 break;
3866 case FastMixer_Static:
3867 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3868 break;
3869 }
3870}
3871
3872AudioFlinger::MixerThread::~MixerThread()
3873{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003874 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003875 FastMixerStateQueue *sq = mFastMixer->sq();
3876 FastMixerState *state = sq->begin();
3877 if (state->mCommand == FastMixerState::COLD_IDLE) {
3878 int32_t old = android_atomic_inc(&mFastMixerFutex);
3879 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003880 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003881 }
3882 }
3883 state->mCommand = FastMixerState::EXIT;
3884 sq->end();
3885 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3886 mFastMixer->join();
3887 // Though the fast mixer thread has exited, it's state queue is still valid.
3888 // We'll use that extract the final state which contains one remaining fast track
3889 // corresponding to our sub-mix.
3890 state = sq->begin();
3891 ALOG_ASSERT(state->mTrackMask == 1);
3892 FastTrack *fastTrack = &state->mFastTracks[0];
3893 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3894 delete fastTrack->mBufferProvider;
3895 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003896 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003897#ifdef AUDIO_WATCHDOG
3898 if (mAudioWatchdog != 0) {
3899 mAudioWatchdog->requestExit();
3900 mAudioWatchdog->requestExitAndWait();
3901 mAudioWatchdog.clear();
3902 }
3903#endif
3904 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003905 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003906 delete mAudioMixer;
3907}
3908
3909
3910uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3911{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003912 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003913 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3914 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3915 }
3916 return latency;
3917}
3918
3919
3920void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3921{
3922 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3923}
3924
Eric Laurentbfb1b832013-01-07 09:53:42 -08003925ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003926{
3927 // FIXME we should only do one push per cycle; confirm this is true
3928 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003929 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003930 FastMixerStateQueue *sq = mFastMixer->sq();
3931 FastMixerState *state = sq->begin();
3932 if (state->mCommand != FastMixerState::MIX_WRITE &&
3933 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3934 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003935
3936 // FIXME workaround for first HAL write being CPU bound on some devices
3937 ATRACE_BEGIN("write");
3938 mOutput->write((char *)mSinkBuffer, 0);
3939 ATRACE_END();
3940
Eric Laurent81784c32012-11-19 14:55:58 -08003941 int32_t old = android_atomic_inc(&mFastMixerFutex);
3942 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003943 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003944 }
3945#ifdef AUDIO_WATCHDOG
3946 if (mAudioWatchdog != 0) {
3947 mAudioWatchdog->resume();
3948 }
3949#endif
3950 }
3951 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003952#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003953 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003954 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003955#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003956 sq->end();
3957 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3958 if (kUseFastMixer == FastMixer_Dynamic) {
3959 mNormalSink = mPipeSink;
3960 }
3961 } else {
3962 sq->end(false /*didModify*/);
3963 }
3964 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003965 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003966}
3967
3968void AudioFlinger::MixerThread::threadLoop_standby()
3969{
3970 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003971 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003972 FastMixerStateQueue *sq = mFastMixer->sq();
3973 FastMixerState *state = sq->begin();
3974 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003975 // Report any frames trapped in the Monopipe
3976 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3977 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3978 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3979 "monoPipeWritten:%lld monoPipeLeft:%lld",
3980 (long long)mFramesWritten, (long long)mSuspendedFrames,
3981 (long long)mPipeSink->framesWritten(), pipeFrames);
3982 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3983
Eric Laurent81784c32012-11-19 14:55:58 -08003984 state->mCommand = FastMixerState::COLD_IDLE;
3985 state->mColdFutexAddr = &mFastMixerFutex;
3986 state->mColdGen++;
3987 mFastMixerFutex = 0;
3988 sq->end();
3989 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3990 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3991 if (kUseFastMixer == FastMixer_Dynamic) {
3992 mNormalSink = mOutputSink;
3993 }
3994#ifdef AUDIO_WATCHDOG
3995 if (mAudioWatchdog != 0) {
3996 mAudioWatchdog->pause();
3997 }
3998#endif
3999 } else {
4000 sq->end(false /*didModify*/);
4001 }
4002 }
4003 PlaybackThread::threadLoop_standby();
4004}
4005
Eric Laurentbfb1b832013-01-07 09:53:42 -08004006bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4007{
4008 return false;
4009}
4010
4011bool AudioFlinger::PlaybackThread::shouldStandby_l()
4012{
4013 return !mStandby;
4014}
4015
4016bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4017{
4018 Mutex::Autolock _l(mLock);
4019 return waitingAsyncCallback_l();
4020}
4021
Eric Laurent81784c32012-11-19 14:55:58 -08004022// shared by MIXER and DIRECT, overridden by DUPLICATING
4023void AudioFlinger::PlaybackThread::threadLoop_standby()
4024{
4025 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004026 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004027 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004028 // discard any pending drain or write ack by incrementing sequence
4029 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4030 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004032 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4033 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004034 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004035 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004036}
4037
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004038void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4039{
4040 ALOGV("signal playback thread");
4041 broadcast_l();
4042}
4043
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004044void AudioFlinger::PlaybackThread::onAsyncError()
4045{
4046 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4047 invalidateTracks((audio_stream_type_t)i);
4048 }
4049}
4050
Eric Laurent81784c32012-11-19 14:55:58 -08004051void AudioFlinger::MixerThread::threadLoop_mix()
4052{
Eric Laurent81784c32012-11-19 14:55:58 -08004053 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004054 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004055 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004056 // increase sleep time progressively when application underrun condition clears.
4057 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4058 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4059 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004060 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004061 sleepTimeShift--;
4062 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004063 mSleepTimeUs = 0;
4064 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004065 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004066
Eric Laurent81784c32012-11-19 14:55:58 -08004067}
4068
4069void AudioFlinger::MixerThread::threadLoop_sleepTime()
4070{
4071 // If no tracks are ready, sleep once for the duration of an output
4072 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004073 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004074 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004075 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4076 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4077 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004078 }
4079 // reduce sleep time in case of consecutive application underruns to avoid
4080 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4081 // duration we would end up writing less data than needed by the audio HAL if
4082 // the condition persists.
4083 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4084 sleepTimeShift++;
4085 }
4086 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004087 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004088 }
4089 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004090 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4091 // before effects processing or output.
4092 if (mMixerBufferValid) {
4093 memset(mMixerBuffer, 0, mMixerBufferSize);
4094 } else {
4095 memset(mSinkBuffer, 0, mSinkBufferSize);
4096 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004097 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004098 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4099 "anticipated start");
4100 }
4101 // TODO add standby time extension fct of effect tail
4102}
4103
4104// prepareTracks_l() must be called with ThreadBase::mLock held
4105AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4106 Vector< sp<Track> > *tracksToRemove)
4107{
4108
4109 mixer_state mixerStatus = MIXER_IDLE;
4110 // find out which tracks need to be processed
4111 size_t count = mActiveTracks.size();
4112 size_t mixedTracks = 0;
4113 size_t tracksWithEffect = 0;
4114 // counts only _active_ fast tracks
4115 size_t fastTracks = 0;
4116 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4117
4118 float masterVolume = mMasterVolume;
4119 bool masterMute = mMasterMute;
4120
4121 if (masterMute) {
4122 masterVolume = 0;
4123 }
4124 // Delegate master volume control to effect in output mix effect chain if needed
4125 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4126 if (chain != 0) {
4127 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4128 chain->setVolume_l(&v, &v);
4129 masterVolume = (float)((v + (1 << 23)) >> 24);
4130 chain.clear();
4131 }
4132
4133 // prepare a new state to push
4134 FastMixerStateQueue *sq = NULL;
4135 FastMixerState *state = NULL;
4136 bool didModify = false;
4137 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004138 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004139 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004140 sq = mFastMixer->sq();
4141 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004142 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004143 }
4144
Andy Hung69aed5f2014-02-25 17:24:40 -08004145 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004146 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004147
Eric Laurent81784c32012-11-19 14:55:58 -08004148 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004149 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004150
4151 // this const just means the local variable doesn't change
4152 Track* const track = t.get();
4153
4154 // process fast tracks
4155 if (track->isFastTrack()) {
4156
4157 // It's theoretically possible (though unlikely) for a fast track to be created
4158 // and then removed within the same normal mix cycle. This is not a problem, as
4159 // the track never becomes active so it's fast mixer slot is never touched.
4160 // The converse, of removing an (active) track and then creating a new track
4161 // at the identical fast mixer slot within the same normal mix cycle,
4162 // is impossible because the slot isn't marked available until the end of each cycle.
4163 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004164 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004165 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4166 FastTrack *fastTrack = &state->mFastTracks[j];
4167
4168 // Determine whether the track is currently in underrun condition,
4169 // and whether it had a recent underrun.
4170 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4171 FastTrackUnderruns underruns = ftDump->mUnderruns;
4172 uint32_t recentFull = (underruns.mBitFields.mFull -
4173 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4174 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4175 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4176 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4177 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4178 uint32_t recentUnderruns = recentPartial + recentEmpty;
4179 track->mObservedUnderruns = underruns;
4180 // don't count underruns that occur while stopping or pausing
4181 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004182 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4183 recentUnderruns > 0) {
4184 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4185 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004186 } else {
4187 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004188 }
4189
4190 // This is similar to the state machine for normal tracks,
4191 // with a few modifications for fast tracks.
4192 bool isActive = true;
4193 switch (track->mState) {
4194 case TrackBase::STOPPING_1:
4195 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004196 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004197 track->mState = TrackBase::STOPPING_2;
4198 }
4199 break;
4200 case TrackBase::PAUSING:
4201 // ramp down is not yet implemented
4202 track->setPaused();
4203 break;
4204 case TrackBase::RESUMING:
4205 // ramp up is not yet implemented
4206 track->mState = TrackBase::ACTIVE;
4207 break;
4208 case TrackBase::ACTIVE:
4209 if (recentFull > 0 || recentPartial > 0) {
4210 // track has provided at least some frames recently: reset retry count
4211 track->mRetryCount = kMaxTrackRetries;
4212 }
4213 if (recentUnderruns == 0) {
4214 // no recent underruns: stay active
4215 break;
4216 }
4217 // there has recently been an underrun of some kind
4218 if (track->sharedBuffer() == 0) {
4219 // were any of the recent underruns "empty" (no frames available)?
4220 if (recentEmpty == 0) {
4221 // no, then ignore the partial underruns as they are allowed indefinitely
4222 break;
4223 }
4224 // there has recently been an "empty" underrun: decrement the retry counter
4225 if (--(track->mRetryCount) > 0) {
4226 break;
4227 }
4228 // indicate to client process that the track was disabled because of underrun;
4229 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004230 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004231 // remove from active list, but state remains ACTIVE [confusing but true]
4232 isActive = false;
4233 break;
4234 }
4235 // fall through
4236 case TrackBase::STOPPING_2:
4237 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004238 case TrackBase::STOPPED:
4239 case TrackBase::FLUSHED: // flush() while active
4240 // Check for presentation complete if track is inactive
4241 // We have consumed all the buffers of this track.
4242 // This would be incomplete if we auto-paused on underrun
4243 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004244 uint32_t latency = 0;
4245 status_t result = mOutput->stream->getLatency(&latency);
4246 ALOGE_IF(result != OK,
4247 "Error when retrieving output stream latency: %d", result);
4248 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004249 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004250 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4251 // track stays in active list until presentation is complete
4252 break;
4253 }
4254 }
4255 if (track->isStopping_2()) {
4256 track->mState = TrackBase::STOPPED;
4257 }
4258 if (track->isStopped()) {
4259 // Can't reset directly, as fast mixer is still polling this track
4260 // track->reset();
4261 // So instead mark this track as needing to be reset after push with ack
4262 resetMask |= 1 << i;
4263 }
4264 isActive = false;
4265 break;
4266 case TrackBase::IDLE:
4267 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004268 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004269 }
4270
4271 if (isActive) {
4272 // was it previously inactive?
4273 if (!(state->mTrackMask & (1 << j))) {
4274 ExtendedAudioBufferProvider *eabp = track;
4275 VolumeProvider *vp = track;
4276 fastTrack->mBufferProvider = eabp;
4277 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004278 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004279 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004280 fastTrack->mGeneration++;
4281 state->mTrackMask |= 1 << j;
4282 didModify = true;
4283 // no acknowledgement required for newly active tracks
4284 }
4285 // cache the combined master volume and stream type volume for fast mixer; this
4286 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004287 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004288 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004289 track->mCachedVolume = masterVolume
4290 * mStreamTypes[track->streamType()].volume
4291 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004292 ++fastTracks;
4293 } else {
4294 // was it previously active?
4295 if (state->mTrackMask & (1 << j)) {
4296 fastTrack->mBufferProvider = NULL;
4297 fastTrack->mGeneration++;
4298 state->mTrackMask &= ~(1 << j);
4299 didModify = true;
4300 // If any fast tracks were removed, we must wait for acknowledgement
4301 // because we're about to decrement the last sp<> on those tracks.
4302 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4303 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004304 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4305 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4306 j, track->mState, state->mTrackMask, recentUnderruns,
4307 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004308 }
4309 tracksToRemove->add(track);
4310 // Avoids a misleading display in dumpsys
4311 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4312 }
4313 continue;
4314 }
4315
4316 { // local variable scope to avoid goto warning
4317
4318 audio_track_cblk_t* cblk = track->cblk();
4319
4320 // The first time a track is added we wait
4321 // for all its buffers to be filled before processing it
4322 int name = track->name();
4323 // make sure that we have enough frames to mix one full buffer.
4324 // enforce this condition only once to enable draining the buffer in case the client
4325 // app does not call stop() and relies on underrun to stop:
4326 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4327 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004328 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004329 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004330 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004331
4332 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004333 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004334 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4335 // add frames already consumed but not yet released by the resampler
4336 // because mAudioTrackServerProxy->framesReady() will include these frames
4337 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4338
Eric Laurent81784c32012-11-19 14:55:58 -08004339 uint32_t minFrames = 1;
4340 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4341 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004342 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004343 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004344
4345 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004346 if (ATRACE_ENABLED()) {
4347 // I wish we had formatted trace names
4348 char traceName[16];
4349 strcpy(traceName, "nRdy");
4350 int name = track->name();
4351 if (AudioMixer::TRACK0 <= name &&
4352 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4353 name -= AudioMixer::TRACK0;
4354 traceName[4] = (name / 10) + '0';
4355 traceName[5] = (name % 10) + '0';
4356 } else {
4357 traceName[4] = '?';
4358 traceName[5] = '?';
4359 }
4360 traceName[6] = '\0';
4361 ATRACE_INT(traceName, framesReady);
4362 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004363 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004364 !track->isPaused() && !track->isTerminated())
4365 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004366 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004367
4368 mixedTracks++;
4369
Andy Hung69aed5f2014-02-25 17:24:40 -08004370 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4371 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004372 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004373 if (track->mainBuffer() != mSinkBuffer &&
4374 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004375 if (mEffectBufferEnabled) {
4376 mEffectBufferValid = true; // Later can set directly.
4377 }
Eric Laurent81784c32012-11-19 14:55:58 -08004378 chain = getEffectChain_l(track->sessionId());
4379 // Delegate volume control to effect in track effect chain if needed
4380 if (chain != 0) {
4381 tracksWithEffect++;
4382 } else {
4383 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4384 "session %d",
4385 name, track->sessionId());
4386 }
4387 }
4388
4389
4390 int param = AudioMixer::VOLUME;
4391 if (track->mFillingUpStatus == Track::FS_FILLED) {
4392 // no ramp for the first volume setting
4393 track->mFillingUpStatus = Track::FS_ACTIVE;
4394 if (track->mState == TrackBase::RESUMING) {
4395 track->mState = TrackBase::ACTIVE;
4396 param = AudioMixer::RAMP_VOLUME;
4397 }
4398 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004399 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004400 // FIXME should not make a decision based on mServer
4401 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004402 // If the track is stopped before the first frame was mixed,
4403 // do not apply ramp
4404 param = AudioMixer::RAMP_VOLUME;
4405 }
4406
4407 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004408 uint32_t vl, vr; // in U8.24 integer format
4409 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004410 // read original volumes with volume control
4411 float typeVolume = mStreamTypes[track->streamType()].volume;
4412 float v = masterVolume * typeVolume;
4413
Glenn Kastene4756fe2012-11-29 13:38:14 -08004414 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004415 vl = vr = 0;
4416 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004417 if (track->isPausing()) {
4418 track->setPaused();
4419 }
4420 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004421 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004422 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004423 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4424 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004425 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004426 if (vlf > GAIN_FLOAT_UNITY) {
4427 ALOGV("Track left volume out of range: %.3g", vlf);
4428 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004429 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004430 if (vrf > GAIN_FLOAT_UNITY) {
4431 ALOGV("Track right volume out of range: %.3g", vrf);
4432 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004433 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004434 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004435 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004436 // now apply the master volume and stream type volume and shaper volume
4437 vlf *= v * vh;
4438 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004439 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004440 // then derive vl and vr as U8.24 versions for the effect chain
4441 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4442 vl = (uint32_t) (scaleto8_24 * vlf);
4443 vr = (uint32_t) (scaleto8_24 * vrf);
4444 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004445 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004446 // send level comes from shared memory and so may be corrupt
4447 if (sendLevel > MAX_GAIN_INT) {
4448 ALOGV("Track send level out of range: %04X", sendLevel);
4449 sendLevel = MAX_GAIN_INT;
4450 }
Andy Hung6be49402014-05-30 10:42:03 -07004451 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4452 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004453 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004454
Eric Laurent81784c32012-11-19 14:55:58 -08004455 // Delegate volume control to effect in track effect chain if needed
4456 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4457 // Do not ramp volume if volume is controlled by effect
4458 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004459 // Update remaining floating point volume levels
4460 vlf = (float)vl / (1 << 24);
4461 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004462 track->mHasVolumeController = true;
4463 } else {
4464 // force no volume ramp when volume controller was just disabled or removed
4465 // from effect chain to avoid volume spike
4466 if (track->mHasVolumeController) {
4467 param = AudioMixer::VOLUME;
4468 }
4469 track->mHasVolumeController = false;
4470 }
4471
Eric Laurent7c29ec92017-09-20 17:54:22 -07004472 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4473 // still applied by the mixer.
4474 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4475 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4476 if (v != mLeftVolFloat) {
4477 status_t result = mOutput->stream->setVolume(v, v);
4478 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4479 if (result == OK) {
4480 mLeftVolFloat = v;
4481 }
4482 }
4483 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4484 // remove stream volume contribution from software volume.
4485 if (v != 0.0f && mLeftVolFloat == v) {
4486 vlf = min(1.0f, vlf / v);
4487 vrf = min(1.0f, vrf / v);
4488 vaf = min(1.0f, vaf / v);
4489 }
4490 }
Eric Laurent81784c32012-11-19 14:55:58 -08004491 // XXX: these things DON'T need to be done each time
4492 mAudioMixer->setBufferProvider(name, track);
4493 mAudioMixer->enable(name);
4494
Andy Hung6be49402014-05-30 10:42:03 -07004495 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4496 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4497 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004498 mAudioMixer->setParameter(
4499 name,
4500 AudioMixer::TRACK,
4501 AudioMixer::FORMAT, (void *)track->format());
4502 mAudioMixer->setParameter(
4503 name,
4504 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004505 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004506 mAudioMixer->setParameter(
4507 name,
4508 AudioMixer::TRACK,
4509 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004510 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004511 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004512 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004513 if (reqSampleRate == 0) {
4514 reqSampleRate = mSampleRate;
4515 } else if (reqSampleRate > maxSampleRate) {
4516 reqSampleRate = maxSampleRate;
4517 }
Eric Laurent81784c32012-11-19 14:55:58 -08004518 mAudioMixer->setParameter(
4519 name,
4520 AudioMixer::RESAMPLE,
4521 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004522 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004523
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004524 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004525 mAudioMixer->setParameter(
4526 name,
4527 AudioMixer::TIMESTRETCH,
4528 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004529 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004530
Andy Hung69aed5f2014-02-25 17:24:40 -08004531 /*
4532 * Select the appropriate output buffer for the track.
4533 *
Andy Hung98ef9782014-03-04 14:46:50 -08004534 * Tracks with effects go into their own effects chain buffer
4535 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004536 *
4537 * Other tracks can use mMixerBuffer for higher precision
4538 * channel accumulation. If this buffer is enabled
4539 * (mMixerBufferEnabled true), then selected tracks will accumulate
4540 * into it.
4541 *
4542 */
4543 if (mMixerBufferEnabled
4544 && (track->mainBuffer() == mSinkBuffer
4545 || track->mainBuffer() == mMixerBuffer)) {
4546 mAudioMixer->setParameter(
4547 name,
4548 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004549 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004550 mAudioMixer->setParameter(
4551 name,
4552 AudioMixer::TRACK,
4553 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4554 // TODO: override track->mainBuffer()?
4555 mMixerBufferValid = true;
4556 } else {
4557 mAudioMixer->setParameter(
4558 name,
4559 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004560 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004561 mAudioMixer->setParameter(
4562 name,
4563 AudioMixer::TRACK,
4564 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4565 }
Eric Laurent81784c32012-11-19 14:55:58 -08004566 mAudioMixer->setParameter(
4567 name,
4568 AudioMixer::TRACK,
4569 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4570
4571 // reset retry count
4572 track->mRetryCount = kMaxTrackRetries;
4573
4574 // If one track is ready, set the mixer ready if:
4575 // - the mixer was not ready during previous round OR
4576 // - no other track is not ready
4577 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4578 mixerStatus != MIXER_TRACKS_ENABLED) {
4579 mixerStatus = MIXER_TRACKS_READY;
4580 }
4581 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004582 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004583 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4584 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004585 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004586 } else {
4587 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004588 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004589
Eric Laurent81784c32012-11-19 14:55:58 -08004590 // clear effect chain input buffer if an active track underruns to avoid sending
4591 // previous audio buffer again to effects
4592 chain = getEffectChain_l(track->sessionId());
4593 if (chain != 0) {
4594 chain->clearInputBuffer();
4595 }
4596
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004597 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004598 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4599 track->isStopped() || track->isPaused()) {
4600 // We have consumed all the buffers of this track.
4601 // Remove it from the list of active tracks.
4602 // TODO: use actual buffer filling status instead of latency when available from
4603 // audio HAL
4604 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004605 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004606 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4607 if (track->isStopped()) {
4608 track->reset();
4609 }
4610 tracksToRemove->add(track);
4611 }
4612 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004613 // No buffers for this track. Give it a few chances to
4614 // fill a buffer, then remove it from active list.
4615 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004616 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004617 tracksToRemove->add(track);
4618 // indicate to client process that the track was disabled because of underrun;
4619 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004620 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004621 // If one track is not ready, mark the mixer also not ready if:
4622 // - the mixer was ready during previous round OR
4623 // - no other track is ready
4624 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4625 mixerStatus != MIXER_TRACKS_READY) {
4626 mixerStatus = MIXER_TRACKS_ENABLED;
4627 }
4628 }
4629 mAudioMixer->disable(name);
4630 }
4631
4632 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004633
4634 }
4635
4636 // Push the new FastMixer state if necessary
4637 bool pauseAudioWatchdog = false;
4638 if (didModify) {
4639 state->mFastTracksGen++;
4640 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4641 if (kUseFastMixer == FastMixer_Dynamic &&
4642 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4643 state->mCommand = FastMixerState::COLD_IDLE;
4644 state->mColdFutexAddr = &mFastMixerFutex;
4645 state->mColdGen++;
4646 mFastMixerFutex = 0;
4647 if (kUseFastMixer == FastMixer_Dynamic) {
4648 mNormalSink = mOutputSink;
4649 }
4650 // If we go into cold idle, need to wait for acknowledgement
4651 // so that fast mixer stops doing I/O.
4652 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4653 pauseAudioWatchdog = true;
4654 }
Eric Laurent81784c32012-11-19 14:55:58 -08004655 }
4656 if (sq != NULL) {
4657 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004658 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4659 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4660 // when bringing the output sink into standby.)
4661 //
4662 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4663 //
4664 // This occurs with BT suspend when we idle the FastMixer with
4665 // active tracks, which may be added or removed.
4666 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004667 }
4668#ifdef AUDIO_WATCHDOG
4669 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4670 mAudioWatchdog->pause();
4671 }
4672#endif
4673
4674 // Now perform the deferred reset on fast tracks that have stopped
4675 while (resetMask != 0) {
4676 size_t i = __builtin_ctz(resetMask);
4677 ALOG_ASSERT(i < count);
4678 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004679 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004680 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4681 track->reset();
4682 }
4683
4684 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004685 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004686
Eric Laurent97d547d2014-09-02 14:45:53 -07004687 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4688 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004689 }
4690
4691 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004692 // as long as there are effects we should clear the effects buffer, to avoid
4693 // passing a non-clean buffer to the effect chain
4694 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004695 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004696 // sink or mix buffer must be cleared if all tracks are connected to an
4697 // effect chain as in this case the mixer will not write to the sink or mix buffer
4698 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004699 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4700 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004701 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004702 if (mMixerBufferValid) {
4703 memset(mMixerBuffer, 0, mMixerBufferSize);
4704 // TODO: In testing, mSinkBuffer below need not be cleared because
4705 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4706 // after mixing.
4707 //
4708 // To enforce this guarantee:
4709 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4710 // (mixedTracks == 0 && fastTracks > 0))
4711 // must imply MIXER_TRACKS_READY.
4712 // Later, we may clear buffers regardless, and skip much of this logic.
4713 }
Andy Hung98ef9782014-03-04 14:46:50 -08004714 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004715 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004716 }
4717
4718 // if any fast tracks, then status is ready
4719 mMixerStatusIgnoringFastTracks = mixerStatus;
4720 if (fastTracks > 0) {
4721 mixerStatus = MIXER_TRACKS_READY;
4722 }
4723 return mixerStatus;
4724}
4725
Eric Laurentad7dd962016-09-22 12:38:37 -07004726// trackCountForUid_l() must be called with ThreadBase::mLock held
4727uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4728{
4729 uint32_t trackCount = 0;
4730 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004731 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004732 trackCount++;
4733 }
4734 }
4735 return trackCount;
4736}
4737
Eric Laurent81784c32012-11-19 14:55:58 -08004738// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004739int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004740 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004741{
Eric Laurentad7dd962016-09-22 12:38:37 -07004742 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4743 return -1;
4744 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004745 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004746}
4747
4748// deleteTrackName_l() must be called with ThreadBase::mLock held
4749void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4750{
4751 ALOGV("remove track (%d) and delete from mixer", name);
4752 mAudioMixer->deleteTrackName(name);
4753}
4754
Eric Laurent10351942014-05-08 18:49:52 -07004755// checkForNewParameter_l() must be called with ThreadBase::mLock held
4756bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4757 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004758{
Eric Laurent81784c32012-11-19 14:55:58 -08004759 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004760 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004761
Eric Laurent10351942014-05-08 18:49:52 -07004762 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004763
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004764 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004765
Eric Laurent10351942014-05-08 18:49:52 -07004766 AudioParameter param = AudioParameter(keyValuePair);
4767 int value;
4768 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4769 reconfig = true;
4770 }
4771 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004772 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004773 status = BAD_VALUE;
4774 } else {
4775 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004776 reconfig = true;
4777 }
Eric Laurent10351942014-05-08 18:49:52 -07004778 }
4779 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004780 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004781 status = BAD_VALUE;
4782 } else {
4783 // no need to save value, since it's constant
4784 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004785 }
Eric Laurent10351942014-05-08 18:49:52 -07004786 }
4787 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4788 // do not accept frame count changes if tracks are open as the track buffer
4789 // size depends on frame count and correct behavior would not be guaranteed
4790 // if frame count is changed after track creation
4791 if (!mTracks.isEmpty()) {
4792 status = INVALID_OPERATION;
4793 } else {
4794 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004795 }
Eric Laurent10351942014-05-08 18:49:52 -07004796 }
4797 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004798#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004799 // when changing the audio output device, call addBatteryData to notify
4800 // the change
4801 if (mOutDevice != value) {
4802 uint32_t params = 0;
4803 // check whether speaker is on
4804 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4805 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004806 }
Eric Laurent10351942014-05-08 18:49:52 -07004807
4808 audio_devices_t deviceWithoutSpeaker
4809 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4810 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004811 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004812 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4813 }
4814
4815 if (params != 0) {
4816 addBatteryData(params);
4817 }
4818 }
Eric Laurent81784c32012-11-19 14:55:58 -08004819#endif
4820
Eric Laurent10351942014-05-08 18:49:52 -07004821 // forward device change to effects that have requested to be
4822 // aware of attached audio device.
4823 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004824 a2dpDeviceChanged =
4825 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004826 mOutDevice = value;
4827 for (size_t i = 0; i < mEffectChains.size(); i++) {
4828 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004829 }
4830 }
Eric Laurent10351942014-05-08 18:49:52 -07004831 }
Eric Laurent81784c32012-11-19 14:55:58 -08004832
Eric Laurent10351942014-05-08 18:49:52 -07004833 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004834 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004835 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004836 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004837 mStandby = true;
4838 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004839 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004840 }
Eric Laurent10351942014-05-08 18:49:52 -07004841 if (status == NO_ERROR && reconfig) {
4842 readOutputParameters_l();
4843 delete mAudioMixer;
4844 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4845 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004846 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004847 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004848 if (name < 0) {
4849 break;
4850 }
4851 mTracks[i]->mName = name;
4852 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004853 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004854 }
Eric Laurent81784c32012-11-19 14:55:58 -08004855 }
4856
Eric Laurent42537be2016-01-08 17:16:42 -08004857 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004858}
4859
4860
4861void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4862{
Eric Laurent81784c32012-11-19 14:55:58 -08004863 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004864 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004865 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004866 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004867
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004868 if (hasFastMixer()) {
4869 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4870
4871 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4872 // while we are dumping it. It may be inconsistent, but it won't mutate!
4873 // This is a large object so we place it on the heap.
4874 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4875 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4876 copy->dump(fd);
4877 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004878
4879#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004880 // Similar for state queue
4881 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4882 observerCopy.dump(fd);
4883 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4884 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004885#endif
4886
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004887#ifdef AUDIO_WATCHDOG
4888 if (mAudioWatchdog != 0) {
4889 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4890 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4891 wdCopy.dump(fd);
4892 }
4893#endif
4894
4895 } else {
4896 dprintf(fd, " No FastMixer\n");
4897 }
4898
Glenn Kasten46909e72013-02-26 09:20:22 -08004899#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004900 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004901 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004902#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004903
Eric Laurent81784c32012-11-19 14:55:58 -08004904}
4905
4906uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4907{
4908 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4909}
4910
4911uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4912{
4913 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4914}
4915
4916void AudioFlinger::MixerThread::cacheParameters_l()
4917{
4918 PlaybackThread::cacheParameters_l();
4919
4920 // FIXME: Relaxed timing because of a certain device that can't meet latency
4921 // Should be reduced to 2x after the vendor fixes the driver issue
4922 // increase threshold again due to low power audio mode. The way this warning
4923 // threshold is calculated and its usefulness should be reconsidered anyway.
4924 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4925}
4926
4927// ----------------------------------------------------------------------------
4928
4929AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004930 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4931 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004932{
4933}
4934
Eric Laurentbfb1b832013-01-07 09:53:42 -08004935AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4936 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004937 ThreadBase::type_t type, bool systemReady)
4938 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08004939 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004940{
4941}
4942
Eric Laurent81784c32012-11-19 14:55:58 -08004943AudioFlinger::DirectOutputThread::~DirectOutputThread()
4944{
4945}
4946
Eric Laurent5850c4c2016-11-10 13:04:31 -08004947void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004948{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004949 float left, right;
4950
4951 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4952 left = right = 0;
4953 } else {
4954 float typeVolume = mStreamTypes[track->streamType()].volume;
4955 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004956 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004957
Andy Hung10cbff12017-02-21 17:30:14 -08004958 // Get volumeshaper scaling
4959 std::pair<float /* volume */, bool /* active */>
4960 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004961 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004962 v *= vh.first;
4963 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004964
Glenn Kastenc56f3422014-03-21 17:53:17 -07004965 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4966 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4967 if (left > GAIN_FLOAT_UNITY) {
4968 left = GAIN_FLOAT_UNITY;
4969 }
4970 left *= v;
4971 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4972 if (right > GAIN_FLOAT_UNITY) {
4973 right = GAIN_FLOAT_UNITY;
4974 }
4975 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004976 }
4977
4978 if (lastTrack) {
4979 if (left != mLeftVolFloat || right != mRightVolFloat) {
4980 mLeftVolFloat = left;
4981 mRightVolFloat = right;
4982
4983 // Convert volumes from float to 8.24
4984 uint32_t vl = (uint32_t)(left * (1 << 24));
4985 uint32_t vr = (uint32_t)(right * (1 << 24));
4986
4987 // Delegate volume control to effect in track effect chain if needed
4988 // only one effect chain can be present on DirectOutputThread, so if
4989 // there is one, the track is connected to it
4990 if (!mEffectChains.isEmpty()) {
4991 mEffectChains[0]->setVolume_l(&vl, &vr);
4992 left = (float)vl / (1 << 24);
4993 right = (float)vr / (1 << 24);
4994 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004995 status_t result = mOutput->stream->setVolume(left, right);
4996 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004997 }
4998 }
4999}
5000
Phil Burk43b4dcc2015-06-09 16:53:44 -07005001void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5002{
5003 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005004 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005005
Eric Laurent0f0631e2015-07-06 18:01:25 -07005006 if (previousTrack != 0 && latestTrack != 0) {
5007 if (mType == DIRECT) {
5008 if (previousTrack.get() != latestTrack.get()) {
5009 mFlushPending = true;
5010 }
5011 } else /* mType == OFFLOAD */ {
5012 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5013 mFlushPending = true;
5014 }
5015 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005016 }
5017 PlaybackThread::onAddNewTrack_l();
5018}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005019
Eric Laurent81784c32012-11-19 14:55:58 -08005020AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5021 Vector< sp<Track> > *tracksToRemove
5022)
5023{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005024 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005025 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005026 bool doHwPause = false;
5027 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005028
5029 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005030 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005031 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005032 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005033 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005034 continue;
5035 }
5036
Eric Laurent5850c4c2016-11-10 13:04:31 -08005037 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005038#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005039 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005040#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005041 // Only consider last track started for volume and mixer state control.
5042 // In theory an older track could underrun and restart after the new one starts
5043 // but as we only care about the transition phase between two tracks on a
5044 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005045 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005046 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005047
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005048 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005049 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005050 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005051 doHwPause = true;
5052 mHwPaused = true;
5053 }
5054 tracksToRemove->add(track);
5055 } else if (track->isFlushPending()) {
5056 track->flushAck();
5057 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005058 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005059 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005060 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005061 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005062 if (last) {
5063 mLeftVolFloat = mRightVolFloat = -1.0;
5064 if (mHwPaused) {
5065 doHwResume = true;
5066 mHwPaused = false;
5067 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005068 }
5069 }
5070
Eric Laurent81784c32012-11-19 14:55:58 -08005071 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005072 // for all its buffers to be filled before processing it.
5073 // Allow draining the buffer in case the client
5074 // app does not call stop() and relies on underrun to stop:
5075 // hence the test on (track->mRetryCount > 1).
5076 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005077 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005078 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005079 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005080 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005081 minFrames = mNormalFrameCount;
5082 } else {
5083 minFrames = 1;
5084 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005085
Eric Laurentab5cdba2014-06-09 17:22:27 -07005086 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5087 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005088 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005089 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005090
5091 if (track->mFillingUpStatus == Track::FS_FILLED) {
5092 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005093 if (last) {
5094 // make sure processVolume_l() will apply new volume even if 0
5095 mLeftVolFloat = mRightVolFloat = -1.0;
5096 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005097 if (!mHwSupportsPause) {
5098 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005099 }
5100 }
5101
5102 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005103 processVolume_l(track, last);
5104 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005105 sp<Track> previousTrack = mPreviousTrack.promote();
5106 if (previousTrack != 0) {
5107 if (track != previousTrack.get()) {
5108 // Flush any data still being written from last track
5109 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005110 // Invalidate previous track to force a seek when resuming.
5111 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005112 }
5113 }
5114 mPreviousTrack = track;
5115
Eric Laurentd595b7c2013-04-03 17:27:56 -07005116 // reset retry count
5117 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005118 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005119 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005120 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005121 doHwResume = true;
5122 mHwPaused = false;
5123 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005124 }
Eric Laurent81784c32012-11-19 14:55:58 -08005125 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005126 // clear effect chain input buffer if the last active track started underruns
5127 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005128 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005129 mEffectChains[0]->clearInputBuffer();
5130 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005131 if (track->isStopping_1()) {
5132 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005133 if (last && mHwPaused) {
5134 doHwResume = true;
5135 mHwPaused = false;
5136 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005137 }
5138 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5139 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005140 // We have consumed all the buffers of this track.
5141 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005142 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005143 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005144 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5145 } else {
5146 audioHALFrames = 0;
5147 }
5148
Andy Hung818e7a32016-02-16 18:08:07 -08005149 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005150 if (mStandby || !last ||
5151 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005152 if (track->isStopping_2()) {
5153 track->mState = TrackBase::STOPPED;
5154 }
Eric Laurent81784c32012-11-19 14:55:58 -08005155 if (track->isStopped()) {
5156 track->reset();
5157 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005158 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005159 }
5160 } else {
5161 // No buffers for this track. Give it a few chances to
5162 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005163 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005164 if (--(track->mRetryCount) <= 0) {
5165 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005166 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005167 // indicate to client process that the track was disabled because of underrun;
5168 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005169 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005170 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005171 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5172 "minFrames = %u, mFormat = %#x",
5173 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005174 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005175 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005176 doHwPause = true;
5177 mHwPaused = true;
5178 }
Eric Laurent81784c32012-11-19 14:55:58 -08005179 }
5180 }
5181 }
5182 }
5183
Eric Laurentd1f69b02014-12-15 14:33:13 -08005184 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005185 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005186 for (size_t i = 0; i < mTracks.size(); i++) {
5187 if (mTracks[i]->isFlushPending()) {
5188 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005189 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005190 }
5191 }
5192 }
5193
5194 // make sure the pause/flush/resume sequence is executed in the right order.
5195 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5196 // before flush and then resume HW. This can happen in case of pause/flush/resume
5197 // if resume is received before pause is executed.
5198 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005199 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005200 status_t result = mOutput->stream->pause();
5201 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005202 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005203 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005204 flushHw_l();
5205 }
5206 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005207 status_t result = mOutput->stream->resume();
5208 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005209 }
Eric Laurent81784c32012-11-19 14:55:58 -08005210 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005211 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005212
5213 return mixerStatus;
5214}
5215
5216void AudioFlinger::DirectOutputThread::threadLoop_mix()
5217{
Eric Laurent81784c32012-11-19 14:55:58 -08005218 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005219 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005220 // output audio to hardware
5221 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005222 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005223 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005224 status_t status = mActiveTrack->getNextBuffer(&buffer);
5225 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005226 // no need to pad with 0 for compressed audio
5227 if (audio_has_proportional_frames(mFormat)) {
5228 memset(curBuf, 0, frameCount * mFrameSize);
5229 }
Eric Laurent81784c32012-11-19 14:55:58 -08005230 break;
5231 }
5232 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5233 frameCount -= buffer.frameCount;
5234 curBuf += buffer.frameCount * mFrameSize;
5235 mActiveTrack->releaseBuffer(&buffer);
5236 }
Andy Hung2098f272014-02-27 14:00:06 -08005237 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005238 mSleepTimeUs = 0;
5239 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005240 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005241}
5242
5243void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5244{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005245 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005246 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005247 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005248 return;
5249 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005250 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005251 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005252 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005253 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005254 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005255 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005256 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005257 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005258 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005259 }
5260}
5261
Eric Laurentd1f69b02014-12-15 14:33:13 -08005262void AudioFlinger::DirectOutputThread::threadLoop_exit()
5263{
5264 {
5265 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005266 for (size_t i = 0; i < mTracks.size(); i++) {
5267 if (mTracks[i]->isFlushPending()) {
5268 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005269 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005270 }
5271 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005272 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005273 flushHw_l();
5274 }
5275 }
5276 PlaybackThread::threadLoop_exit();
5277}
5278
5279// must be called with thread mutex locked
5280bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5281{
5282 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005283 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005284
vivek mehta9cd7ad12016-03-17 00:18:29 -07005285 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5286 return !mStandby;
5287 }
5288
Eric Laurentd1f69b02014-12-15 14:33:13 -08005289 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5290 // after a timeout and we will enter standby then.
5291 if (mTracks.size() > 0) {
5292 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005293 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5294 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005295 }
5296
Eric Laurent5cff4032015-05-26 13:49:58 -07005297 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005298}
5299
Eric Laurent81784c32012-11-19 14:55:58 -08005300// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005301int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005302 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005303{
Eric Laurentad7dd962016-09-22 12:38:37 -07005304 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5305 return -1;
5306 }
Eric Laurent81784c32012-11-19 14:55:58 -08005307 return 0;
5308}
5309
5310// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005311void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005312{
5313}
5314
Eric Laurent10351942014-05-08 18:49:52 -07005315// checkForNewParameter_l() must be called with ThreadBase::mLock held
5316bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5317 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005318{
5319 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005320 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005321
Eric Laurent10351942014-05-08 18:49:52 -07005322 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005323
Eric Laurent10351942014-05-08 18:49:52 -07005324 AudioParameter param = AudioParameter(keyValuePair);
5325 int value;
5326 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5327 // forward device change to effects that have requested to be
5328 // aware of attached audio device.
5329 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005330 a2dpDeviceChanged =
5331 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005332 mOutDevice = value;
5333 for (size_t i = 0; i < mEffectChains.size(); i++) {
5334 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005335 }
5336 }
Eric Laurent81784c32012-11-19 14:55:58 -08005337 }
Eric Laurent10351942014-05-08 18:49:52 -07005338 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5339 // do not accept frame count changes if tracks are open as the track buffer
5340 // size depends on frame count and correct behavior would not be garantied
5341 // if frame count is changed after track creation
5342 if (!mTracks.isEmpty()) {
5343 status = INVALID_OPERATION;
5344 } else {
5345 reconfig = true;
5346 }
5347 }
5348 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005349 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005350 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005351 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005352 mStandby = true;
5353 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005354 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005355 }
5356 if (status == NO_ERROR && reconfig) {
5357 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005358 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005359 }
5360 }
5361
Eric Laurent42537be2016-01-08 17:16:42 -08005362 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005363}
5364
5365uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5366{
5367 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005368 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005369 time = PlaybackThread::activeSleepTimeUs();
5370 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005371 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005372 }
5373 return time;
5374}
5375
5376uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5377{
5378 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005379 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005380 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5381 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005382 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005383 }
5384 return time;
5385}
5386
5387uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5388{
5389 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005390 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005391 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5392 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005393 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005394 }
5395 return time;
5396}
5397
5398void AudioFlinger::DirectOutputThread::cacheParameters_l()
5399{
5400 PlaybackThread::cacheParameters_l();
5401
5402 // use shorter standby delay as on normal output to release
5403 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005404 // no delay on outputs with HW A/V sync
5405 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005406 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005407 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005408 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005409 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005410 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005411 }
Eric Laurent81784c32012-11-19 14:55:58 -08005412}
5413
Eric Laurente659ef42014-09-29 13:06:46 -07005414void AudioFlinger::DirectOutputThread::flushHw_l()
5415{
Phil Burk062e67a2015-02-11 13:40:50 -08005416 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005417 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005418 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005419}
5420
Andy Hung10cbff12017-02-21 17:30:14 -08005421int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5422 // If a VolumeShaper is active, we must wake up periodically to update volume.
5423 const int64_t NS_PER_MS = 1000000;
5424 return mVolumeShaperActive ?
5425 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5426}
5427
Eric Laurent81784c32012-11-19 14:55:58 -08005428// ----------------------------------------------------------------------------
5429
Eric Laurentbfb1b832013-01-07 09:53:42 -08005430AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005431 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005433 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005434 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005435 mDrainSequence(0),
5436 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005437{
5438}
5439
5440AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5441{
5442}
5443
5444void AudioFlinger::AsyncCallbackThread::onFirstRef()
5445{
5446 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5447}
5448
5449bool AudioFlinger::AsyncCallbackThread::threadLoop()
5450{
5451 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005452 uint32_t writeAckSequence;
5453 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005454 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005455
5456 {
5457 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005458 while (!((mWriteAckSequence & 1) ||
5459 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005460 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005461 exitPending())) {
5462 mWaitWorkCV.wait(mLock);
5463 }
5464
Eric Laurentbfb1b832013-01-07 09:53:42 -08005465 if (exitPending()) {
5466 break;
5467 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005468 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5469 mWriteAckSequence, mDrainSequence);
5470 writeAckSequence = mWriteAckSequence;
5471 mWriteAckSequence &= ~1;
5472 drainSequence = mDrainSequence;
5473 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005474 asyncError = mAsyncError;
5475 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005476 }
5477 {
Eric Laurent4de95592013-09-26 15:28:21 -07005478 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5479 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005480 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005481 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005483 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005484 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005485 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005486 if (asyncError) {
5487 playbackThread->onAsyncError();
5488 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005489 }
5490 }
5491 }
5492 return false;
5493}
5494
5495void AudioFlinger::AsyncCallbackThread::exit()
5496{
5497 ALOGV("AsyncCallbackThread::exit");
5498 Mutex::Autolock _l(mLock);
5499 requestExit();
5500 mWaitWorkCV.broadcast();
5501}
5502
Eric Laurent3b4529e2013-09-05 18:09:19 -07005503void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005504{
5505 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005506 // bit 0 is cleared
5507 mWriteAckSequence = sequence << 1;
5508}
5509
5510void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5511{
5512 Mutex::Autolock _l(mLock);
5513 // ignore unexpected callbacks
5514 if (mWriteAckSequence & 2) {
5515 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005516 mWaitWorkCV.signal();
5517 }
5518}
5519
Eric Laurent3b4529e2013-09-05 18:09:19 -07005520void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005521{
5522 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005523 // bit 0 is cleared
5524 mDrainSequence = sequence << 1;
5525}
5526
5527void AudioFlinger::AsyncCallbackThread::resetDraining()
5528{
5529 Mutex::Autolock _l(mLock);
5530 // ignore unexpected callbacks
5531 if (mDrainSequence & 2) {
5532 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005533 mWaitWorkCV.signal();
5534 }
5535}
5536
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005537void AudioFlinger::AsyncCallbackThread::setAsyncError()
5538{
5539 Mutex::Autolock _l(mLock);
5540 mAsyncError = true;
5541 mWaitWorkCV.signal();
5542}
5543
Eric Laurentbfb1b832013-01-07 09:53:42 -08005544
5545// ----------------------------------------------------------------------------
5546AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005547 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5548 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005549 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5550 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005551{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005552 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005553 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005554 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005555}
5556
Eric Laurentbfb1b832013-01-07 09:53:42 -08005557void AudioFlinger::OffloadThread::threadLoop_exit()
5558{
5559 if (mFlushPending || mHwPaused) {
5560 // If a flush is pending or track was paused, just discard buffered data
5561 flushHw_l();
5562 } else {
5563 mMixerStatus = MIXER_DRAIN_ALL;
5564 threadLoop_drain();
5565 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005566 if (mUseAsyncWrite) {
5567 ALOG_ASSERT(mCallbackThread != 0);
5568 mCallbackThread->exit();
5569 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005570 PlaybackThread::threadLoop_exit();
5571}
5572
5573AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5574 Vector< sp<Track> > *tracksToRemove
5575)
5576{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005577 size_t count = mActiveTracks.size();
5578
5579 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005580 bool doHwPause = false;
5581 bool doHwResume = false;
5582
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005583 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005584
Eric Laurentbfb1b832013-01-07 09:53:42 -08005585 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005586 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005587 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005588#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005589 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005590#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005591 // Only consider last track started for volume and mixer state control.
5592 // In theory an older track could underrun and restart after the new one starts
5593 // but as we only care about the transition phase between two tracks on a
5594 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005595 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005596 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005597
Haynes Mathew George7844f672014-01-15 12:32:55 -08005598 if (track->isInvalid()) {
5599 ALOGW("An invalidated track shouldn't be in active list");
5600 tracksToRemove->add(track);
5601 continue;
5602 }
5603
5604 if (track->mState == TrackBase::IDLE) {
5605 ALOGW("An idle track shouldn't be in active list");
5606 continue;
5607 }
5608
Eric Laurentbfb1b832013-01-07 09:53:42 -08005609 if (track->isPausing()) {
5610 track->setPaused();
5611 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005612 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005613 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005614 mHwPaused = true;
5615 }
5616 // If we were part way through writing the mixbuffer to
5617 // the HAL we must save this until we resume
5618 // BUG - this will be wrong if a different track is made active,
5619 // in that case we want to discard the pending data in the
5620 // mixbuffer and tell the client to present it again when the
5621 // track is resumed
5622 mPausedWriteLength = mCurrentWriteLength;
5623 mPausedBytesRemaining = mBytesRemaining;
5624 mBytesRemaining = 0; // stop writing
5625 }
5626 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005627 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005628 if (track->isStopping_1()) {
5629 track->mRetryCount = kMaxTrackStopRetriesOffload;
5630 } else {
5631 track->mRetryCount = kMaxTrackRetriesOffload;
5632 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005633 track->flushAck();
5634 if (last) {
5635 mFlushPending = true;
5636 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005637 } else if (track->isResumePending()){
5638 track->resumeAck();
5639 if (last) {
5640 if (mPausedBytesRemaining) {
5641 // Need to continue write that was interrupted
5642 mCurrentWriteLength = mPausedWriteLength;
5643 mBytesRemaining = mPausedBytesRemaining;
5644 mPausedBytesRemaining = 0;
5645 }
5646 if (mHwPaused) {
5647 doHwResume = true;
5648 mHwPaused = false;
5649 // threadLoop_mix() will handle the case that we need to
5650 // resume an interrupted write
5651 }
5652 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005653 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005654
Eric Laurent3df841a2016-07-15 15:15:40 -07005655 mLeftVolFloat = mRightVolFloat = -1.0;
5656
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005657 // Do not handle new data in this iteration even if track->framesReady()
5658 mixerStatus = MIXER_TRACKS_ENABLED;
5659 }
5660 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005661 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005662 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005663 if (track->mFillingUpStatus == Track::FS_FILLED) {
5664 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005665 if (last) {
5666 // make sure processVolume_l() will apply new volume even if 0
5667 mLeftVolFloat = mRightVolFloat = -1.0;
5668 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005669 }
5670
5671 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005672 sp<Track> previousTrack = mPreviousTrack.promote();
5673 if (previousTrack != 0) {
5674 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005675 // Flush any data still being written from last track
5676 mBytesRemaining = 0;
5677 if (mPausedBytesRemaining) {
5678 // Last track was paused so we also need to flush saved
5679 // mixbuffer state and invalidate track so that it will
5680 // re-submit that unwritten data when it is next resumed
5681 mPausedBytesRemaining = 0;
5682 // Invalidate is a bit drastic - would be more efficient
5683 // to have a flag to tell client that some of the
5684 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005685 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005686 }
5687 // flush data already sent to the DSP if changing audio session as audio
5688 // comes from a different source. Also invalidate previous track to force a
5689 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005690 if (previousTrack->sessionId() != track->sessionId()) {
5691 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005692 }
5693 }
5694 }
5695 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005696 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005697 if (track->isStopping_1()) {
5698 track->mRetryCount = kMaxTrackStopRetriesOffload;
5699 } else {
5700 track->mRetryCount = kMaxTrackRetriesOffload;
5701 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005702 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005703 mixerStatus = MIXER_TRACKS_READY;
5704 }
5705 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005706 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005707 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005708 if (--(track->mRetryCount) <= 0) {
5709 // Hardware buffer can hold a large amount of audio so we must
5710 // wait for all current track's data to drain before we say
5711 // that the track is stopped.
5712 if (mBytesRemaining == 0) {
5713 // Only start draining when all data in mixbuffer
5714 // has been written
5715 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5716 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5717 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5718 if (last && !mStandby) {
5719 // do not modify drain sequence if we are already draining. This happens
5720 // when resuming from pause after drain.
5721 if ((mDrainSequence & 1) == 0) {
5722 mSleepTimeUs = 0;
5723 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5724 mixerStatus = MIXER_DRAIN_TRACK;
5725 mDrainSequence += 2;
5726 }
5727 if (mHwPaused) {
5728 // It is possible to move from PAUSED to STOPPING_1 without
5729 // a resume so we must ensure hardware is running
5730 doHwResume = true;
5731 mHwPaused = false;
5732 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005733 }
5734 }
Eric Laurente93cc032016-05-05 10:15:10 -07005735 } else if (last) {
5736 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5737 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005738 }
5739 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005740 // Drain has completed or we are in standby, signal presentation complete
5741 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005742 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005743 uint32_t latency = 0;
5744 status_t result = mOutput->stream->getLatency(&latency);
5745 ALOGE_IF(result != OK,
5746 "Error when retrieving output stream latency: %d", result);
5747 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005748 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005749 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005750 track->presentationComplete(framesWritten, audioHALFrames);
5751 track->reset();
5752 tracksToRemove->add(track);
5753 }
5754 } else {
5755 // No buffers for this track. Give it a few chances to
5756 // fill a buffer, then remove it from active list.
5757 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005758 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005759 uint64_t position = 0;
5760 struct timespec unused;
5761 // The running check restarts the retry counter at least once.
5762 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5763 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5764 running = true;
5765 mOffloadUnderrunPosition = position;
5766 }
5767 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005768 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5769 (long long)position, (long long)mOffloadUnderrunPosition);
5770 }
5771 if (running) { // still running, give us more time.
5772 track->mRetryCount = kMaxTrackRetriesOffload;
5773 } else {
5774 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5775 track->name());
5776 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005777 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005778 // it will then automatically call start() when data is available
5779 track->disable();
5780 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005781 } else if (last){
5782 mixerStatus = MIXER_TRACKS_ENABLED;
5783 }
5784 }
5785 }
5786 // compute volume for this track
5787 processVolume_l(track, last);
5788 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005789
Eric Laurentea0fade2013-10-04 16:23:48 -07005790 // make sure the pause/flush/resume sequence is executed in the right order.
5791 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5792 // before flush and then resume HW. This can happen in case of pause/flush/resume
5793 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005794 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005795 status_t result = mOutput->stream->pause();
5796 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005797 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005798 if (mFlushPending) {
5799 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005800 }
Eric Laurentfd477972013-10-25 18:10:40 -07005801 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005802 status_t result = mOutput->stream->resume();
5803 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005804 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005805
Eric Laurentbfb1b832013-01-07 09:53:42 -08005806 // remove all the tracks that need to be...
5807 removeTracks_l(*tracksToRemove);
5808
5809 return mixerStatus;
5810}
5811
Eric Laurentbfb1b832013-01-07 09:53:42 -08005812// must be called with thread mutex locked
5813bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5814{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005815 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5816 mWriteAckSequence, mDrainSequence);
5817 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005818 return true;
5819 }
5820 return false;
5821}
5822
Eric Laurentbfb1b832013-01-07 09:53:42 -08005823bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5824{
5825 Mutex::Autolock _l(mLock);
5826 return waitingAsyncCallback_l();
5827}
5828
5829void AudioFlinger::OffloadThread::flushHw_l()
5830{
Eric Laurente659ef42014-09-29 13:06:46 -07005831 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005832 // Flush anything still waiting in the mixbuffer
5833 mCurrentWriteLength = 0;
5834 mBytesRemaining = 0;
5835 mPausedWriteLength = 0;
5836 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005837 // reset bytes written count to reflect that DSP buffers are empty after flush.
5838 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005839 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005840
Eric Laurentbfb1b832013-01-07 09:53:42 -08005841 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005842 // discard any pending drain or write ack by incrementing sequence
5843 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5844 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005845 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005846 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5847 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005848 }
5849}
5850
Haynes Mathew George05317d22016-05-03 16:34:26 -07005851void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5852{
5853 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005854 if (PlaybackThread::invalidateTracks_l(streamType)) {
5855 mFlushPending = true;
5856 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005857}
5858
Eric Laurentbfb1b832013-01-07 09:53:42 -08005859// ----------------------------------------------------------------------------
5860
Eric Laurent81784c32012-11-19 14:55:58 -08005861AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005862 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005863 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005864 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005865 mWaitTimeMs(UINT_MAX)
5866{
5867 addOutputTrack(mainThread);
5868}
5869
5870AudioFlinger::DuplicatingThread::~DuplicatingThread()
5871{
5872 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5873 mOutputTracks[i]->destroy();
5874 }
5875}
5876
5877void AudioFlinger::DuplicatingThread::threadLoop_mix()
5878{
5879 // mix buffers...
5880 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005881 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005882 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005883 if (mMixerBufferValid) {
5884 memset(mMixerBuffer, 0, mMixerBufferSize);
5885 } else {
5886 memset(mSinkBuffer, 0, mSinkBufferSize);
5887 }
Eric Laurent81784c32012-11-19 14:55:58 -08005888 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005889 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005890 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005891 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005892 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005893}
5894
5895void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5896{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005897 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005898 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005899 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005900 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005901 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005902 }
5903 } else if (mBytesWritten != 0) {
5904 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5905 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005906 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005907 } else {
5908 // flush remaining overflow buffers in output tracks
5909 writeFrames = 0;
5910 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005911 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005912 }
5913}
5914
Eric Laurentbfb1b832013-01-07 09:53:42 -08005915ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005916{
5917 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005918 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005919 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005920 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005921 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005922}
5923
5924void AudioFlinger::DuplicatingThread::threadLoop_standby()
5925{
5926 // DuplicatingThread implements standby by stopping all tracks
5927 for (size_t i = 0; i < outputTracks.size(); i++) {
5928 outputTracks[i]->stop();
5929 }
5930}
5931
5932void AudioFlinger::DuplicatingThread::saveOutputTracks()
5933{
5934 outputTracks = mOutputTracks;
5935}
5936
5937void AudioFlinger::DuplicatingThread::clearOutputTracks()
5938{
5939 outputTracks.clear();
5940}
5941
5942void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5943{
5944 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005945 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5946 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5947 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5948 const size_t frameCount =
5949 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5950 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5951 // from different OutputTracks and their associated MixerThreads (e.g. one may
5952 // nearly empty and the other may be dropping data).
5953
5954 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005955 this,
5956 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005957 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005958 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005959 frameCount,
5960 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005961 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5962 if (status != NO_ERROR) {
5963 ALOGE("addOutputTrack() initCheck failed %d", status);
5964 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005965 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005966 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5967 mOutputTracks.add(outputTrack);
5968 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5969 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005970}
5971
5972void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5973{
5974 Mutex::Autolock _l(mLock);
5975 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5976 if (mOutputTracks[i]->thread() == thread) {
5977 mOutputTracks[i]->destroy();
5978 mOutputTracks.removeAt(i);
5979 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005980 if (thread->getOutput() == mOutput) {
5981 mOutput = NULL;
5982 }
Eric Laurent81784c32012-11-19 14:55:58 -08005983 return;
5984 }
5985 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005986 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005987}
5988
5989// caller must hold mLock
5990void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5991{
5992 mWaitTimeMs = UINT_MAX;
5993 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5994 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5995 if (strong != 0) {
5996 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5997 if (waitTimeMs < mWaitTimeMs) {
5998 mWaitTimeMs = waitTimeMs;
5999 }
6000 }
6001 }
6002}
6003
6004
6005bool AudioFlinger::DuplicatingThread::outputsReady(
6006 const SortedVector< sp<OutputTrack> > &outputTracks)
6007{
6008 for (size_t i = 0; i < outputTracks.size(); i++) {
6009 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6010 if (thread == 0) {
6011 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6012 outputTracks[i].get());
6013 return false;
6014 }
6015 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6016 // see note at standby() declaration
6017 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6018 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6019 thread.get());
6020 return false;
6021 }
6022 }
6023 return true;
6024}
6025
6026uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6027{
6028 return (mWaitTimeMs * 1000) / 2;
6029}
6030
6031void AudioFlinger::DuplicatingThread::cacheParameters_l()
6032{
6033 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6034 updateWaitTime_l();
6035
6036 MixerThread::cacheParameters_l();
6037}
6038
Eric Laurent6acd1d42017-01-04 14:23:29 -08006039
Eric Laurent81784c32012-11-19 14:55:58 -08006040// ----------------------------------------------------------------------------
6041// Record
6042// ----------------------------------------------------------------------------
6043
6044AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6045 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006046 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006047 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006048 audio_devices_t inDevice,
6049 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006050#ifdef TEE_SINK
6051 , const sp<NBAIO_Sink>& teeSink
6052#endif
6053 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006054 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006055 mInput(input),
6056 mActiveTracks(&this->mLocalLog),
6057 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006058 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006059 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08006060#ifdef TEE_SINK
6061 , mTeeSink(teeSink)
6062#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006063 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6064 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006065 // mFastCapture below
6066 , mFastCaptureFutex(0)
6067 // mInputSource
6068 // mPipeSink
6069 // mPipeSource
6070 , mPipeFramesP2(0)
6071 // mPipeMemory
6072 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006073 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006074 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006075{
Glenn Kastend7dca052015-03-05 16:05:54 -08006076 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6077 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006078
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006079 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006080
6081 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006082 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006083 size_t numCounterOffers = 0;
6084 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006085#if !LOG_NDEBUG
6086 ssize_t index =
6087#else
6088 (void)
6089#endif
6090 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006091 ALOG_ASSERT(index == 0);
6092
6093 // initialize fast capture depending on configuration
6094 bool initFastCapture;
6095 switch (kUseFastCapture) {
6096 case FastCapture_Never:
6097 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006098 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006099 break;
6100 case FastCapture_Always:
6101 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006102 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006103 break;
6104 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006105 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006106 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6107 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6108 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006109 break;
6110 // case FastCapture_Dynamic:
6111 }
6112
6113 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006114 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006115 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006116 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6117 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006118 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006119 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006120 const sp<MemoryDealer> roHeap(readOnlyHeap());
6121 sp<IMemory> pipeMemory;
6122 if ((roHeap == 0) ||
6123 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006124 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6125 ALOGE("not enough memory for pipe buffer size=%zu; "
6126 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6127 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6128 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006129 goto failed;
6130 }
6131 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6132 memset(pipeBuffer, 0, pipeSize);
6133 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6134 const NBAIO_Format offers[1] = {format};
6135 size_t numCounterOffers = 0;
6136 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6137 ALOG_ASSERT(index == 0);
6138 mPipeSink = pipe;
6139 PipeReader *pipeReader = new PipeReader(*pipe);
6140 numCounterOffers = 0;
6141 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6142 ALOG_ASSERT(index == 0);
6143 mPipeSource = pipeReader;
6144 mPipeFramesP2 = pipeFramesP2;
6145 mPipeMemory = pipeMemory;
6146
6147 // create fast capture
6148 mFastCapture = new FastCapture();
6149 FastCaptureStateQueue *sq = mFastCapture->sq();
6150#ifdef STATE_QUEUE_DUMP
6151 // FIXME
6152#endif
6153 FastCaptureState *state = sq->begin();
6154 state->mCblk = NULL;
6155 state->mInputSource = mInputSource.get();
6156 state->mInputSourceGen++;
6157 state->mPipeSink = pipe;
6158 state->mPipeSinkGen++;
6159 state->mFrameCount = mFrameCount;
6160 state->mCommand = FastCaptureState::COLD_IDLE;
6161 // already done in constructor initialization list
6162 //mFastCaptureFutex = 0;
6163 state->mColdFutexAddr = &mFastCaptureFutex;
6164 state->mColdGen++;
6165 state->mDumpState = &mFastCaptureDumpState;
6166#ifdef TEE_SINK
6167 // FIXME
6168#endif
6169 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6170 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6171 sq->end();
6172 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6173
6174 // start the fast capture
6175 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6176 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006177 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006178 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006179#ifdef AUDIO_WATCHDOG
6180 // FIXME
6181#endif
6182
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006183 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006184 }
6185failed: ;
6186
6187 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006188}
6189
Eric Laurent81784c32012-11-19 14:55:58 -08006190AudioFlinger::RecordThread::~RecordThread()
6191{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006192 if (mFastCapture != 0) {
6193 FastCaptureStateQueue *sq = mFastCapture->sq();
6194 FastCaptureState *state = sq->begin();
6195 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6196 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6197 if (old == -1) {
6198 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6199 }
6200 }
6201 state->mCommand = FastCaptureState::EXIT;
6202 sq->end();
6203 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6204 mFastCapture->join();
6205 mFastCapture.clear();
6206 }
6207 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006208 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006209 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006210}
6211
6212void AudioFlinger::RecordThread::onFirstRef()
6213{
Glenn Kastend7dca052015-03-05 16:05:54 -08006214 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006215}
6216
Eric Laurent555530a2017-02-07 18:17:24 -08006217void AudioFlinger::RecordThread::preExit()
6218{
6219 ALOGV(" preExit()");
6220 Mutex::Autolock _l(mLock);
6221 for (size_t i = 0; i < mTracks.size(); i++) {
6222 sp<RecordTrack> track = mTracks[i];
6223 track->invalidate();
6224 }
6225 mActiveTracks.clear();
6226 mStartStopCond.broadcast();
6227}
6228
Eric Laurent81784c32012-11-19 14:55:58 -08006229bool AudioFlinger::RecordThread::threadLoop()
6230{
Eric Laurent81784c32012-11-19 14:55:58 -08006231 nsecs_t lastWarning = 0;
6232
6233 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006234
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006235reacquire_wakelock:
6236 sp<RecordTrack> activeTrack;
6237 {
6238 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006239 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006240 }
6241
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006242 // used to request a deferred sleep, to be executed later while mutex is unlocked
6243 uint32_t sleepUs = 0;
6244
6245 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006246 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006247 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006248
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006249 // activeTracks accumulates a copy of a subset of mActiveTracks
6250 Vector< sp<RecordTrack> > activeTracks;
6251
Glenn Kasten735f45f2014-08-18 15:51:59 -07006252 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006253 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006254
Glenn Kasten735f45f2014-08-18 15:51:59 -07006255 // reference to a fast track which is about to be removed
6256 sp<RecordTrack> fastTrackToRemove;
6257
Eric Laurent81784c32012-11-19 14:55:58 -08006258 { // scope for mLock
6259 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006260
Eric Laurent021cf962014-05-13 10:18:14 -07006261 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006262
Eric Laurent000a4192014-01-29 15:17:32 -08006263 // check exitPending here because checkForNewParameters_l() and
6264 // checkForNewParameters_l() can temporarily release mLock
6265 if (exitPending()) {
6266 break;
6267 }
6268
Eric Laurent5c25d562016-07-13 17:17:45 -07006269 // sleep with mutex unlocked
6270 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006271 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006272 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6273 ATRACE_END();
6274 sleepUs = 0;
6275 continue;
6276 }
6277
Glenn Kasten2b806402013-11-20 16:37:38 -08006278 // if no active track(s), then standby and release wakelock
6279 size_t size = mActiveTracks.size();
6280 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006281 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006282 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006283 releaseWakeLock_l();
6284 ALOGV("RecordThread: loop stopping");
6285 // go to sleep
6286 mWaitWorkCV.wait(mLock);
6287 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006288 goto reacquire_wakelock;
6289 }
6290
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006291 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006292 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006293 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006294
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006295 activeTrack = mActiveTracks[i];
6296 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006297 if (activeTrack->isFastTrack()) {
6298 ALOG_ASSERT(fastTrackToRemove == 0);
6299 fastTrackToRemove = activeTrack;
6300 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006301 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006302 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006303 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006304 continue;
6305 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006306
6307 TrackBase::track_state activeTrackState = activeTrack->mState;
6308 switch (activeTrackState) {
6309
6310 case TrackBase::PAUSING:
6311 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006312 doBroadcast = true;
6313 size--;
6314 continue;
6315
6316 case TrackBase::STARTING_1:
6317 sleepUs = 10000;
6318 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006319 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006320 continue;
6321
6322 case TrackBase::STARTING_2:
6323 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006324 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006325 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006326 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006327 break;
6328
6329 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006330 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006331 break;
6332
6333 case TrackBase::IDLE:
6334 i++;
6335 continue;
6336
6337 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006338 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006339 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006340
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006341 activeTracks.add(activeTrack);
6342 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006343
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006344 if (activeTrack->isFastTrack()) {
6345 ALOG_ASSERT(!mFastTrackAvail);
6346 ALOG_ASSERT(fastTrack == 0);
6347 fastTrack = activeTrack;
6348 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006349 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006350
Andy Hungdae27702016-10-31 14:01:16 -07006351 mActiveTracks.updatePowerState(this);
6352
Eric Laurent5c25d562016-07-13 17:17:45 -07006353 if (allStopped) {
6354 standbyIfNotAlreadyInStandby();
6355 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006356 if (doBroadcast) {
6357 mStartStopCond.broadcast();
6358 }
6359
6360 // sleep if there are no active tracks to process
6361 if (activeTracks.size() == 0) {
6362 if (sleepUs == 0) {
6363 sleepUs = kRecordThreadSleepUs;
6364 }
6365 continue;
6366 }
6367 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006368
Eric Laurent81784c32012-11-19 14:55:58 -08006369 lockEffectChains_l(effectChains);
6370 }
6371
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006372 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006373
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006374 size_t size = effectChains.size();
6375 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006376 // thread mutex is not locked, but effect chain is locked
6377 effectChains[i]->process_l();
6378 }
6379
Glenn Kasten735f45f2014-08-18 15:51:59 -07006380 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006381 if (mFastCapture != 0) {
6382 FastCaptureStateQueue *sq = mFastCapture->sq();
6383 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006384 bool didModify = false;
6385 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006386 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6387 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6388 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6389 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6390 if (old == -1) {
6391 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6392 }
6393 }
6394 state->mCommand = FastCaptureState::READ_WRITE;
6395#if 0 // FIXME
6396 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006397 FastThreadDumpState::kSamplingNforLowRamDevice :
6398 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006399#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006400 didModify = true;
6401 }
6402 audio_track_cblk_t *cblkOld = state->mCblk;
6403 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6404 if (cblkNew != cblkOld) {
6405 state->mCblk = cblkNew;
6406 // block until acked if removing a fast track
6407 if (cblkOld != NULL) {
6408 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6409 }
6410 didModify = true;
6411 }
6412 sq->end(didModify);
6413 if (didModify) {
6414 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006415#if 0
6416 if (kUseFastCapture == FastCapture_Dynamic) {
6417 mNormalSource = mPipeSource;
6418 }
6419#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006420 }
6421 }
6422
Glenn Kasten735f45f2014-08-18 15:51:59 -07006423 // now run the fast track destructor with thread mutex unlocked
6424 fastTrackToRemove.clear();
6425
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006426 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6427 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6428 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6429 // If destination is non-contiguous, first read past the nominal end of buffer, then
6430 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006431
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006432 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006433 ssize_t framesRead;
6434
6435 // If an NBAIO source is present, use it to read the normal capture's data
6436 if (mPipeSource != 0) {
6437 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006438 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006439 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006440 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006441 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6442 // buffer size or at least for 20ms.
6443 size_t sleepFrames = max(
6444 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6445 if (framesRead <= (ssize_t) sleepFrames) {
6446 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6447 }
6448 if (framesRead < 0) {
6449 status_t status = (status_t) framesRead;
6450 switch (status) {
6451 case OVERRUN:
6452 ALOGW("overrun on read from pipe");
6453 framesRead = 0;
6454 break;
6455 case NEGOTIATE:
6456 ALOGE("re-negotiation is needed");
6457 framesRead = -1; // Will cause an attempt to recover.
6458 break;
6459 default:
6460 ALOGE("unknown error %d on read from pipe", status);
6461 break;
6462 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006463 }
6464 // otherwise use the HAL / AudioStreamIn directly
6465 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006466 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006467 size_t bytesRead;
6468 status_t result = mInput->stream->read(
6469 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006470 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006471 if (result < 0) {
6472 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006473 } else {
6474 framesRead = bytesRead / mFrameSize;
6475 }
6476 }
6477
Andy Hung3f0c9022016-01-15 17:49:46 -08006478 // Update server timestamp with server stats
6479 // systemTime() is optional if the hardware supports timestamps.
6480 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6481 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6482
6483 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006484 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006485 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006486 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006487 if (ret == NO_ERROR) {
6488 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6489 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6490 // Note: In general record buffers should tend to be empty in
6491 // a properly running pipeline.
6492 //
6493 // Also, it is not advantageous to call get_presentation_position during the read
6494 // as the read obtains a lock, preventing the timestamp call from executing.
6495 }
6496 }
6497 // Use this to track timestamp information
6498 // ALOGD("%s", mTimestamp.toString().c_str());
6499
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006500 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006501 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006502 // Force input into standby so that it tries to recover at next read attempt
6503 inputStandBy();
6504 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006505 }
6506 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006507 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006508 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006509 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006510
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006511 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006512 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006513 }
6514 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006515 {
6516 size_t part1 = mRsmpInFramesP2 - rear;
6517 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006518 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006519 (framesRead - part1) * mFrameSize);
6520 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006521 }
6522 rear = mRsmpInRear += framesRead;
6523
6524 size = activeTracks.size();
6525 // loop over each active track
6526 for (size_t i = 0; i < size; i++) {
6527 activeTrack = activeTracks[i];
6528
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006529 // skip fast tracks, as those are handled directly by FastCapture
6530 if (activeTrack->isFastTrack()) {
6531 continue;
6532 }
6533
Andy Hung73c02e42015-03-29 01:13:58 -07006534 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006535 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6536
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006537 enum {
6538 OVERRUN_UNKNOWN,
6539 OVERRUN_TRUE,
6540 OVERRUN_FALSE
6541 } overrun = OVERRUN_UNKNOWN;
6542
6543 // loop over getNextBuffer to handle circular sink
6544 for (;;) {
6545
6546 activeTrack->mSink.frameCount = ~0;
6547 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6548 size_t framesOut = activeTrack->mSink.frameCount;
6549 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6550
Andy Hung73c02e42015-03-29 01:13:58 -07006551 // check available frames and handle overrun conditions
6552 // if the record track isn't draining fast enough.
6553 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006554 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006555 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6556 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006557 overrun = OVERRUN_TRUE;
6558 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006559 if (framesOut == 0 || framesIn == 0) {
6560 break;
6561 }
6562
Andy Hung6770c6f2015-04-07 13:43:36 -07006563 // Don't allow framesOut to be larger than what is possible with resampling
6564 // from framesIn.
6565 // This isn't strictly necessary but helps limit buffer resizing in
6566 // RecordBufferConverter. TODO: remove when no longer needed.
6567 framesOut = min(framesOut,
6568 destinationFramesPossible(
6569 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006570 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6571 framesOut = activeTrack->mRecordBufferConverter->convert(
6572 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006573
6574 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6575 overrun = OVERRUN_FALSE;
6576 }
6577
6578 if (activeTrack->mFramesToDrop == 0) {
6579 if (framesOut > 0) {
6580 activeTrack->mSink.frameCount = framesOut;
6581 activeTrack->releaseBuffer(&activeTrack->mSink);
6582 }
6583 } else {
6584 // FIXME could do a partial drop of framesOut
6585 if (activeTrack->mFramesToDrop > 0) {
6586 activeTrack->mFramesToDrop -= framesOut;
6587 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006588 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006589 }
6590 } else {
6591 activeTrack->mFramesToDrop += framesOut;
6592 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6593 activeTrack->mSyncStartEvent->isCancelled()) {
6594 ALOGW("Synced record %s, session %d, trigger session %d",
6595 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6596 activeTrack->sessionId(),
6597 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006598 activeTrack->mSyncStartEvent->triggerSession() :
6599 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006600 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006601 }
6602 }
6603 }
6604
6605 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006606 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006607 }
6608 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006609
6610 switch (overrun) {
6611 case OVERRUN_TRUE:
6612 // client isn't retrieving buffers fast enough
6613 if (!activeTrack->setOverflow()) {
6614 nsecs_t now = systemTime();
6615 // FIXME should lastWarning per track?
6616 if ((now - lastWarning) > kWarningThrottleNs) {
6617 ALOGW("RecordThread: buffer overflow");
6618 lastWarning = now;
6619 }
6620 }
6621 break;
6622 case OVERRUN_FALSE:
6623 activeTrack->clearOverflow();
6624 break;
6625 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006626 break;
6627 }
6628
Andy Hung3f0c9022016-01-15 17:49:46 -08006629 // update frame information and push timestamp out
6630 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006631 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006632 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6633 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006634 }
6635
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006636unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006637 // enable changes in effect chain
6638 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006639 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006640 }
6641
Glenn Kasten93e471f2013-08-19 08:40:07 -07006642 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006643
6644 {
6645 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006646 for (size_t i = 0; i < mTracks.size(); i++) {
6647 sp<RecordTrack> track = mTracks[i];
6648 track->invalidate();
6649 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006650 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006651 mStartStopCond.broadcast();
6652 }
6653
6654 releaseWakeLock();
6655
6656 ALOGV("RecordThread %p exiting", this);
6657 return false;
6658}
6659
Glenn Kasten93e471f2013-08-19 08:40:07 -07006660void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006661{
6662 if (!mStandby) {
6663 inputStandBy();
6664 mStandby = true;
6665 }
6666}
6667
6668void AudioFlinger::RecordThread::inputStandBy()
6669{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006670 // Idle the fast capture if it's currently running
6671 if (mFastCapture != 0) {
6672 FastCaptureStateQueue *sq = mFastCapture->sq();
6673 FastCaptureState *state = sq->begin();
6674 if (!(state->mCommand & FastCaptureState::IDLE)) {
6675 state->mCommand = FastCaptureState::COLD_IDLE;
6676 state->mColdFutexAddr = &mFastCaptureFutex;
6677 state->mColdGen++;
6678 mFastCaptureFutex = 0;
6679 sq->end();
6680 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6681 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6682#if 0
6683 if (kUseFastCapture == FastCapture_Dynamic) {
6684 // FIXME
6685 }
6686#endif
6687#ifdef AUDIO_WATCHDOG
6688 // FIXME
6689#endif
6690 } else {
6691 sq->end(false /*didModify*/);
6692 }
6693 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006694 status_t result = mInput->stream->standby();
6695 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006696
6697 // If going into standby, flush the pipe source.
6698 if (mPipeSource.get() != nullptr) {
6699 const ssize_t flushed = mPipeSource->flush();
6700 if (flushed > 0) {
6701 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6702 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6703 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6704 }
6705 }
Eric Laurent81784c32012-11-19 14:55:58 -08006706}
6707
Glenn Kasten05997e22014-03-13 15:08:33 -07006708// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006709sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006710 const sp<AudioFlinger::Client>& client,
Eric Laurent0aa3c6e2017-12-08 18:13:22 +00006711 uint32_t sampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08006712 audio_format_t format,
6713 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006714 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006715 audio_session_t sessionId,
Eric Laurent0aa3c6e2017-12-08 18:13:22 +00006716 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006717 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006718 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006719 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006720 status_t *status,
6721 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006722{
Glenn Kasten74935e42013-12-19 08:56:45 -08006723 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006724 sp<RecordTrack> track;
6725 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006726 audio_input_flags_t inputFlags = mInput->flags;
6727
6728 // special case for FAST flag considered OK if fast capture is present
6729 if (hasFastCapture()) {
6730 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6731 }
6732
Eric Laurent0aa3c6e2017-12-08 18:13:22 +00006733 // Check if requested flags are compatible with output stream flags
Eric Laurent05067782016-06-01 18:27:28 -07006734 if ((*flags & inputFlags) != *flags) {
6735 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6736 " input flags (%08x)",
6737 *flags, inputFlags);
6738 *flags = (audio_input_flags_t)(*flags & inputFlags);
6739 }
Eric Laurent81784c32012-11-19 14:55:58 -08006740
Glenn Kasten90e58b12013-07-31 16:16:02 -07006741 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006742 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006743 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006744 // we formerly checked for a callback handler (non-0 tid),
6745 // but that is no longer required for TRANSFER_OBTAIN mode
6746 //
Glenn Kasten74105912014-07-03 12:28:53 -07006747 // frame count is not specified, or is exactly the pipe depth
6748 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006749 // PCM data
6750 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006751 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006752 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006753 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006754 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006755 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006756 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006757 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006758 hasFastCapture() &&
6759 // there are sufficient fast track slots available
6760 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006761 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006762 // check compatibility with audio effects.
6763 Mutex::Autolock _l(mLock);
6764 // Do not accept FAST flag if the session has software effects
6765 sp<EffectChain> chain = getEffectChain_l(sessionId);
6766 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006767 audio_input_flags_t old = *flags;
6768 chain->checkInputFlagCompatibility(flags);
6769 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006770 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6771 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006772 }
6773 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006774 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006775 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6776 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006777 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006778 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6779 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006780 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006781 this, frameCount, mFrameCount, mPipeFramesP2,
6782 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006783 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006784 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006785 }
6786 }
6787
6788 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006789 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006790 // fast track: frame count is exactly the pipe depth
6791 frameCount = mPipeFramesP2;
6792 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurent0aa3c6e2017-12-08 18:13:22 +00006793 *notificationFrames = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07006794 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006795 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6796 // or 20 ms if there is a fast capture
6797 // TODO This could be a roundupRatio inline, and const
6798 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6799 * sampleRate + mSampleRate - 1) / mSampleRate;
6800 // minimum number of notification periods is at least kMinNotifications,
6801 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6802 static const size_t kMinNotifications = 3;
6803 static const uint32_t kMinMs = 30;
6804 // TODO This could be a roundupRatio inline
6805 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6806 // TODO This could be a roundupRatio inline
6807 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6808 maxNotificationFrames;
6809 const size_t minFrameCount = maxNotificationFrames *
6810 max(kMinNotifications, minNotificationsByMs);
6811 frameCount = max(frameCount, minFrameCount);
Eric Laurent0aa3c6e2017-12-08 18:13:22 +00006812 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6813 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006814 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006815 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006816 *pFrameCount = frameCount;
Eric Laurent0aa3c6e2017-12-08 18:13:22 +00006817
6818 lStatus = initCheck();
6819 if (lStatus != NO_ERROR) {
6820 ALOGE("createRecordTrack_l() audio driver not initialized");
6821 goto Exit;
6822 }
Eric Laurent81784c32012-11-19 14:55:58 -08006823
6824 { // scope for mLock
6825 Mutex::Autolock _l(mLock);
6826
6827 track = new RecordTrack(this, client, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07006828 format, channelMask, frameCount,
6829 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006830 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006831
Glenn Kasten03003332013-08-06 15:40:54 -07006832 lStatus = track->initCheck();
6833 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006834 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006835 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006836 goto Exit;
6837 }
6838 mTracks.add(track);
6839
Eric Laurent05067782016-06-01 18:27:28 -07006840 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006841 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6842 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6843 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006844 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006845 }
Eric Laurent81784c32012-11-19 14:55:58 -08006846 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006847
Eric Laurent81784c32012-11-19 14:55:58 -08006848 lStatus = NO_ERROR;
6849
6850Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006851 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006852 return track;
6853}
6854
6855status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6856 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006857 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006858{
6859 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6860 sp<ThreadBase> strongMe = this;
6861 status_t status = NO_ERROR;
6862
6863 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006864 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006865 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006866 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006867 triggerSession,
6868 recordTrack->sessionId(),
6869 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006870 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006871 // Sync event can be cancelled by the trigger session if the track is not in a
6872 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006873 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006874 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006875 } else {
6876 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006877 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006878 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006879 }
6880 }
6881
6882 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006883 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006884 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006885 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6886 if (recordTrack->mState == TrackBase::PAUSING) {
6887 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006888 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006889 } else {
6890 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006891 }
6892 return status;
6893 }
6894
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006895 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6896 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6897 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006898 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006899 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006900 status_t status = NO_ERROR;
6901 if (recordTrack->isExternalTrack()) {
6902 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006903 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006904 mLock.lock();
6905 // FIXME should verify that recordTrack is still in mActiveTracks
6906 if (status != NO_ERROR) {
6907 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006908 recordTrack->clearSyncStartEvent();
6909 ALOGV("RecordThread::start error %d", status);
6910 return status;
6911 }
Eric Laurent81784c32012-11-19 14:55:58 -08006912 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006913 // Catch up with current buffer indices if thread is already running.
6914 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6915 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6916 // see previously buffered data before it called start(), but with greater risk of overrun.
6917
Andy Hung73c02e42015-03-29 01:13:58 -07006918 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006919 // clear any converter state as new data will be discontinuous
6920 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006921 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006922 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006923 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006924 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006925 ALOGV("Record failed to start");
6926 status = BAD_VALUE;
6927 goto startError;
6928 }
Eric Laurent81784c32012-11-19 14:55:58 -08006929 return status;
6930 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006931
Eric Laurent81784c32012-11-19 14:55:58 -08006932startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006933 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006934 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006935 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006936 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006937 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006938 return status;
6939}
6940
Eric Laurent81784c32012-11-19 14:55:58 -08006941void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6942{
6943 sp<SyncEvent> strongEvent = event.promote();
6944
6945 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006946 sp<RefBase> ptr = strongEvent->cookie().promote();
6947 if (ptr != 0) {
6948 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6949 recordTrack->handleSyncStartEvent(strongEvent);
6950 }
Eric Laurent81784c32012-11-19 14:55:58 -08006951 }
6952}
6953
Glenn Kastena8356f62013-07-25 14:37:52 -07006954bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006955 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006956 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006957 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006958 return false;
6959 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006960 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006961 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006962 // signal thread to stop
6963 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006964 // do not wait for mStartStopCond if exiting
6965 if (exitPending()) {
6966 return true;
6967 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006968 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006969 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006970 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006971 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006972 ALOGV("Record stopped OK");
6973 return true;
6974 }
6975 return false;
6976}
6977
Glenn Kasten0f11b512014-01-31 16:18:54 -08006978bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006979{
6980 return false;
6981}
6982
Glenn Kasten0f11b512014-01-31 16:18:54 -08006983status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006984{
6985#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6986 if (!isValidSyncEvent(event)) {
6987 return BAD_VALUE;
6988 }
6989
Glenn Kastend848eb42016-03-08 13:42:11 -08006990 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006991 status_t ret = NAME_NOT_FOUND;
6992
6993 Mutex::Autolock _l(mLock);
6994
6995 for (size_t i = 0; i < mTracks.size(); i++) {
6996 sp<RecordTrack> track = mTracks[i];
6997 if (eventSession == track->sessionId()) {
6998 (void) track->setSyncEvent(event);
6999 ret = NO_ERROR;
7000 }
7001 }
7002 return ret;
7003#else
7004 return BAD_VALUE;
7005#endif
7006}
7007
7008// destroyTrack_l() must be called with ThreadBase::mLock held
7009void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7010{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007011 track->terminate();
7012 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007013 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007014 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007015 removeTrack_l(track);
7016 }
7017}
7018
7019void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7020{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007021 String8 result;
7022 track->appendDump(result, false /* active */);
7023 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7024
Eric Laurent81784c32012-11-19 14:55:58 -08007025 mTracks.remove(track);
7026 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007027 if (track->isFastTrack()) {
7028 ALOG_ASSERT(!mFastTrackAvail);
7029 mFastTrackAvail = true;
7030 }
Eric Laurent81784c32012-11-19 14:55:58 -08007031}
7032
7033void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7034{
7035 dumpInternals(fd, args);
7036 dumpTracks(fd, args);
7037 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007038 dprintf(fd, " Local log:\n");
7039 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007040}
7041
7042void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7043{
Glenn Kasten44182c22015-03-05 17:12:23 -08007044 dumpBase(fd, args);
7045
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007046 AudioStreamIn *input = mInput;
7047 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7048 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7049 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007050 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007051 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007052 }
Andy Hungbfa64962017-06-12 14:43:19 -07007053
7054 if (input != nullptr) {
7055 dprintf(fd, " Hal stream dump:\n");
7056 (void)input->stream->dump(fd);
7057 }
7058
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007059 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007060 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007061
Glenn Kasten2f90c512015-12-02 11:40:09 -08007062 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7063 // while we are dumping it. It may be inconsistent, but it won't mutate!
7064 // This is a large object so we place it on the heap.
7065 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7066 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7067 copy->dump(fd);
7068 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007069}
7070
Glenn Kasten0f11b512014-01-31 16:18:54 -08007071void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007072{
Eric Laurent81784c32012-11-19 14:55:58 -08007073 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007074 size_t numtracks = mTracks.size();
7075 size_t numactive = mActiveTracks.size();
7076 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007077 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007078 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007079 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007080 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007081 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08007082 RecordTrack::appendDumpHeader(result);
7083 for (size_t i = 0; i < numtracks ; ++i) {
7084 sp<RecordTrack> track = mTracks[i];
7085 if (track != 0) {
7086 bool active = mActiveTracks.indexOf(track) >= 0;
7087 if (active) {
7088 numactiveseen++;
7089 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007090 result.append(prefix);
7091 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007092 }
Eric Laurent81784c32012-11-19 14:55:58 -08007093 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007094 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007095 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007096 }
7097
Marco Nelissenb2208842014-02-07 14:00:50 -08007098 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007099 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007100 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007101 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08007102 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007103 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007104 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007105 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007106 result.append(prefix);
7107 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007108 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007109 }
Eric Laurent81784c32012-11-19 14:55:58 -08007110
7111 }
7112 write(fd, result.string(), result.size());
7113}
7114
Andy Hung73c02e42015-03-29 01:13:58 -07007115
7116void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7117{
7118 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7119 RecordThread *recordThread = (RecordThread *) threadBase.get();
7120 mRsmpInFront = recordThread->mRsmpInRear;
7121 mRsmpInUnrel = 0;
7122}
7123
7124void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7125 size_t *framesAvailable, bool *hasOverrun)
7126{
7127 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7128 RecordThread *recordThread = (RecordThread *) threadBase.get();
7129 const int32_t rear = recordThread->mRsmpInRear;
7130 const int32_t front = mRsmpInFront;
7131 const ssize_t filled = rear - front;
7132
7133 size_t framesIn;
7134 bool overrun = false;
7135 if (filled < 0) {
7136 // should not happen, but treat like a massive overrun and re-sync
7137 framesIn = 0;
7138 mRsmpInFront = rear;
7139 overrun = true;
7140 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7141 framesIn = (size_t) filled;
7142 } else {
7143 // client is not keeping up with server, but give it latest data
7144 framesIn = recordThread->mRsmpInFrames;
7145 mRsmpInFront = /* front = */ rear - framesIn;
7146 overrun = true;
7147 }
7148 if (framesAvailable != NULL) {
7149 *framesAvailable = framesIn;
7150 }
7151 if (hasOverrun != NULL) {
7152 *hasOverrun = overrun;
7153 }
7154}
7155
Eric Laurent81784c32012-11-19 14:55:58 -08007156// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007157status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007158 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007159{
Andy Hung73c02e42015-03-29 01:13:58 -07007160 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007161 if (threadBase == 0) {
7162 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007163 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007164 return NOT_ENOUGH_DATA;
7165 }
7166 RecordThread *recordThread = (RecordThread *) threadBase.get();
7167 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007168 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007169 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007170 // FIXME should not be P2 (don't want to increase latency)
7171 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007172 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007173 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007174 front &= recordThread->mRsmpInFramesP2 - 1;
7175 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007176 if (part1 > (size_t) filled) {
7177 part1 = filled;
7178 }
7179 size_t ask = buffer->frameCount;
7180 ALOG_ASSERT(ask > 0);
7181 if (part1 > ask) {
7182 part1 = ask;
7183 }
7184 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007185 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007186 buffer->raw = NULL;
7187 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007188 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007189 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007190 }
7191
Andy Hung57446612015-04-19 23:56:46 -07007192 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007193 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007194 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007195 return NO_ERROR;
7196}
7197
7198// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007199void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7200 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007201{
Glenn Kasten85948432013-08-19 12:09:05 -07007202 size_t stepCount = buffer->frameCount;
7203 if (stepCount == 0) {
7204 return;
7205 }
Andy Hung73c02e42015-03-29 01:13:58 -07007206 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7207 mRsmpInUnrel -= stepCount;
7208 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007209 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007210 buffer->frameCount = 0;
7211}
7212
Eric Laurentd8365c52017-07-16 15:27:05 -07007213void AudioFlinger::RecordThread::checkBtNrec()
7214{
7215 Mutex::Autolock _l(mLock);
7216 checkBtNrec_l();
7217}
7218
7219void AudioFlinger::RecordThread::checkBtNrec_l()
7220{
7221 // disable AEC and NS if the device is a BT SCO headset supporting those
7222 // pre processings
7223 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7224 mAudioFlinger->btNrecIsOff();
7225 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7226 for (size_t i = 0; i < mEffectChains.size(); i++) {
7227 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7228 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7229 }
7230 }
7231}
7232
Andy Hung97a893e2015-03-29 01:03:07 -07007233
Eric Laurent10351942014-05-08 18:49:52 -07007234bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7235 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007236{
7237 bool reconfig = false;
7238
Eric Laurent10351942014-05-08 18:49:52 -07007239 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007240
Eric Laurent10351942014-05-08 18:49:52 -07007241 audio_format_t reqFormat = mFormat;
7242 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007243 // 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 -07007244 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7245
7246 AudioParameter param = AudioParameter(keyValuePair);
7247 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007248
7249 // scope for AutoPark extends to end of method
7250 AutoPark<FastCapture> park(mFastCapture);
7251
Eric Laurent10351942014-05-08 18:49:52 -07007252 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7253 // channel count change can be requested. Do we mandate the first client defines the
7254 // HAL sampling rate and channel count or do we allow changes on the fly?
7255 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7256 samplingRate = value;
7257 reconfig = true;
7258 }
7259 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007260 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007261 status = BAD_VALUE;
7262 } else {
7263 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007264 reconfig = true;
7265 }
Eric Laurent10351942014-05-08 18:49:52 -07007266 }
7267 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7268 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007269 if (!audio_is_input_channel(mask) ||
7270 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007271 status = BAD_VALUE;
7272 } else {
7273 channelMask = mask;
7274 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007275 }
Eric Laurent10351942014-05-08 18:49:52 -07007276 }
7277 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7278 // do not accept frame count changes if tracks are open as the track buffer
7279 // size depends on frame count and correct behavior would not be guaranteed
7280 // if frame count is changed after track creation
7281 if (mActiveTracks.size() > 0) {
7282 status = INVALID_OPERATION;
7283 } else {
7284 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007285 }
Eric Laurent10351942014-05-08 18:49:52 -07007286 }
7287 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7288 // forward device change to effects that have requested to be
7289 // aware of attached audio device.
7290 for (size_t i = 0; i < mEffectChains.size(); i++) {
7291 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007292 }
Eric Laurent81784c32012-11-19 14:55:58 -08007293
Eric Laurent10351942014-05-08 18:49:52 -07007294 // store input device and output device but do not forward output device to audio HAL.
7295 // Note that status is ignored by the caller for output device
7296 // (see AudioFlinger::setParameters()
7297 if (audio_is_output_devices(value)) {
7298 mOutDevice = value;
7299 status = BAD_VALUE;
7300 } else {
7301 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007302 if (value != AUDIO_DEVICE_NONE) {
7303 mPrevInDevice = value;
7304 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007305 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007306 }
Eric Laurent10351942014-05-08 18:49:52 -07007307 }
7308 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7309 mAudioSource != (audio_source_t)value) {
7310 // forward device change to effects that have requested to be
7311 // aware of attached audio device.
7312 for (size_t i = 0; i < mEffectChains.size(); i++) {
7313 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007314 }
Eric Laurent10351942014-05-08 18:49:52 -07007315 mAudioSource = (audio_source_t)value;
7316 }
Glenn Kastene198c362013-08-13 09:13:36 -07007317
Eric Laurent10351942014-05-08 18:49:52 -07007318 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007319 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007320 if (status == INVALID_OPERATION) {
7321 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007322 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007323 }
7324 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007325 if (status == BAD_VALUE) {
7326 uint32_t sRate;
7327 audio_channel_mask_t channelMask;
7328 audio_format_t format;
7329 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7330 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7331 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7332 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7333 status = NO_ERROR;
7334 }
Eric Laurent81784c32012-11-19 14:55:58 -08007335 }
Eric Laurent10351942014-05-08 18:49:52 -07007336 if (status == NO_ERROR) {
7337 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007338 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007339 }
7340 }
Eric Laurent81784c32012-11-19 14:55:58 -08007341 }
Eric Laurent10351942014-05-08 18:49:52 -07007342
Eric Laurent81784c32012-11-19 14:55:58 -08007343 return reconfig;
7344}
7345
7346String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7347{
Eric Laurent81784c32012-11-19 14:55:58 -08007348 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007349 if (initCheck() == NO_ERROR) {
7350 String8 out_s8;
7351 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7352 return out_s8;
7353 }
Eric Laurent81784c32012-11-19 14:55:58 -08007354 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007355 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007356}
7357
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007358void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007359 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7360
7361 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007362
7363 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007364 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007365 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007366 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007367 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007368 desc->mChannelMask = mChannelMask;
7369 desc->mSamplingRate = mSampleRate;
7370 desc->mFormat = mFormat;
7371 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007372 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007373 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007374 break;
7375
Eric Laurent73e26b62015-04-27 16:55:58 -07007376 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007377 default:
7378 break;
7379 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007380 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007381}
7382
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007383void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007384{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007385 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7386 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007387 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007388 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007389 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007390 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7391 result = mInput->stream->getFrameSize(&mFrameSize);
7392 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7393 result = mInput->stream->getBufferSize(&mBufferSize);
7394 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007395 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007396 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7397 "mBufferSize=%lld, mFrameCount=%lld",
7398 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7399 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007400 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007401 // 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 -07007402 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007403 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007404 // A larger value should allow more old data to be read after a track calls start(),
7405 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007406 //
7407 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007408 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007409 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007410 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007411 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007412
7413 // TODO optimize audio capture buffer sizes ...
7414 // Here we calculate the size of the sliding buffer used as a source
7415 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7416 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7417 // be better to have it derived from the pipe depth in the long term.
7418 // The current value is higher than necessary. However it should not add to latency.
7419
Glenn Kasten85948432013-08-19 12:09:05 -07007420 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007421 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7422 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007423 // if posix_memalign fails, will segv here.
7424 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007425
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007426 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7427 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007428}
7429
Glenn Kasten5f972c02014-01-13 09:59:31 -08007430uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007431{
7432 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007433 uint32_t result;
7434 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7435 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007436 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007437 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007438}
7439
Eric Laurent4c415062016-06-17 16:14:16 -07007440// hasAudioSession_l() must be called with ThreadBase::mLock held
7441uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007442{
Eric Laurent81784c32012-11-19 14:55:58 -08007443 uint32_t result = 0;
7444 if (getEffectChain_l(sessionId) != 0) {
7445 result = EFFECT_SESSION;
7446 }
7447
7448 for (size_t i = 0; i < mTracks.size(); ++i) {
7449 if (sessionId == mTracks[i]->sessionId()) {
7450 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007451 if (mTracks[i]->isFastTrack()) {
7452 result |= FAST_SESSION;
7453 }
Eric Laurent81784c32012-11-19 14:55:58 -08007454 break;
7455 }
7456 }
7457
7458 return result;
7459}
7460
Glenn Kastend848eb42016-03-08 13:42:11 -08007461KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007462{
Glenn Kastend848eb42016-03-08 13:42:11 -08007463 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007464 Mutex::Autolock _l(mLock);
7465 for (size_t j = 0; j < mTracks.size(); ++j) {
7466 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007467 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007468 if (ids.indexOfKey(sessionId) < 0) {
7469 ids.add(sessionId, true);
7470 }
7471 }
7472 return ids;
7473}
7474
7475AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7476{
7477 Mutex::Autolock _l(mLock);
7478 AudioStreamIn *input = mInput;
7479 mInput = NULL;
7480 return input;
7481}
7482
7483// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007484sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007485{
7486 if (mInput == NULL) {
7487 return NULL;
7488 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007489 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007490}
7491
7492status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7493{
7494 // only one chain per input thread
7495 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007496 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007497 return INVALID_OPERATION;
7498 }
7499 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007500 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007501 chain->setInBuffer(NULL);
7502 chain->setOutBuffer(NULL);
7503
7504 checkSuspendOnAddEffectChain_l(chain);
7505
Eric Laurent1b928682014-10-02 19:41:47 -07007506 // make sure enabled pre processing effects state is communicated to the HAL as we
7507 // just moved them to a new input stream.
7508 chain->syncHalEffectsState();
7509
Eric Laurent81784c32012-11-19 14:55:58 -08007510 mEffectChains.add(chain);
7511
7512 return NO_ERROR;
7513}
7514
7515size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7516{
7517 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7518 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007519 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007520 chain.get(), mEffectChains.size(), this);
7521 if (mEffectChains.size() == 1) {
7522 mEffectChains.removeAt(0);
7523 }
7524 return 0;
7525}
7526
Eric Laurent1c333e22014-05-20 10:48:17 -07007527status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7528 audio_patch_handle_t *handle)
7529{
7530 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007531
7532 // store new device and send to effects
7533 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007534 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007535 for (size_t i = 0; i < mEffectChains.size(); i++) {
7536 mEffectChains[i]->setDevice_l(mInDevice);
7537 }
7538
Eric Laurentd8365c52017-07-16 15:27:05 -07007539 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007540
7541 // store new source and send to effects
7542 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7543 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007544 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007545 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007546 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007547 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007548
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007549 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007550 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7551 status = hwDevice->createAudioPatch(patch->num_sources,
7552 patch->sources,
7553 patch->num_sinks,
7554 patch->sinks,
7555 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007556 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007557 char *address;
7558 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7559 address = audio_device_address_to_parameter(
7560 patch->sources[0].ext.device.type,
7561 patch->sources[0].ext.device.address);
7562 } else {
7563 address = (char *)calloc(1, 1);
7564 }
7565 AudioParameter param = AudioParameter(String8(address));
7566 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007567 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007568 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007569 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007570 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007571 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007572 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007573 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007574
Eric Laurente8726fe2015-06-26 09:39:24 -07007575 if (mInDevice != mPrevInDevice) {
7576 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7577 mPrevInDevice = mInDevice;
7578 }
Eric Laurent296fb132015-05-01 11:38:42 -07007579
Eric Laurent1c333e22014-05-20 10:48:17 -07007580 return status;
7581}
7582
7583status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7584{
7585 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007586
7587 mInDevice = AUDIO_DEVICE_NONE;
7588
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007589 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007590 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7591 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007592 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007593 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007594 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007595 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007596 }
7597 return status;
7598}
7599
Eric Laurent83b88082014-06-20 18:31:16 -07007600void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7601{
7602 Mutex::Autolock _l(mLock);
7603 mTracks.add(record);
7604}
7605
7606void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7607{
7608 Mutex::Autolock _l(mLock);
7609 destroyTrack_l(record);
7610}
7611
7612void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7613{
7614 ThreadBase::getAudioPortConfig(config);
7615 config->role = AUDIO_PORT_ROLE_SINK;
7616 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7617 config->ext.mix.usecase.source = mAudioSource;
7618}
Eric Laurent1c333e22014-05-20 10:48:17 -07007619
Eric Laurent6acd1d42017-01-04 14:23:29 -08007620// ----------------------------------------------------------------------------
7621// Mmap
7622// ----------------------------------------------------------------------------
7623
7624AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7625 : mThread(thread)
7626{
Phil Burk9fabbf82017-08-03 12:02:00 -07007627 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007628}
7629
7630AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7631{
Phil Burk9fabbf82017-08-03 12:02:00 -07007632 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007633}
7634
7635status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7636 struct audio_mmap_buffer_info *info)
7637{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007638 return mThread->createMmapBuffer(minSizeFrames, info);
7639}
7640
7641status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7642{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007643 return mThread->getMmapPosition(position);
7644}
7645
Eric Laurenta54f1282017-07-01 19:39:32 -07007646status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007647 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007648
7649{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007650 return mThread->start(client, handle);
7651}
7652
7653status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7654{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007655 return mThread->stop(handle);
7656}
7657
Eric Laurent18b57012017-02-13 16:23:52 -08007658status_t AudioFlinger::MmapThreadHandle::standby()
7659{
Eric Laurent18b57012017-02-13 16:23:52 -08007660 return mThread->standby();
7661}
7662
Eric Laurent6acd1d42017-01-04 14:23:29 -08007663
7664AudioFlinger::MmapThread::MmapThread(
7665 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7666 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7667 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7668 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007669 mSessionId(AUDIO_SESSION_NONE),
7670 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007671 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
7672 mActiveTracks(&this->mLocalLog)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007673{
Eric Laurent18b57012017-02-13 16:23:52 -08007674 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007675 readHalParameters_l();
7676}
7677
7678AudioFlinger::MmapThread::~MmapThread()
7679{
Eric Laurent18b57012017-02-13 16:23:52 -08007680 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007681}
7682
7683void AudioFlinger::MmapThread::onFirstRef()
7684{
7685 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7686}
7687
7688void AudioFlinger::MmapThread::disconnect()
7689{
7690 for (const sp<MmapTrack> &t : mActiveTracks) {
7691 stop(t->portId());
7692 }
Phil Burk9fabbf82017-08-03 12:02:00 -07007693 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08007694 if (isOutput()) {
7695 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7696 } else {
7697 AudioSystem::releaseInput(mId, mSessionId);
7698 }
7699}
7700
7701
7702void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7703 audio_stream_type_t streamType __unused,
7704 audio_session_t sessionId,
7705 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007706 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007707 audio_port_handle_t portId)
7708{
7709 mAttr = *attr;
7710 mSessionId = sessionId;
7711 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007712 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007713 mPortId = portId;
7714}
7715
7716status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7717 struct audio_mmap_buffer_info *info)
7718{
7719 if (mHalStream == 0) {
7720 return NO_INIT;
7721 }
Eric Laurent18b57012017-02-13 16:23:52 -08007722 mStandby = true;
7723 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007724 return mHalStream->createMmapBuffer(minSizeFrames, info);
7725}
7726
7727status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7728{
7729 if (mHalStream == 0) {
7730 return NO_INIT;
7731 }
7732 return mHalStream->getMmapPosition(position);
7733}
7734
Eric Laurenta54f1282017-07-01 19:39:32 -07007735status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007736 audio_port_handle_t *handle)
7737{
Eric Laurenta54f1282017-07-01 19:39:32 -07007738 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7739 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007740 if (mHalStream == 0) {
7741 return NO_INIT;
7742 }
7743
7744 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007745
Eric Laurenta54f1282017-07-01 19:39:32 -07007746 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007747 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007748 ret = mHalStream->start();
7749 if (ret != NO_ERROR) {
7750 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7751 return ret;
7752 }
Eric Laurent18b57012017-02-13 16:23:52 -08007753 mStandby = false;
Eric Laurenta54f1282017-07-01 19:39:32 -07007754 return NO_ERROR;
7755 }
7756
Phil Burk81ad5ec2017-09-01 10:45:41 -07007757 if (!isOutput() && !recordingAllowed(client.packageName, client.clientPid, client.clientUid)) {
7758 return PERMISSION_DENIED;
7759 }
7760
Eric Laurenta54f1282017-07-01 19:39:32 -07007761 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7762
7763 audio_io_handle_t io = mId;
7764 if (isOutput()) {
7765 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7766 config.sample_rate = mSampleRate;
7767 config.channel_mask = mChannelMask;
7768 config.format = mFormat;
7769 audio_stream_type_t stream = streamType();
7770 audio_output_flags_t flags =
7771 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007772 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007773 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7774 mSessionId,
7775 &stream,
7776 client.clientUid,
7777 &config,
7778 flags,
7779 &deviceId,
7780 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007781 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007782 audio_config_base_t config;
7783 config.sample_rate = mSampleRate;
7784 config.channel_mask = mChannelMask;
7785 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007786 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007787 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7788 mSessionId,
7789 client.clientPid,
7790 client.clientUid,
7791 &config,
7792 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7793 &deviceId,
7794 &portId);
7795 }
7796 // APM should not chose a different input or output stream for the same set of attributes
7797 // and audo configuration
7798 if (ret != NO_ERROR || io != mId) {
7799 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7800 __FUNCTION__, ret, io, mId);
7801 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007802 }
7803
7804 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007805 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007806 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007807 ret = AudioSystem::startInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007808 }
7809
7810 // abort if start is rejected by audio policy manager
7811 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007812 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007813 if (mActiveTracks.size() != 0) {
7814 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007815 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007816 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007817 AudioSystem::releaseInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007818 }
Eric Laurent18b57012017-02-13 16:23:52 -08007819 } else {
7820 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007821 }
7822 return PERMISSION_DENIED;
7823 }
7824
Eric Laurenta54f1282017-07-01 19:39:32 -07007825 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, mSessionId,
7826 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007827
7828 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07007829 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007830 if (chain != 0) {
7831 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7832 chain->incTrackCnt();
7833 chain->incActiveTrackCnt();
7834 }
7835
7836 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007837 broadcast_l();
7838
Eric Laurenta54f1282017-07-01 19:39:32 -07007839 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007840
7841 return NO_ERROR;
7842}
7843
7844status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7845{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007846 ALOGV("%s handle %d", __FUNCTION__, handle);
7847
7848 if (mHalStream == 0) {
7849 return NO_INIT;
7850 }
7851
Eric Laurenta54f1282017-07-01 19:39:32 -07007852 if (handle == mPortId) {
7853 mHalStream->stop();
7854 return NO_ERROR;
7855 }
7856
Eric Laurent6acd1d42017-01-04 14:23:29 -08007857 sp<MmapTrack> track;
7858 for (const sp<MmapTrack> &t : mActiveTracks) {
7859 if (handle == t->portId()) {
7860 track = t;
7861 break;
7862 }
7863 }
7864 if (track == 0) {
7865 return BAD_VALUE;
7866 }
7867
7868 mActiveTracks.remove(track);
7869
7870 if (isOutput()) {
7871 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007872 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007873 } else {
7874 AudioSystem::stopInput(mId, track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007875 AudioSystem::releaseInput(mId, track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007876 }
7877
7878 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7879 if (chain != 0) {
7880 chain->decActiveTrackCnt();
7881 chain->decTrackCnt();
7882 }
7883
7884 broadcast_l();
7885
Eric Laurent6acd1d42017-01-04 14:23:29 -08007886 return NO_ERROR;
7887}
7888
Eric Laurent18b57012017-02-13 16:23:52 -08007889status_t AudioFlinger::MmapThread::standby()
7890{
7891 ALOGV("%s", __FUNCTION__);
7892
7893 if (mHalStream == 0) {
7894 return NO_INIT;
7895 }
7896 if (mActiveTracks.size() != 0) {
7897 return INVALID_OPERATION;
7898 }
7899 mHalStream->standby();
7900 mStandby = true;
7901 releaseWakeLock();
7902 return NO_ERROR;
7903}
7904
Eric Laurent6acd1d42017-01-04 14:23:29 -08007905
7906void AudioFlinger::MmapThread::readHalParameters_l()
7907{
7908 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7909 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7910 mFormat = mHALFormat;
7911 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7912 result = mHalStream->getFrameSize(&mFrameSize);
7913 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7914 result = mHalStream->getBufferSize(&mBufferSize);
7915 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7916 mFrameCount = mBufferSize / mFrameSize;
7917}
7918
7919bool AudioFlinger::MmapThread::threadLoop()
7920{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007921 checkSilentMode_l();
7922
7923 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7924
7925 while (!exitPending())
7926 {
7927 Mutex::Autolock _l(mLock);
7928 Vector< sp<EffectChain> > effectChains;
7929
7930 if (mSignalPending) {
7931 // A signal was raised while we were unlocked
7932 mSignalPending = false;
7933 } else {
7934 if (mConfigEvents.isEmpty()) {
7935 // we're about to wait, flush the binder command buffer
7936 IPCThreadState::self()->flushCommands();
7937
7938 if (exitPending()) {
7939 break;
7940 }
7941
Eric Laurent6acd1d42017-01-04 14:23:29 -08007942 // wait until we have something to do...
7943 ALOGV("%s going to sleep", myName.string());
7944 mWaitWorkCV.wait(mLock);
7945 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007946
7947 checkSilentMode_l();
7948
7949 continue;
7950 }
7951 }
7952
7953 processConfigEvents_l();
7954
7955 processVolume_l();
7956
7957 checkInvalidTracks_l();
7958
7959 mActiveTracks.updatePowerState(this);
7960
7961 lockEffectChains_l(effectChains);
7962 for (size_t i = 0; i < effectChains.size(); i ++) {
7963 effectChains[i]->process_l();
7964 }
7965 // enable changes in effect chain
7966 unlockEffectChains(effectChains);
7967 // Effect chains will be actually deleted here if they were removed from
7968 // mEffectChains list during mixing or effects processing
7969 }
7970
7971 threadLoop_exit();
7972
7973 if (!mStandby) {
7974 threadLoop_standby();
7975 mStandby = true;
7976 }
7977
Eric Laurent6acd1d42017-01-04 14:23:29 -08007978 ALOGV("Thread %p type %d exiting", this, mType);
7979 return false;
7980}
7981
7982// checkForNewParameter_l() must be called with ThreadBase::mLock held
7983bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7984 status_t& status)
7985{
7986 AudioParameter param = AudioParameter(keyValuePair);
7987 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07007988 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007989 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07007990 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007991 // forward device change to effects that have requested to be
7992 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07007993 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007994 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07007995 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007996 }
7997 }
Eric Laurente6e9a482017-07-25 19:26:02 -07007998 if (audio_is_output_devices(device)) {
7999 mOutDevice = device;
8000 if (!isOutput()) {
8001 sendToHal = false;
8002 }
8003 } else {
8004 mInDevice = device;
8005 if (device != AUDIO_DEVICE_NONE) {
8006 mPrevInDevice = value;
8007 }
8008 // TODO: implement and call checkBtNrec_l();
8009 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008010 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008011 if (sendToHal) {
8012 status = mHalStream->setParameters(keyValuePair);
8013 } else {
8014 status = NO_ERROR;
8015 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008016
8017 return false;
8018}
8019
8020String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8021{
8022 Mutex::Autolock _l(mLock);
8023 String8 out_s8;
8024 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8025 return out_s8;
8026 }
8027 return String8();
8028}
8029
8030void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8031 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8032
8033 desc->mIoHandle = mId;
8034
8035 switch (event) {
8036 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008037 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008038 case AUDIO_INPUT_CONFIG_CHANGED:
8039 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008040 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008041 case AUDIO_OUTPUT_CONFIG_CHANGED:
8042 desc->mPatch = mPatch;
8043 desc->mChannelMask = mChannelMask;
8044 desc->mSamplingRate = mSampleRate;
8045 desc->mFormat = mFormat;
8046 desc->mFrameCount = mFrameCount;
8047 desc->mFrameCountHAL = mFrameCount;
8048 desc->mLatency = 0;
8049 break;
8050
8051 case AUDIO_INPUT_CLOSED:
8052 case AUDIO_OUTPUT_CLOSED:
8053 default:
8054 break;
8055 }
8056 mAudioFlinger->ioConfigChanged(event, desc, pid);
8057}
8058
8059status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8060 audio_patch_handle_t *handle)
8061{
8062 status_t status = NO_ERROR;
8063
8064 // store new device and send to effects
8065 audio_devices_t type = AUDIO_DEVICE_NONE;
8066 audio_port_handle_t deviceId;
8067 if (isOutput()) {
8068 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8069 type |= patch->sinks[i].ext.device.type;
8070 }
8071 deviceId = patch->sinks[0].id;
8072 } else {
8073 type = patch->sources[0].ext.device.type;
8074 deviceId = patch->sources[0].id;
8075 }
8076
8077 for (size_t i = 0; i < mEffectChains.size(); i++) {
8078 mEffectChains[i]->setDevice_l(type);
8079 }
8080
8081 if (isOutput()) {
8082 mOutDevice = type;
8083 } else {
8084 mInDevice = type;
8085 // store new source and send to effects
8086 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8087 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8088 for (size_t i = 0; i < mEffectChains.size(); i++) {
8089 mEffectChains[i]->setAudioSource_l(mAudioSource);
8090 }
8091 }
8092 }
8093
8094 if (mAudioHwDev->supportsAudioPatches()) {
8095 status = mHalDevice->createAudioPatch(patch->num_sources,
8096 patch->sources,
8097 patch->num_sinks,
8098 patch->sinks,
8099 handle);
8100 } else {
8101 char *address;
8102 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8103 //FIXME: we only support address on first sink with HAL version < 3.0
8104 address = audio_device_address_to_parameter(
8105 patch->sinks[0].ext.device.type,
8106 patch->sinks[0].ext.device.address);
8107 } else {
8108 address = (char *)calloc(1, 1);
8109 }
8110 AudioParameter param = AudioParameter(String8(address));
8111 free(address);
8112 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8113 if (!isOutput()) {
8114 param.addInt(String8(AudioParameter::keyInputSource),
8115 (int)patch->sinks[0].ext.mix.usecase.source);
8116 }
8117 status = mHalStream->setParameters(param.toString());
8118 *handle = AUDIO_PATCH_HANDLE_NONE;
8119 }
8120
8121 if (isOutput() && mPrevOutDevice != mOutDevice) {
8122 mPrevOutDevice = type;
8123 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008124 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008125 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008126 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008127 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008128 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008129 }
8130 if (!isOutput() && mPrevInDevice != mInDevice) {
8131 mPrevInDevice = type;
8132 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008133 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008134 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008135 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008136 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008137 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008138 }
8139 return status;
8140}
8141
8142status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8143{
8144 status_t status = NO_ERROR;
8145
8146 mInDevice = AUDIO_DEVICE_NONE;
8147
8148 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8149 supportsAudioPatches : false;
8150
8151 if (supportsAudioPatches) {
8152 status = mHalDevice->releaseAudioPatch(handle);
8153 } else {
8154 AudioParameter param;
8155 param.addInt(String8(AudioParameter::keyRouting), 0);
8156 status = mHalStream->setParameters(param.toString());
8157 }
8158 return status;
8159}
8160
8161void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8162{
8163 ThreadBase::getAudioPortConfig(config);
8164 if (isOutput()) {
8165 config->role = AUDIO_PORT_ROLE_SOURCE;
8166 config->ext.mix.hw_module = mAudioHwDev->handle();
8167 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8168 } else {
8169 config->role = AUDIO_PORT_ROLE_SINK;
8170 config->ext.mix.hw_module = mAudioHwDev->handle();
8171 config->ext.mix.usecase.source = mAudioSource;
8172 }
8173}
8174
8175status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8176{
8177 audio_session_t session = chain->sessionId();
8178
8179 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8180 // Attach all tracks with same session ID to this chain.
8181 // indicate all active tracks in the chain
8182 for (const sp<MmapTrack> &track : mActiveTracks) {
8183 if (session == track->sessionId()) {
8184 chain->incTrackCnt();
8185 chain->incActiveTrackCnt();
8186 }
8187 }
8188
8189 chain->setThread(this);
8190 chain->setInBuffer(nullptr);
8191 chain->setOutBuffer(nullptr);
8192 chain->syncHalEffectsState();
8193
8194 mEffectChains.add(chain);
8195 checkSuspendOnAddEffectChain_l(chain);
8196 return NO_ERROR;
8197}
8198
8199size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8200{
8201 audio_session_t session = chain->sessionId();
8202
8203 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8204
8205 for (size_t i = 0; i < mEffectChains.size(); i++) {
8206 if (chain == mEffectChains[i]) {
8207 mEffectChains.removeAt(i);
8208 // detach all active tracks from the chain
8209 // detach all tracks with same session ID from this chain
8210 for (const sp<MmapTrack> &track : mActiveTracks) {
8211 if (session == track->sessionId()) {
8212 chain->decActiveTrackCnt();
8213 chain->decTrackCnt();
8214 }
8215 }
8216 break;
8217 }
8218 }
8219 return mEffectChains.size();
8220}
8221
8222// hasAudioSession_l() must be called with ThreadBase::mLock held
8223uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8224{
8225 uint32_t result = 0;
8226 if (getEffectChain_l(sessionId) != 0) {
8227 result = EFFECT_SESSION;
8228 }
8229
8230 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8231 sp<MmapTrack> track = mActiveTracks[i];
8232 if (sessionId == track->sessionId()) {
8233 result |= TRACK_SESSION;
8234 if (track->isFastTrack()) {
8235 result |= FAST_SESSION;
8236 }
8237 break;
8238 }
8239 }
8240
8241 return result;
8242}
8243
8244void AudioFlinger::MmapThread::threadLoop_standby()
8245{
8246 mHalStream->standby();
8247}
8248
8249void AudioFlinger::MmapThread::threadLoop_exit()
8250{
Phil Burk7dce7282017-09-27 13:51:41 -07008251 // Do not call callback->onTearDown() because it is redundant for thread exit
8252 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008253}
8254
8255status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8256{
8257 return BAD_VALUE;
8258}
8259
8260bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8261{
8262 return false;
8263}
8264
8265status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8266 const effect_descriptor_t *desc, audio_session_t sessionId)
8267{
8268 // No global effect sessions on mmap threads
8269 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8270 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8271 desc->name, mThreadName);
8272 return BAD_VALUE;
8273 }
8274
8275 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8276 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8277 desc->name);
8278 return BAD_VALUE;
8279 }
8280 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008281 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8282 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008283 return BAD_VALUE;
8284 }
8285
8286 // Only allow effects without processing load or latency
8287 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8288 return BAD_VALUE;
8289 }
8290
8291 return NO_ERROR;
8292
8293}
8294
8295void AudioFlinger::MmapThread::checkInvalidTracks_l()
8296{
8297 for (const sp<MmapTrack> &track : mActiveTracks) {
8298 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008299 sp<MmapStreamCallback> callback = mCallback.promote();
8300 if (callback != 0) {
8301 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008302 }
8303 break;
8304 }
8305 }
8306}
8307
8308void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8309{
8310 dumpInternals(fd, args);
8311 dumpTracks(fd, args);
8312 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008313 dprintf(fd, " Local log:\n");
8314 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008315}
8316
8317void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8318{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008319 dumpBase(fd, args);
8320
8321 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8322 mAttr.content_type, mAttr.usage, mAttr.source);
8323 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8324 if (mActiveTracks.size() == 0) {
8325 dprintf(fd, " No active clients\n");
8326 }
8327}
8328
8329void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8330{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008331 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008332 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008333 dprintf(fd, " %zu Tracks\n", numtracks);
8334 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008335 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008336 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008337 MmapTrack::appendDumpHeader(result);
8338 for (size_t i = 0; i < numtracks ; ++i) {
8339 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008340 result.append(prefix);
8341 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008342 }
8343 } else {
8344 dprintf(fd, "\n");
8345 }
8346 write(fd, result.string(), result.size());
8347}
8348
8349AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8350 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8351 AudioHwDevice *hwDev, AudioStreamOut *output,
8352 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8353 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8354 mStreamType(AUDIO_STREAM_MUSIC),
8355 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8356{
8357 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8358 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8359 mMasterVolume = audioFlinger->masterVolume_l();
8360 mMasterMute = audioFlinger->masterMute_l();
8361 if (mAudioHwDev) {
8362 if (mAudioHwDev->canSetMasterVolume()) {
8363 mMasterVolume = 1.0;
8364 }
8365
8366 if (mAudioHwDev->canSetMasterMute()) {
8367 mMasterMute = false;
8368 }
8369 }
8370}
8371
8372void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8373 audio_stream_type_t streamType,
8374 audio_session_t sessionId,
8375 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008376 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008377 audio_port_handle_t portId)
8378{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008379 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008380 mStreamType = streamType;
8381}
8382
8383AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8384{
8385 Mutex::Autolock _l(mLock);
8386 AudioStreamOut *output = mOutput;
8387 mOutput = NULL;
8388 return output;
8389}
8390
8391void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8392{
8393 Mutex::Autolock _l(mLock);
8394 // Don't apply master volume in SW if our HAL can do it for us.
8395 if (mAudioHwDev &&
8396 mAudioHwDev->canSetMasterVolume()) {
8397 mMasterVolume = 1.0;
8398 } else {
8399 mMasterVolume = value;
8400 }
8401}
8402
8403void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8404{
8405 Mutex::Autolock _l(mLock);
8406 // Don't apply master mute in SW if our HAL can do it for us.
8407 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8408 mMasterMute = false;
8409 } else {
8410 mMasterMute = muted;
8411 }
8412}
8413
8414void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8415{
8416 Mutex::Autolock _l(mLock);
8417 if (stream == mStreamType) {
8418 mStreamVolume = value;
8419 broadcast_l();
8420 }
8421}
8422
8423float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8424{
8425 Mutex::Autolock _l(mLock);
8426 if (stream == mStreamType) {
8427 return mStreamVolume;
8428 }
8429 return 0.0f;
8430}
8431
8432void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8433{
8434 Mutex::Autolock _l(mLock);
8435 if (stream == mStreamType) {
8436 mStreamMute= muted;
8437 broadcast_l();
8438 }
8439}
8440
8441void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8442{
8443 Mutex::Autolock _l(mLock);
8444 if (streamType == mStreamType) {
8445 for (const sp<MmapTrack> &track : mActiveTracks) {
8446 track->invalidate();
8447 }
8448 broadcast_l();
8449 }
8450}
8451
8452void AudioFlinger::MmapPlaybackThread::processVolume_l()
8453{
8454 float volume;
8455
8456 if (mMasterMute || mStreamMute) {
8457 volume = 0;
8458 } else {
8459 volume = mMasterVolume * mStreamVolume;
8460 }
8461
8462 if (volume != mHalVolFloat) {
8463 mHalVolFloat = volume;
8464
8465 // Convert volumes from float to 8.24
8466 uint32_t vol = (uint32_t)(volume * (1 << 24));
8467
8468 // Delegate volume control to effect in track effect chain if needed
8469 // only one effect chain can be present on DirectOutputThread, so if
8470 // there is one, the track is connected to it
8471 if (!mEffectChains.isEmpty()) {
8472 mEffectChains[0]->setVolume_l(&vol, &vol);
8473 volume = (float)vol / (1 << 24);
8474 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008475 // Try to use HW volume control and fall back to SW control if not implemented
8476 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8477 sp<MmapStreamCallback> callback = mCallback.promote();
8478 if (callback != 0) {
8479 int channelCount;
8480 if (isOutput()) {
8481 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8482 } else {
8483 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8484 }
8485 Vector<float> values;
8486 for (int i = 0; i < channelCount; i++) {
8487 values.add(volume);
8488 }
8489 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008490 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008491 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008492 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008493 }
8494 }
8495}
8496
8497void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8498{
8499 if (!mMasterMute) {
8500 char value[PROPERTY_VALUE_MAX];
8501 if (property_get("ro.audio.silent", value, "0") > 0) {
8502 char *endptr;
8503 unsigned long ul = strtoul(value, &endptr, 0);
8504 if (*endptr == '\0' && ul != 0) {
8505 ALOGD("Silence is golden");
8506 // The setprop command will not allow a property to be changed after
8507 // the first time it is set, so we don't have to worry about un-muting.
8508 setMasterMute_l(true);
8509 }
8510 }
8511 }
8512}
8513
8514void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8515{
8516 MmapThread::dumpInternals(fd, args);
8517
Glenn Kastend3bb6452016-12-05 18:14:37 -08008518 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8519 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008520 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8521}
8522
8523AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8524 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8525 AudioHwDevice *hwDev, AudioStreamIn *input,
8526 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8527 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8528 mInput(input)
8529{
8530 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8531 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8532}
8533
8534AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8535{
8536 Mutex::Autolock _l(mLock);
8537 AudioStreamIn *input = mInput;
8538 mInput = NULL;
8539 return input;
8540}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008541} // namespace android