blob: 3b1edec2ec44e103c25687eb9bc0917f6dd340a7 [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
Andy Hungd330ee42015-04-20 13:23:41 -0700103#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700104#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700105#endif
106
Eric Laurent81784c32012-11-19 14:55:58 -0800107namespace android {
108
109// retry counts for buffer fill timeout
110// 50 * ~20msecs = 1 second
111static const int8_t kMaxTrackRetries = 50;
112static const int8_t kMaxTrackStartupRetries = 50;
113// allow less retry attempts on direct output thread.
114// direct outputs can be a scarce resource in audio hardware and should
115// be released as quickly as possible.
116static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700117
Eric Laurent51716182016-02-29 18:00:56 -0800118
Eric Laurent81784c32012-11-19 14:55:58 -0800119
120// don't warn about blocked writes or record buffer overflows more often than this
121static const nsecs_t kWarningThrottleNs = seconds(5);
122
123// RecordThread loop sleep time upon application overrun or audio HAL read error
124static const int kRecordThreadSleepUs = 5000;
125
Eric Laurent10351942014-05-08 18:49:52 -0700126// maximum time to wait in sendConfigEvent_l() for a status to be received
127static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800128
129// minimum sleep time for the mixer thread loop when tracks are active but in underrun
130static const uint32_t kMinThreadSleepTimeUs = 5000;
131// maximum divider applied to the active sleep time in the mixer thread loop
132static const uint32_t kMaxThreadSleepTimeShift = 2;
133
Andy Hung09a50072014-02-27 14:30:47 -0800134// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700135// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800136static const uint32_t kMinNormalSinkBufferSizeMs = 20;
137// maximum normal sink buffer size
138static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800139
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700140// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
141// FIXME This should be based on experimentally observed scheduling jitter
142static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
143
Eric Laurent972a1732013-09-04 09:42:59 -0700144// Offloaded output thread standby delay: allows track transition without going to standby
145static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
146
Eric Laurent51716182016-02-29 18:00:56 -0800147// Direct output thread minimum sleep time in idle or active(underrun) state
148static const nsecs_t kDirectMinSleepTimeUs = 10000;
149
Glenn Kasten1b291842016-07-18 14:55:21 -0700150// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
151// balance between power consumption and latency, and allows threads to be scheduled reliably
152// by the CFS scheduler.
153// FIXME Express other hardcoded references to 20ms with references to this constant and move
154// it appropriately.
155#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800156
Eric Laurent81784c32012-11-19 14:55:58 -0800157// Whether to use fast mixer
158static const enum {
159 FastMixer_Never, // never initialize or use: for debugging only
160 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
161 // normal mixer multiplier is 1
162 FastMixer_Static, // initialize if needed, then use all the time if initialized,
163 // multiplier is calculated based on min & max normal mixer buffer size
164 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
165 // multiplier is calculated based on min & max normal mixer buffer size
166 // FIXME for FastMixer_Dynamic:
167 // Supporting this option will require fixing HALs that can't handle large writes.
168 // For example, one HAL implementation returns an error from a large write,
169 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
170 // We could either fix the HAL implementations, or provide a wrapper that breaks
171 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
172} kUseFastMixer = FastMixer_Static;
173
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700174// Whether to use fast capture
175static const enum {
176 FastCapture_Never, // never initialize or use: for debugging only
177 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
178 FastCapture_Static, // initialize if needed, then use all the time if initialized
179} kUseFastCapture = FastCapture_Static;
180
Eric Laurent81784c32012-11-19 14:55:58 -0800181// Priorities for requestPriority
182static const int kPriorityAudioApp = 2;
183static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700184static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800185
Glenn Kastenea38ee72016-04-18 11:08:01 -0700186// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
187// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
188// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700189
190// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800191static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800192
Glenn Kasten03490092014-05-27 12:30:54 -0700193// The minimum and maximum allowed values
194static const int kFastTrackMultiplierMin = 1;
195static const int kFastTrackMultiplierMax = 2;
196
197// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
198static int sFastTrackMultiplier = kFastTrackMultiplier;
199
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700200// See Thread::readOnlyHeap().
201// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
202// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
203// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700204static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700205
Eric Laurent81784c32012-11-19 14:55:58 -0800206// ----------------------------------------------------------------------------
207
Glenn Kasten03490092014-05-27 12:30:54 -0700208static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
209
210static void sFastTrackMultiplierInit()
211{
212 char value[PROPERTY_VALUE_MAX];
213 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
214 char *endptr;
215 unsigned long ul = strtoul(value, &endptr, 0);
216 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
217 sFastTrackMultiplier = (int) ul;
218 }
219 }
220}
221
222// ----------------------------------------------------------------------------
223
Eric Laurent81784c32012-11-19 14:55:58 -0800224#ifdef ADD_BATTERY_DATA
225// To collect the amplifier usage
226static void addBatteryData(uint32_t params) {
227 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
228 if (service == NULL) {
229 // it already logged
230 return;
231 }
232
233 service->addBatteryData(params);
234}
235#endif
236
Andy Hung3f0c9022016-01-15 17:49:46 -0800237// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
238struct {
239 // call when you acquire a partial wakelock
240 void acquire(const sp<IBinder> &wakeLockToken) {
241 pthread_mutex_lock(&mLock);
242 if (wakeLockToken.get() == nullptr) {
243 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
244 } else {
245 if (mCount == 0) {
246 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
247 }
248 ++mCount;
249 }
250 pthread_mutex_unlock(&mLock);
251 }
252
253 // call when you release a partial wakelock.
254 void release(const sp<IBinder> &wakeLockToken) {
255 if (wakeLockToken.get() == nullptr) {
256 return;
257 }
258 pthread_mutex_lock(&mLock);
259 if (--mCount < 0) {
260 ALOGE("negative wakelock count");
261 mCount = 0;
262 }
263 pthread_mutex_unlock(&mLock);
264 }
265
266 // retrieves the boottime timebase offset from monotonic.
267 int64_t getBoottimeOffset() {
268 pthread_mutex_lock(&mLock);
269 int64_t boottimeOffset = mBoottimeOffset;
270 pthread_mutex_unlock(&mLock);
271 return boottimeOffset;
272 }
273
274 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
275 // and the selected timebase.
276 // Currently only TIMEBASE_BOOTTIME is allowed.
277 //
278 // This only needs to be called upon acquiring the first partial wakelock
279 // after all other partial wakelocks are released.
280 //
281 // We do an empirical measurement of the offset rather than parsing
282 // /proc/timer_list since the latter is not a formal kernel ABI.
283 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
284 int clockbase;
285 switch (timebase) {
286 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
287 clockbase = SYSTEM_TIME_BOOTTIME;
288 break;
289 default:
290 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
291 break;
292 }
293 // try three times to get the clock offset, choose the one
294 // with the minimum gap in measurements.
295 const int tries = 3;
296 nsecs_t bestGap, measured;
297 for (int i = 0; i < tries; ++i) {
298 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
299 const nsecs_t tbase = systemTime(clockbase);
300 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
301 const nsecs_t gap = tmono2 - tmono;
302 if (i == 0 || gap < bestGap) {
303 bestGap = gap;
304 measured = tbase - ((tmono + tmono2) >> 1);
305 }
306 }
307
308 // to avoid micro-adjusting, we don't change the timebase
309 // unless it is significantly different.
310 //
311 // Assumption: It probably takes more than toleranceNs to
312 // suspend and resume the device.
313 static int64_t toleranceNs = 10000; // 10 us
314 if (llabs(*offset - measured) > toleranceNs) {
315 ALOGV("Adjusting timebase offset old: %lld new: %lld",
316 (long long)*offset, (long long)measured);
317 *offset = measured;
318 }
319 }
320
321 pthread_mutex_t mLock;
322 int32_t mCount;
323 int64_t mBoottimeOffset;
324} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800325
326// ----------------------------------------------------------------------------
327// CPU Stats
328// ----------------------------------------------------------------------------
329
330class CpuStats {
331public:
332 CpuStats();
333 void sample(const String8 &title);
334#ifdef DEBUG_CPU_USAGE
335private:
336 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
337 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
338
339 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
340
341 int mCpuNum; // thread's current CPU number
342 int mCpukHz; // frequency of thread's current CPU in kHz
343#endif
344};
345
346CpuStats::CpuStats()
347#ifdef DEBUG_CPU_USAGE
348 : mCpuNum(-1), mCpukHz(-1)
349#endif
350{
351}
352
Glenn Kasten0f11b512014-01-31 16:18:54 -0800353void CpuStats::sample(const String8 &title
354#ifndef DEBUG_CPU_USAGE
355 __unused
356#endif
357 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800358#ifdef DEBUG_CPU_USAGE
359 // get current thread's delta CPU time in wall clock ns
360 double wcNs;
361 bool valid = mCpuUsage.sampleAndEnable(wcNs);
362
363 // record sample for wall clock statistics
364 if (valid) {
365 mWcStats.sample(wcNs);
366 }
367
368 // get the current CPU number
369 int cpuNum = sched_getcpu();
370
371 // get the current CPU frequency in kHz
372 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
373
374 // check if either CPU number or frequency changed
375 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
376 mCpuNum = cpuNum;
377 mCpukHz = cpukHz;
378 // ignore sample for purposes of cycles
379 valid = false;
380 }
381
382 // if no change in CPU number or frequency, then record sample for cycle statistics
383 if (valid && mCpukHz > 0) {
384 double cycles = wcNs * cpukHz * 0.000001;
385 mHzStats.sample(cycles);
386 }
387
388 unsigned n = mWcStats.n();
389 // mCpuUsage.elapsed() is expensive, so don't call it every loop
390 if ((n & 127) == 1) {
391 long long elapsed = mCpuUsage.elapsed();
392 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
393 double perLoop = elapsed / (double) n;
394 double perLoop100 = perLoop * 0.01;
395 double perLoop1k = perLoop * 0.001;
396 double mean = mWcStats.mean();
397 double stddev = mWcStats.stddev();
398 double minimum = mWcStats.minimum();
399 double maximum = mWcStats.maximum();
400 double meanCycles = mHzStats.mean();
401 double stddevCycles = mHzStats.stddev();
402 double minCycles = mHzStats.minimum();
403 double maxCycles = mHzStats.maximum();
404 mCpuUsage.resetElapsed();
405 mWcStats.reset();
406 mHzStats.reset();
407 ALOGD("CPU usage for %s over past %.1f secs\n"
408 " (%u mixer loops at %.1f mean ms per loop):\n"
409 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
410 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
411 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
412 title.string(),
413 elapsed * .000000001, n, perLoop * .000001,
414 mean * .001,
415 stddev * .001,
416 minimum * .001,
417 maximum * .001,
418 mean / perLoop100,
419 stddev / perLoop100,
420 minimum / perLoop100,
421 maximum / perLoop100,
422 meanCycles / perLoop1k,
423 stddevCycles / perLoop1k,
424 minCycles / perLoop1k,
425 maxCycles / perLoop1k);
426
427 }
428 }
429#endif
430};
431
432// ----------------------------------------------------------------------------
433// ThreadBase
434// ----------------------------------------------------------------------------
435
Glenn Kasten97b7b752014-09-28 13:04:24 -0700436// static
437const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
438{
439 switch (type) {
440 case MIXER:
441 return "MIXER";
442 case DIRECT:
443 return "DIRECT";
444 case DUPLICATING:
445 return "DUPLICATING";
446 case RECORD:
447 return "RECORD";
448 case OFFLOAD:
449 return "OFFLOAD";
450 default:
451 return "unknown";
452 }
453}
454
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700461 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800462 }
463 return result;
464}
465
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800467{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700468 std::string result;
469 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800470 return result;
471}
472
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700474{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700475 std::string result;
476 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477 return result;
478}
479
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800480const char *sourceToString(audio_source_t source)
481{
482 switch (source) {
483 case AUDIO_SOURCE_DEFAULT: return "default";
484 case AUDIO_SOURCE_MIC: return "mic";
485 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
486 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
487 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
488 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
489 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
490 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
491 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800492 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800493 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
494 case AUDIO_SOURCE_HOTWORD: return "hotword";
495 default: return "unknown";
496 }
497}
498
Eric Laurent81784c32012-11-19 14:55:58 -0800499AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700500 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800501 : Thread(false /*canCallJava*/),
502 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700503 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700504 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800505 // are set by PlaybackThread::readOutputParameters_l() or
506 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700507 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800508 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700509 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
510 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800511 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700512 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800513 mSystemReady(systemReady),
514 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800515{
Eric Laurent296fb132015-05-01 11:38:42 -0700516 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800517}
518
519AudioFlinger::ThreadBase::~ThreadBase()
520{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700521 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700522 mConfigEvents.clear();
523
Eric Laurent81784c32012-11-19 14:55:58 -0800524 // do not lock the mutex in destructor
525 releaseWakeLock_l();
526 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800527 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800528 binder->unlinkToDeath(mDeathRecipient);
529 }
530}
531
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700532status_t AudioFlinger::ThreadBase::readyToRun()
533{
534 status_t status = initCheck();
535 if (status == NO_ERROR) {
536 ALOGI("AudioFlinger's thread %p ready to run", this);
537 } else {
538 ALOGE("No working audio driver found.");
539 }
540 return status;
541}
542
Eric Laurent81784c32012-11-19 14:55:58 -0800543void AudioFlinger::ThreadBase::exit()
544{
545 ALOGV("ThreadBase::exit");
546 // do any cleanup required for exit to succeed
547 preExit();
548 {
549 // This lock prevents the following race in thread (uniprocessor for illustration):
550 // if (!exitPending()) {
551 // // context switch from here to exit()
552 // // exit() calls requestExit(), what exitPending() observes
553 // // exit() calls signal(), which is dropped since no waiters
554 // // context switch back from exit() to here
555 // mWaitWorkCV.wait(...);
556 // // now thread is hung
557 // }
558 AutoMutex lock(mLock);
559 requestExit();
560 mWaitWorkCV.broadcast();
561 }
562 // When Thread::requestExitAndWait is made virtual and this method is renamed to
563 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
564 requestExitAndWait();
565}
566
567status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
568{
Eric Laurent81784c32012-11-19 14:55:58 -0800569 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
570 Mutex::Autolock _l(mLock);
571
Eric Laurent10351942014-05-08 18:49:52 -0700572 return sendSetParameterConfigEvent_l(keyValuePairs);
573}
574
575// sendConfigEvent_l() must be called with ThreadBase::mLock held
576// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
577status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
578{
579 status_t status = NO_ERROR;
580
Eric Laurent72e3f392015-05-20 14:43:50 -0700581 if (event->mRequiresSystemReady && !mSystemReady) {
582 event->mWaitStatus = false;
583 mPendingConfigEvents.add(event);
584 return status;
585 }
Eric Laurent10351942014-05-08 18:49:52 -0700586 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700587 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800588 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700589 mLock.unlock();
590 {
591 Mutex::Autolock _l(event->mLock);
592 while (event->mWaitStatus) {
593 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
594 event->mStatus = TIMED_OUT;
595 event->mWaitStatus = false;
596 }
597 }
598 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800599 }
Eric Laurent10351942014-05-08 18:49:52 -0700600 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800601 return status;
602}
603
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700604void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800605{
606 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700607 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800608}
609
610// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800612{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700613 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700614 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800615}
616
Mikhail Naganov83f04272017-02-07 10:45:09 -0800617void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700618{
619 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800620 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700621}
622
Eric Laurent81784c32012-11-19 14:55:58 -0800623// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800624void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
625 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800626{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800627 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700628 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800629}
630
Eric Laurent10351942014-05-08 18:49:52 -0700631// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
632status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800633{
Andy Hung2ddee192015-12-18 17:34:44 -0800634 sp<ConfigEvent> configEvent;
635 AudioParameter param(keyValuePair);
636 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700637 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800638 setMasterMono_l(value != 0);
639 if (param.size() == 1) {
640 return NO_ERROR; // should be a solo parameter - we don't pass down
641 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700642 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800643 configEvent = new SetParameterConfigEvent(param.toString());
644 } else {
645 configEvent = new SetParameterConfigEvent(keyValuePair);
646 }
Eric Laurent10351942014-05-08 18:49:52 -0700647 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700648}
649
Eric Laurent1c333e22014-05-20 10:48:17 -0700650status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
651 const struct audio_patch *patch,
652 audio_patch_handle_t *handle)
653{
654 Mutex::Autolock _l(mLock);
655 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
656 status_t status = sendConfigEvent_l(configEvent);
657 if (status == NO_ERROR) {
658 CreateAudioPatchConfigEventData *data =
659 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
660 *handle = data->mHandle;
661 }
662 return status;
663}
664
665status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
666 const audio_patch_handle_t handle)
667{
668 Mutex::Autolock _l(mLock);
669 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
670 return sendConfigEvent_l(configEvent);
671}
672
673
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700674// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700675void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700676{
Eric Laurent10351942014-05-08 18:49:52 -0700677 bool configChanged = false;
678
Eric Laurent81784c32012-11-19 14:55:58 -0800679 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700680 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700681 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800682 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700683 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700684 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700685 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
686 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800687 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700688 true /*asynchronous*/);
689 if (err != 0) {
690 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700691 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700692 }
693 } break;
694 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700695 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700696 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700697 } break;
698 case CFG_EVENT_SET_PARAMETER: {
699 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
700 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
701 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700702 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
703 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700704 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700705 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700706 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700707 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700708 CreateAudioPatchConfigEventData *data =
709 (CreateAudioPatchConfigEventData *)event->mData.get();
710 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700711 const audio_devices_t newDevice = getDevice();
712 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
713 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
714 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700715 } break;
716 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700717 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700718 ReleaseAudioPatchConfigEventData *data =
719 (ReleaseAudioPatchConfigEventData *)event->mData.get();
720 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700721 const audio_devices_t newDevice = getDevice();
722 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
723 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
724 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700725 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700726 default:
Eric Laurent10351942014-05-08 18:49:52 -0700727 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700728 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800729 }
Eric Laurent10351942014-05-08 18:49:52 -0700730 {
731 Mutex::Autolock _l(event->mLock);
732 if (event->mWaitStatus) {
733 event->mWaitStatus = false;
734 event->mCond.signal();
735 }
736 }
737 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
738 }
739
740 if (configChanged) {
741 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800742 }
Eric Laurent81784c32012-11-19 14:55:58 -0800743}
744
Marco Nelissenb2208842014-02-07 14:00:50 -0800745String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
746 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700747 const audio_channel_representation_t representation =
748 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700749
750 switch (representation) {
751 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
752 if (output) {
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
756 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
757 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
758 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
759 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
761 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
763 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
770 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
771 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
772 } else {
773 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
774 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
775 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
776 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
777 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
781 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
782 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
783 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
784 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
785 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
786 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
787 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
788 }
789 const int len = s.length();
790 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700791 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700792 s.unlockBuffer(len - 2); // remove trailing ", "
793 }
794 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800795 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700796 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
797 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
798 return s;
799 default:
800 s.appendFormat("unknown mask, representation:%d bits:%#x",
801 representation, audio_channel_mask_get_bits(mask));
802 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800803 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800804}
805
Glenn Kasten0f11b512014-01-31 16:18:54 -0800806void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800807{
808 const size_t SIZE = 256;
809 char buffer[SIZE];
810 String8 result;
811
812 bool locked = AudioFlinger::dumpTryLock(mLock);
813 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700814 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800815 }
816
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800817 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, " I/O handle: %d\n", mId);
819 dprintf(fd, " TID: %d\n", getTid());
820 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700821 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700822 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700823 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700824 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700825 dprintf(fd, " Channel count: %u\n", mChannelCount);
826 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800827 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700828 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700829 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700830 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800831 size_t numConfig = mConfigEvents.size();
832 if (numConfig) {
833 for (size_t i = 0; i < numConfig; i++) {
834 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700835 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800836 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800838 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700839 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800840 }
Andy Hung293558a2017-03-21 12:19:20 -0700841 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700842 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
843 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800844 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800845
846 if (locked) {
847 mLock.unlock();
848 }
849}
850
851void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
852{
853 const size_t SIZE = 256;
854 char buffer[SIZE];
855 String8 result;
856
Marco Nelissenb2208842014-02-07 14:00:50 -0800857 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000858 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800859 write(fd, buffer, strlen(buffer));
860
Marco Nelissenb2208842014-02-07 14:00:50 -0800861 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800862 sp<EffectChain> chain = mEffectChains[i];
863 if (chain != 0) {
864 chain->dump(fd, args);
865 }
866 }
867}
868
Andy Hungdae27702016-10-31 14:01:16 -0700869void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800870{
871 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700872 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800873}
874
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100875String16 AudioFlinger::ThreadBase::getWakeLockTag()
876{
877 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800878 case MIXER:
879 return String16("AudioMix");
880 case DIRECT:
881 return String16("AudioDirectOut");
882 case DUPLICATING:
883 return String16("AudioDup");
884 case RECORD:
885 return String16("AudioIn");
886 case OFFLOAD:
887 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800888 case MMAP:
889 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800890 default:
891 ALOG_ASSERT(false);
892 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100893 }
894}
895
Andy Hungdae27702016-10-31 14:01:16 -0700896void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800897{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800898 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800899 if (mPowerManager != 0) {
900 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700901 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
902 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700903 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100904 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700905 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700906 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800907 if (status == NO_ERROR) {
908 mWakeLockToken = binder;
909 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800910 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800911 }
Wei Jia3f273d12015-11-24 09:06:49 -0800912
Andy Hung3f0c9022016-01-15 17:49:46 -0800913 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800914 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
915 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800916}
917
918void AudioFlinger::ThreadBase::releaseWakeLock()
919{
920 Mutex::Autolock _l(mLock);
921 releaseWakeLock_l();
922}
923
924void AudioFlinger::ThreadBase::releaseWakeLock_l()
925{
Andy Hung3f0c9022016-01-15 17:49:46 -0800926 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800927 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800928 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800929 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700930 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
931 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
933 mWakeLockToken.clear();
934 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800935}
936
937void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700938 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800939 // use checkService() to avoid blocking if power service is not up yet
940 sp<IBinder> binder =
941 defaultServiceManager()->checkService(String16("power"));
942 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800943 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800944 } else {
945 mPowerManager = interface_cast<IPowerManager>(binder);
946 binder->linkToDeath(mDeathRecipient);
947 }
948 }
949}
950
Andy Hungd01b0f12016-11-07 16:10:30 -0800951void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800952 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700953
954#if !LOG_NDEBUG
955 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800956 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700957 s << uid << " ";
958 }
959 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
960#endif
961
Andy Hung438e7572015-12-14 15:51:17 -0800962 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
963 if (mSystemReady) {
964 ALOGE("no wake lock to update, but system ready!");
965 } else {
966 ALOGW("no wake lock to update, system not ready yet");
967 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800968 return;
969 }
970 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800971 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
972 status_t status = mPowerManager->updateWakeLockUids(
973 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
974 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800975 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800976 }
977}
978
Eric Laurent81784c32012-11-19 14:55:58 -0800979void AudioFlinger::ThreadBase::clearPowerManager()
980{
981 Mutex::Autolock _l(mLock);
982 releaseWakeLock_l();
983 mPowerManager.clear();
984}
985
Glenn Kasten0f11b512014-01-31 16:18:54 -0800986void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800987{
988 sp<ThreadBase> thread = mThread.promote();
989 if (thread != 0) {
990 thread->clearPowerManager();
991 }
992 ALOGW("power manager service died !!!");
993}
994
995void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800996 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800997{
998 Mutex::Autolock _l(mLock);
999 setEffectSuspended_l(type, suspend, sessionId);
1000}
1001
1002void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001003 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001004{
1005 sp<EffectChain> chain = getEffectChain_l(sessionId);
1006 if (chain != 0) {
1007 if (type != NULL) {
1008 chain->setEffectSuspended_l(type, suspend);
1009 } else {
1010 chain->setEffectSuspendedAll_l(suspend);
1011 }
1012 }
1013
1014 updateSuspendedSessions_l(type, suspend, sessionId);
1015}
1016
1017void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1018{
1019 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1020 if (index < 0) {
1021 return;
1022 }
1023
1024 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1025 mSuspendedSessions.valueAt(index);
1026
1027 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001028 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001029 for (int j = 0; j < desc->mRefCount; j++) {
1030 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1031 chain->setEffectSuspendedAll_l(true);
1032 } else {
1033 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1034 desc->mType.timeLow);
1035 chain->setEffectSuspended_l(&desc->mType, true);
1036 }
1037 }
1038 }
1039}
1040
1041void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1042 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001043 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001044{
1045 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1046
1047 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1048
1049 if (suspend) {
1050 if (index >= 0) {
1051 sessionEffects = mSuspendedSessions.valueAt(index);
1052 } else {
1053 mSuspendedSessions.add(sessionId, sessionEffects);
1054 }
1055 } else {
1056 if (index < 0) {
1057 return;
1058 }
1059 sessionEffects = mSuspendedSessions.valueAt(index);
1060 }
1061
1062
1063 int key = EffectChain::kKeyForSuspendAll;
1064 if (type != NULL) {
1065 key = type->timeLow;
1066 }
1067 index = sessionEffects.indexOfKey(key);
1068
1069 sp<SuspendedSessionDesc> desc;
1070 if (suspend) {
1071 if (index >= 0) {
1072 desc = sessionEffects.valueAt(index);
1073 } else {
1074 desc = new SuspendedSessionDesc();
1075 if (type != NULL) {
1076 desc->mType = *type;
1077 }
1078 sessionEffects.add(key, desc);
1079 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1080 }
1081 desc->mRefCount++;
1082 } else {
1083 if (index < 0) {
1084 return;
1085 }
1086 desc = sessionEffects.valueAt(index);
1087 if (--desc->mRefCount == 0) {
1088 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1089 sessionEffects.removeItemsAt(index);
1090 if (sessionEffects.isEmpty()) {
1091 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1092 sessionId);
1093 mSuspendedSessions.removeItem(sessionId);
1094 }
1095 }
1096 }
1097 if (!sessionEffects.isEmpty()) {
1098 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1099 }
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(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 Mutex::Autolock _l(mLock);
1107 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1108}
1109
1110void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1111 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001112 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001113{
1114 if (mType != RECORD) {
1115 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1116 // another session. This gives the priority to well behaved effect control panels
1117 // and applications not using global effects.
1118 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1119 // global effects
1120 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1121 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1122 }
1123 }
1124
1125 sp<EffectChain> chain = getEffectChain_l(sessionId);
1126 if (chain != 0) {
1127 chain->checkSuspendOnEffectEnabled(effect, enabled);
1128 }
1129}
1130
Eric Laurent4c415062016-06-17 16:14:16 -07001131// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1132status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1133 const effect_descriptor_t *desc, audio_session_t sessionId)
1134{
1135 // No global effect sessions on record threads
1136 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1137 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1138 desc->name, mThreadName);
1139 return BAD_VALUE;
1140 }
1141 // only pre processing effects on record thread
1142 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1143 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1144 desc->name, mThreadName);
1145 return BAD_VALUE;
1146 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001147
1148 // always allow effects without processing load or latency
1149 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1150 return NO_ERROR;
1151 }
1152
Eric Laurent4c415062016-06-17 16:14:16 -07001153 audio_input_flags_t flags = mInput->flags;
1154 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1155 if (flags & AUDIO_INPUT_FLAG_RAW) {
1156 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1157 desc->name, mThreadName);
1158 return BAD_VALUE;
1159 }
1160 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1161 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1162 desc->name, mThreadName);
1163 return BAD_VALUE;
1164 }
1165 }
1166 return NO_ERROR;
1167}
1168
1169// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1170status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1171 const effect_descriptor_t *desc, audio_session_t sessionId)
1172{
1173 // no preprocessing on playback threads
1174 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1175 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1176 " thread %s", desc->name, mThreadName);
1177 return BAD_VALUE;
1178 }
1179
1180 switch (mType) {
1181 case MIXER: {
1182 // Reject any effect on mixer multichannel sinks.
1183 // TODO: fix both format and multichannel issues with effects.
1184 if (mChannelCount != FCC_2) {
1185 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1186 " thread %s", desc->name, mChannelCount, mThreadName);
1187 return BAD_VALUE;
1188 }
1189 audio_output_flags_t flags = mOutput->flags;
1190 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1191 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1192 // global effects are applied only to non fast tracks if they are SW
1193 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1194 break;
1195 }
1196 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1197 // only post processing on output stage session
1198 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1199 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1200 " on output stage session", desc->name);
1201 return BAD_VALUE;
1202 }
1203 } else {
1204 // no restriction on effects applied on non fast tracks
1205 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1206 break;
1207 }
1208 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001209
1210 // always allow effects without processing load or latency
1211 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1212 break;
1213 }
Eric Laurent4c415062016-06-17 16:14:16 -07001214 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1215 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1216 desc->name);
1217 return BAD_VALUE;
1218 }
1219 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1220 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1221 " in fast mode", desc->name);
1222 return BAD_VALUE;
1223 }
1224 }
1225 } break;
1226 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001227 // nothing actionable on offload threads, if the effect:
1228 // - is offloadable: the effect can be created
1229 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1230 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001231 break;
1232 case DIRECT:
1233 // Reject any effect on Direct output threads for now, since the format of
1234 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1235 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1236 desc->name, mThreadName);
1237 return BAD_VALUE;
1238 case DUPLICATING:
1239 // Reject any effect on mixer multichannel sinks.
1240 // TODO: fix both format and multichannel issues with effects.
1241 if (mChannelCount != FCC_2) {
1242 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1243 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1244 return BAD_VALUE;
1245 }
1246 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1247 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1248 " thread %s", desc->name, mThreadName);
1249 return BAD_VALUE;
1250 }
1251 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1252 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1253 " DUPLICATING thread %s", desc->name, mThreadName);
1254 return BAD_VALUE;
1255 }
1256 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1257 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1258 " DUPLICATING thread %s", desc->name, mThreadName);
1259 return BAD_VALUE;
1260 }
1261 break;
1262 default:
1263 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1264 }
1265
1266 return NO_ERROR;
1267}
1268
Eric Laurent81784c32012-11-19 14:55:58 -08001269// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1270sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1271 const sp<AudioFlinger::Client>& client,
1272 const sp<IEffectClient>& effectClient,
1273 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001274 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001275 effect_descriptor_t *desc,
1276 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001277 status_t *status,
1278 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001279{
1280 sp<EffectModule> effect;
1281 sp<EffectHandle> handle;
1282 status_t lStatus;
1283 sp<EffectChain> chain;
1284 bool chainCreated = false;
1285 bool effectCreated = false;
1286 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001287 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001288
1289 lStatus = initCheck();
1290 if (lStatus != NO_ERROR) {
1291 ALOGW("createEffect_l() Audio driver not initialized.");
1292 goto Exit;
1293 }
1294
Eric Laurent81784c32012-11-19 14:55:58 -08001295 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1296
1297 { // scope for mLock
1298 Mutex::Autolock _l(mLock);
1299
Eric Laurent4c415062016-06-17 16:14:16 -07001300 lStatus = checkEffectCompatibility_l(desc, sessionId);
1301 if (lStatus != NO_ERROR) {
1302 goto Exit;
1303 }
1304
Eric Laurent81784c32012-11-19 14:55:58 -08001305 // check for existing effect chain with the requested audio session
1306 chain = getEffectChain_l(sessionId);
1307 if (chain == 0) {
1308 // create a new chain for this session
1309 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1310 chain = new EffectChain(this, sessionId);
1311 addEffectChain_l(chain);
1312 chain->setStrategy(getStrategyForSession_l(sessionId));
1313 chainCreated = true;
1314 } else {
1315 effect = chain->getEffectFromDesc_l(desc);
1316 }
1317
1318 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1319
1320 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001321 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001322 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001323 lStatus = AudioSystem::registerEffect(
1324 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001325 if (lStatus != NO_ERROR) {
1326 goto Exit;
1327 }
1328 effectRegistered = true;
1329 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001330 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001331 if (lStatus != NO_ERROR) {
1332 goto Exit;
1333 }
1334 effectCreated = true;
1335
1336 effect->setDevice(mOutDevice);
1337 effect->setDevice(mInDevice);
1338 effect->setMode(mAudioFlinger->getMode());
1339 effect->setAudioSource(mAudioSource);
1340 }
1341 // create effect handle and connect it to effect module
1342 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001343 lStatus = handle->initCheck();
1344 if (lStatus == OK) {
1345 lStatus = effect->addHandle(handle.get());
1346 }
Eric Laurent81784c32012-11-19 14:55:58 -08001347 if (enabled != NULL) {
1348 *enabled = (int)effect->isEnabled();
1349 }
1350 }
1351
1352Exit:
1353 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1354 Mutex::Autolock _l(mLock);
1355 if (effectCreated) {
1356 chain->removeEffect_l(effect);
1357 }
1358 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001359 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001360 }
1361 if (chainCreated) {
1362 removeEffectChain_l(chain);
1363 }
1364 handle.clear();
1365 }
1366
Glenn Kasten9156ef32013-08-06 15:39:08 -07001367 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001368 return handle;
1369}
1370
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001371void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1372 bool unpinIfLast)
1373{
1374 bool remove = false;
1375 sp<EffectModule> effect;
1376 {
1377 Mutex::Autolock _l(mLock);
1378
1379 effect = handle->effect().promote();
1380 if (effect == 0) {
1381 return;
1382 }
1383 // restore suspended effects if the disconnected handle was enabled and the last one.
1384 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1385 if (remove) {
1386 removeEffect_l(effect, true);
1387 }
1388 }
1389 if (remove) {
1390 mAudioFlinger->updateOrphanEffectChains(effect);
1391 AudioSystem::unregisterEffect(effect->id());
1392 if (handle->enabled()) {
1393 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1394 }
1395 }
1396}
1397
Glenn Kastend848eb42016-03-08 13:42:11 -08001398sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1399 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001400{
1401 Mutex::Autolock _l(mLock);
1402 return getEffect_l(sessionId, effectId);
1403}
1404
Glenn Kastend848eb42016-03-08 13:42:11 -08001405sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1406 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001407{
1408 sp<EffectChain> chain = getEffectChain_l(sessionId);
1409 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1410}
1411
1412// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1413// PlaybackThread::mLock held
1414status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1415{
1416 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001417 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001418 sp<EffectChain> chain = getEffectChain_l(sessionId);
1419 bool chainCreated = false;
1420
Eric Laurent5baf2af2013-09-12 17:37:00 -07001421 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1422 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1423 this, effect->desc().name, effect->desc().flags);
1424
Eric Laurent81784c32012-11-19 14:55:58 -08001425 if (chain == 0) {
1426 // create a new chain for this session
1427 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1428 chain = new EffectChain(this, sessionId);
1429 addEffectChain_l(chain);
1430 chain->setStrategy(getStrategyForSession_l(sessionId));
1431 chainCreated = true;
1432 }
1433 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1434
1435 if (chain->getEffectFromId_l(effect->id()) != 0) {
1436 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1437 this, effect->desc().name, chain.get());
1438 return BAD_VALUE;
1439 }
1440
Eric Laurent5baf2af2013-09-12 17:37:00 -07001441 effect->setOffloaded(mType == OFFLOAD, mId);
1442
Eric Laurent81784c32012-11-19 14:55:58 -08001443 status_t status = chain->addEffect_l(effect);
1444 if (status != NO_ERROR) {
1445 if (chainCreated) {
1446 removeEffectChain_l(chain);
1447 }
1448 return status;
1449 }
1450
1451 effect->setDevice(mOutDevice);
1452 effect->setDevice(mInDevice);
1453 effect->setMode(mAudioFlinger->getMode());
1454 effect->setAudioSource(mAudioSource);
1455 return NO_ERROR;
1456}
1457
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001458void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001459
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001460 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001461 effect_descriptor_t desc = effect->desc();
1462 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1463 detachAuxEffect_l(effect->id());
1464 }
1465
1466 sp<EffectChain> chain = effect->chain().promote();
1467 if (chain != 0) {
1468 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001469 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001470 removeEffectChain_l(chain);
1471 }
1472 } else {
1473 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1474 }
1475}
1476
1477void AudioFlinger::ThreadBase::lockEffectChains_l(
1478 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1479{
1480 effectChains = mEffectChains;
1481 for (size_t i = 0; i < mEffectChains.size(); i++) {
1482 mEffectChains[i]->lock();
1483 }
1484}
1485
1486void AudioFlinger::ThreadBase::unlockEffectChains(
1487 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1488{
1489 for (size_t i = 0; i < effectChains.size(); i++) {
1490 effectChains[i]->unlock();
1491 }
1492}
1493
Glenn Kastend848eb42016-03-08 13:42:11 -08001494sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001495{
1496 Mutex::Autolock _l(mLock);
1497 return getEffectChain_l(sessionId);
1498}
1499
Glenn Kastend848eb42016-03-08 13:42:11 -08001500sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1501 const
Eric Laurent81784c32012-11-19 14:55:58 -08001502{
1503 size_t size = mEffectChains.size();
1504 for (size_t i = 0; i < size; i++) {
1505 if (mEffectChains[i]->sessionId() == sessionId) {
1506 return mEffectChains[i];
1507 }
1508 }
1509 return 0;
1510}
1511
1512void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1513{
1514 Mutex::Autolock _l(mLock);
1515 size_t size = mEffectChains.size();
1516 for (size_t i = 0; i < size; i++) {
1517 mEffectChains[i]->setMode_l(mode);
1518 }
1519}
1520
Eric Laurent83b88082014-06-20 18:31:16 -07001521void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1522{
1523 config->type = AUDIO_PORT_TYPE_MIX;
1524 config->ext.mix.handle = mId;
1525 config->sample_rate = mSampleRate;
1526 config->format = mFormat;
1527 config->channel_mask = mChannelMask;
1528 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1529 AUDIO_PORT_CONFIG_FORMAT;
1530}
1531
Eric Laurent72e3f392015-05-20 14:43:50 -07001532void AudioFlinger::ThreadBase::systemReady()
1533{
1534 Mutex::Autolock _l(mLock);
1535 if (mSystemReady) {
1536 return;
1537 }
1538 mSystemReady = true;
1539
1540 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1541 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1542 }
1543 mPendingConfigEvents.clear();
1544}
1545
Andy Hungdae27702016-10-31 14:01:16 -07001546template <typename T>
1547ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1548 ssize_t index = mActiveTracks.indexOf(track);
1549 if (index >= 0) {
1550 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1551 return index;
1552 }
1553 mActiveTracksGeneration++;
1554 mLatestActiveTrack = track;
1555 ++mBatteryCounter[track->uid()].second;
1556 return mActiveTracks.add(track);
1557}
1558
1559template <typename T>
1560ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1561 ssize_t index = mActiveTracks.remove(track);
1562 if (index < 0) {
1563 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1564 return index;
1565 }
1566 mActiveTracksGeneration++;
1567 --mBatteryCounter[track->uid()].second;
1568 // mLatestActiveTrack is not cleared even if is the same as track.
1569 return index;
1570}
1571
1572template <typename T>
1573void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1574 for (const sp<T> &track : mActiveTracks) {
1575 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1576 }
1577 mLastActiveTracksGeneration = mActiveTracksGeneration;
1578 mActiveTracks.clear();
1579 mLatestActiveTrack.clear();
1580 mBatteryCounter.clear();
1581}
1582
1583template <typename T>
1584void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1585 sp<ThreadBase> thread, bool force) {
1586 // Updates ActiveTracks client uids to the thread wakelock.
1587 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1588 thread->updateWakeLockUids_l(getWakeLockUids());
1589 mLastActiveTracksGeneration = mActiveTracksGeneration;
1590 }
1591
1592 // Updates BatteryNotifier uids
1593 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1594 const uid_t uid = it->first;
1595 ssize_t &previous = it->second.first;
1596 ssize_t &current = it->second.second;
1597 if (current > 0) {
1598 if (previous == 0) {
1599 BatteryNotifier::getInstance().noteStartAudio(uid);
1600 }
1601 previous = current;
1602 ++it;
1603 } else if (current == 0) {
1604 if (previous > 0) {
1605 BatteryNotifier::getInstance().noteStopAudio(uid);
1606 }
1607 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1608 } else /* (current < 0) */ {
1609 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1610 }
1611 }
1612}
Eric Laurent83b88082014-06-20 18:31:16 -07001613
Eric Laurent6acd1d42017-01-04 14:23:29 -08001614void AudioFlinger::ThreadBase::broadcast_l()
1615{
1616 // Thread could be blocked waiting for async
1617 // so signal it to handle state changes immediately
1618 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1619 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1620 mSignalPending = true;
1621 mWaitWorkCV.broadcast();
1622}
1623
Eric Laurent81784c32012-11-19 14:55:58 -08001624// ----------------------------------------------------------------------------
1625// Playback
1626// ----------------------------------------------------------------------------
1627
1628AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1629 AudioStreamOut* output,
1630 audio_io_handle_t id,
1631 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001632 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001633 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001634 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001635 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001636 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001637 mMixerBuffer(NULL),
1638 mMixerBufferSize(0),
1639 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1640 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001641 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001642 mEffectBuffer(NULL),
1643 mEffectBufferSize(0),
1644 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1645 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001646 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001647 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001648 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001649 // mStreamTypes[] initialized in constructor body
1650 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001651 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001652 mMixerStatus(MIXER_IDLE),
1653 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001654 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001655 mBytesRemaining(0),
1656 mCurrentWriteLength(0),
1657 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001658 mWriteAckSequence(0),
1659 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001660 mScreenState(AudioFlinger::mScreenState),
1661 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001662 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001663 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001664{
Glenn Kastend7dca052015-03-05 16:05:54 -08001665 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1666 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001667
1668 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1669 // it would be safer to explicitly pass initial masterVolume/masterMute as
1670 // parameter.
1671 //
1672 // If the HAL we are using has support for master volume or master mute,
1673 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1674 // and the mute set to false).
1675 mMasterVolume = audioFlinger->masterVolume_l();
1676 mMasterMute = audioFlinger->masterMute_l();
1677 if (mOutput && mOutput->audioHwDev) {
1678 if (mOutput->audioHwDev->canSetMasterVolume()) {
1679 mMasterVolume = 1.0;
1680 }
1681
1682 if (mOutput->audioHwDev->canSetMasterMute()) {
1683 mMasterMute = false;
1684 }
1685 }
1686
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001687 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001688
Eric Laurent223fd5c2014-11-11 13:43:36 -08001689 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001690 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001691 stream = (audio_stream_type_t) (stream + 1)) {
1692 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1693 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1694 }
Eric Laurent81784c32012-11-19 14:55:58 -08001695}
1696
1697AudioFlinger::PlaybackThread::~PlaybackThread()
1698{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001699 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001700 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001701 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001702 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001703}
1704
1705void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1706{
1707 dumpInternals(fd, args);
1708 dumpTracks(fd, args);
1709 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001710 dprintf(fd, " Local log:\n");
1711 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001712}
1713
Glenn Kasten0f11b512014-01-31 16:18:54 -08001714void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001715{
1716 const size_t SIZE = 256;
1717 char buffer[SIZE];
1718 String8 result;
1719
Marco Nelissenb2208842014-02-07 14:00:50 -08001720 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001721 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1722 const stream_type_t *st = &mStreamTypes[i];
1723 if (i > 0) {
1724 result.appendFormat(", ");
1725 }
1726 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1727 if (st->mute) {
1728 result.append("M");
1729 }
1730 }
1731 result.append("\n");
1732 write(fd, result.string(), result.length());
1733 result.clear();
1734
Eric Laurent81784c32012-11-19 14:55:58 -08001735 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1736 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001737 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001738 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001739
1740 size_t numtracks = mTracks.size();
1741 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001742 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001743 size_t numactiveseen = 0;
1744 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001745 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001746 Track::appendDumpHeader(result);
1747 for (size_t i = 0; i < numtracks; ++i) {
1748 sp<Track> track = mTracks[i];
1749 if (track != 0) {
1750 bool active = mActiveTracks.indexOf(track) >= 0;
1751 if (active) {
1752 numactiveseen++;
1753 }
1754 track->dump(buffer, SIZE, active);
1755 result.append(buffer);
1756 }
1757 }
1758 } else {
1759 result.append("\n");
1760 }
1761 if (numactiveseen != numactive) {
1762 // some tracks in the active list were not in the tracks list
1763 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1764 " not in the track list\n");
1765 result.append(buffer);
1766 Track::appendDumpHeader(result);
1767 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001768 sp<Track> track = mActiveTracks[i];
1769 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001770 track->dump(buffer, SIZE, true);
1771 result.append(buffer);
1772 }
1773 }
1774 }
1775
1776 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001777}
1778
1779void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1780{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001781 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001782
1783 dumpBase(fd, args);
1784
Elliott Hughes87cebad2014-05-22 10:14:43 -07001785 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001786 dprintf(fd, " Last write occurred (msecs): %llu\n",
1787 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001788 dprintf(fd, " Total writes: %d\n", mNumWrites);
1789 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1790 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1791 dprintf(fd, " Suspend count: %d\n", mSuspended);
1792 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1793 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1794 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1795 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001796 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001797 AudioStreamOut *output = mOutput;
1798 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001799 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1800 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001801 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1802 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1803 if (mPipeSink.get() != nullptr) {
1804 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1805 }
1806 if (output != nullptr) {
1807 dprintf(fd, " Hal stream dump:\n");
1808 (void)output->stream->dump(fd);
1809 }
Eric Laurent81784c32012-11-19 14:55:58 -08001810}
1811
1812// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001813
1814void AudioFlinger::PlaybackThread::onFirstRef()
1815{
Glenn Kastend7dca052015-03-05 16:05:54 -08001816 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001817}
1818
1819// ThreadBase virtuals
1820void AudioFlinger::PlaybackThread::preExit()
1821{
1822 ALOGV(" preExit()");
1823 // FIXME this is using hard-coded strings but in the future, this functionality will be
1824 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001825 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1826 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001827}
1828
1829// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1830sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1831 const sp<AudioFlinger::Client>& client,
1832 audio_stream_type_t streamType,
1833 uint32_t sampleRate,
1834 audio_format_t format,
1835 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001836 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001837 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001838 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001839 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001840 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001841 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001842 status_t *status,
1843 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001844{
Glenn Kasten74935e42013-12-19 08:56:45 -08001845 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001846 sp<Track> track;
1847 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001848 audio_output_flags_t outputFlags = mOutput->flags;
1849
1850 // special case for FAST flag considered OK if fast mixer is present
1851 if (hasFastMixer()) {
1852 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1853 }
1854
1855 // Check if requested flags are compatible with output stream flags
1856 if ((*flags & outputFlags) != *flags) {
1857 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1858 *flags, outputFlags);
1859 *flags = (audio_output_flags_t)(*flags & outputFlags);
1860 }
Eric Laurent81784c32012-11-19 14:55:58 -08001861
Eric Laurent81784c32012-11-19 14:55:58 -08001862 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001863 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001864 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001865 // PCM data
1866 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001867 // TODO: extract as a data library function that checks that a computationally
1868 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001869 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001870 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1871 (channelMask == AUDIO_CHANNEL_OUT_MONO
1872 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001873 // hardware sample rate
1874 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001875 // normal mixer has an associated fast mixer
1876 hasFastMixer() &&
1877 // there are sufficient fast track slots available
1878 (mFastTrackAvailMask != 0)
1879 // FIXME test that MixerThread for this fast track has a capable output HAL
1880 // FIXME add a permission test also?
1881 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001882 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1883 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001884 // read the fast track multiplier property the first time it is needed
1885 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1886 if (ok != 0) {
1887 ALOGE("%s pthread_once failed: %d", __func__, ok);
1888 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001889 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001890 }
Eric Laurent4c415062016-06-17 16:14:16 -07001891
1892 // check compatibility with audio effects.
1893 { // scope for mLock
1894 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001895 for (audio_session_t session : {
1896 AUDIO_SESSION_OUTPUT_STAGE,
1897 AUDIO_SESSION_OUTPUT_MIX,
1898 sessionId,
1899 }) {
1900 sp<EffectChain> chain = getEffectChain_l(session);
1901 if (chain.get() != nullptr) {
1902 audio_output_flags_t old = *flags;
1903 chain->checkOutputFlagCompatibility(flags);
1904 if (old != *flags) {
1905 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1906 (int)session, (int)old, (int)*flags);
1907 }
Eric Laurent4c415062016-06-17 16:14:16 -07001908 }
1909 }
1910 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001911 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001912 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1913 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001914 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001915 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1916 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001917 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001918 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001919 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001920 audio_is_linear_pcm(format),
1921 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001922 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001923 }
1924 }
1925 // For normal PCM streaming tracks, update minimum frame count.
1926 // For compatibility with AudioTrack calculation, buffer depth is forced
1927 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1928 // This is probably too conservative, but legacy application code may depend on it.
1929 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001930 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001931 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001932 // this must match AudioTrack.cpp calculateMinFrameCount().
1933 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001934 uint32_t latencyMs = 0;
1935 lStatus = mOutput->stream->getLatency(&latencyMs);
1936 if (lStatus != OK) {
1937 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1938 goto Exit;
1939 }
Eric Laurent81784c32012-11-19 14:55:58 -08001940 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1941 if (minBufCount < 2) {
1942 minBufCount = 2;
1943 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001944 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1945 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001946 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001947 minBufCount * sourceFramesNeededWithTimestretch(
1948 sampleRate, mNormalFrameCount,
1949 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001950 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001951 frameCount = minFrameCount;
1952 }
Eric Laurent81784c32012-11-19 14:55:58 -08001953 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001954 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001955
Glenn Kastenc3df8382014-03-13 15:05:25 -07001956 switch (mType) {
1957
1958 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001959 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001960 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001961 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1962 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001963 sampleRate, format, channelMask, mOutput, mFormat);
1964 lStatus = BAD_VALUE;
1965 goto Exit;
1966 }
1967 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001968 break;
1969
1970 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001971 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001972 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1973 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001974 sampleRate, format, channelMask, mOutput, mFormat);
1975 lStatus = BAD_VALUE;
1976 goto Exit;
1977 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001978 break;
1979
1980 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001981 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001982 ALOGE("createTrack_l() Bad parameter: format %#x \""
1983 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001984 format, mOutput, mFormat);
1985 lStatus = BAD_VALUE;
1986 goto Exit;
1987 }
Andy Hungcd044842014-08-07 11:04:34 -07001988 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001989 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1990 lStatus = BAD_VALUE;
1991 goto Exit;
1992 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001993 break;
1994
Eric Laurent81784c32012-11-19 14:55:58 -08001995 }
1996
1997 lStatus = initCheck();
1998 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001999 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002000 goto Exit;
2001 }
2002
2003 { // scope for mLock
2004 Mutex::Autolock _l(mLock);
2005
2006 // all tracks in same audio session must share the same routing strategy otherwise
2007 // conflicts will happen when tracks are moved from one output to another by audio policy
2008 // manager
2009 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2010 for (size_t i = 0; i < mTracks.size(); ++i) {
2011 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002012 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002013 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2014 if (sessionId == t->sessionId() && strategy != actual) {
2015 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2016 strategy, actual);
2017 lStatus = BAD_VALUE;
2018 goto Exit;
2019 }
2020 }
2021 }
2022
Glenn Kastend79072e2016-01-06 08:41:20 -08002023 track = new Track(this, client, streamType, sampleRate, format,
2024 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002025 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002026
Glenn Kasten03003332013-08-06 15:40:54 -07002027 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2028 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002029 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002030 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002031 goto Exit;
2032 }
2033 mTracks.add(track);
2034
2035 sp<EffectChain> chain = getEffectChain_l(sessionId);
2036 if (chain != 0) {
2037 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2038 track->setMainBuffer(chain->inBuffer());
2039 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2040 chain->incTrackCnt();
2041 }
2042
Eric Laurent05067782016-06-01 18:27:28 -07002043 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002044 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2045 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2046 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08002047 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*isForApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002048 }
2049 }
2050
2051 lStatus = NO_ERROR;
2052
2053Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002054 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002055 return track;
2056}
2057
2058uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2059{
2060 return latency;
2061}
2062
2063uint32_t AudioFlinger::PlaybackThread::latency() const
2064{
2065 Mutex::Autolock _l(mLock);
2066 return latency_l();
2067}
2068uint32_t AudioFlinger::PlaybackThread::latency_l() const
2069{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002070 uint32_t latency;
2071 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2072 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002073 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002074 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002075}
2076
2077void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2078{
2079 Mutex::Autolock _l(mLock);
2080 // Don't apply master volume in SW if our HAL can do it for us.
2081 if (mOutput && mOutput->audioHwDev &&
2082 mOutput->audioHwDev->canSetMasterVolume()) {
2083 mMasterVolume = 1.0;
2084 } else {
2085 mMasterVolume = value;
2086 }
2087}
2088
2089void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2090{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002091 if (isDuplicating()) {
2092 return;
2093 }
Eric Laurent81784c32012-11-19 14:55:58 -08002094 Mutex::Autolock _l(mLock);
2095 // Don't apply master mute in SW if our HAL can do it for us.
2096 if (mOutput && mOutput->audioHwDev &&
2097 mOutput->audioHwDev->canSetMasterMute()) {
2098 mMasterMute = false;
2099 } else {
2100 mMasterMute = muted;
2101 }
2102}
2103
2104void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2105{
2106 Mutex::Autolock _l(mLock);
2107 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002108 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002109}
2110
2111void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2112{
2113 Mutex::Autolock _l(mLock);
2114 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002115 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002116}
2117
2118float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2119{
2120 Mutex::Autolock _l(mLock);
2121 return mStreamTypes[stream].volume;
2122}
2123
2124// addTrack_l() must be called with ThreadBase::mLock held
2125status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2126{
2127 status_t status = ALREADY_EXISTS;
2128
Eric Laurent81784c32012-11-19 14:55:58 -08002129 if (mActiveTracks.indexOf(track) < 0) {
2130 // the track is newly added, make sure it fills up all its
2131 // buffers before playing. This is to ensure the client will
2132 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002133 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002134 TrackBase::track_state state = track->mState;
2135 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002136 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002137 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002138 mLock.lock();
2139 // abort track was stopped/paused while we released the lock
2140 if (state != track->mState) {
2141 if (status == NO_ERROR) {
2142 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002143 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002144 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002145 mLock.lock();
2146 }
2147 return INVALID_OPERATION;
2148 }
2149 // abort if start is rejected by audio policy manager
2150 if (status != NO_ERROR) {
2151 return PERMISSION_DENIED;
2152 }
2153#ifdef ADD_BATTERY_DATA
2154 // to track the speaker usage
2155 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2156#endif
2157 }
2158
Eric Laurent51716182016-02-29 18:00:56 -08002159 // set retry count for buffer fill
2160 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002161 if (track->isStopping_1()) {
2162 track->mRetryCount = kMaxTrackStopRetriesOffload;
2163 } else {
2164 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2165 }
2166 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002167 } else {
2168 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002169 track->mFillingUpStatus =
2170 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002171 }
2172
Eric Laurent81784c32012-11-19 14:55:58 -08002173 track->mResetDone = false;
2174 track->mPresentationCompleteFrames = 0;
2175 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002176 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2177 if (chain != 0) {
2178 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2179 track->sessionId());
2180 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002181 }
2182
Andy Hung2148bf02016-11-28 19:01:02 -08002183 char buffer[256];
2184 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2185 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2186
Eric Laurent81784c32012-11-19 14:55:58 -08002187 status = NO_ERROR;
2188 }
2189
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002190 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002191 return status;
2192}
2193
Eric Laurentbfb1b832013-01-07 09:53:42 -08002194bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002195{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002196 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002197 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002198 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2199 track->mState = TrackBase::STOPPED;
2200 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002201 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002202 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002203 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002204 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002205
2206 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002207}
2208
2209void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2210{
2211 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002212
2213 char buffer[256];
2214 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2215 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2216
Eric Laurent81784c32012-11-19 14:55:58 -08002217 mTracks.remove(track);
2218 deleteTrackName_l(track->name());
2219 // redundant as track is about to be destroyed, for dumpsys only
2220 track->mName = -1;
2221 if (track->isFastTrack()) {
2222 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002223 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002224 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2225 mFastTrackAvailMask |= 1 << index;
2226 // redundant as track is about to be destroyed, for dumpsys only
2227 track->mFastIndex = -1;
2228 }
2229 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2230 if (chain != 0) {
2231 chain->decTrackCnt();
2232 }
2233}
2234
2235String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2236{
Eric Laurent81784c32012-11-19 14:55:58 -08002237 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002238 String8 out_s8;
2239 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2240 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002241 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002242 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002243}
2244
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002245void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002246 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2247 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002248
Eric Laurent73e26b62015-04-27 16:55:58 -07002249 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002250
2251 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002252 case AUDIO_OUTPUT_OPENED:
2253 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002254 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002255 desc->mChannelMask = mChannelMask;
2256 desc->mSamplingRate = mSampleRate;
2257 desc->mFormat = mFormat;
2258 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002259 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002260 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002261 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002262 break;
2263
Eric Laurent73e26b62015-04-27 16:55:58 -07002264 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002265 default:
2266 break;
2267 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002268 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002269}
2270
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002271void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002272{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002273 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002274}
2275
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002276void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002277{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002278 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002279}
2280
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002281void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002282{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002283 mCallbackThread->setAsyncError();
2284}
2285
Eric Laurent3b4529e2013-09-05 18:09:19 -07002286void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002287{
2288 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002289 // reject out of sequence requests
2290 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2291 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002292 mWaitWorkCV.signal();
2293 }
2294}
2295
Eric Laurent3b4529e2013-09-05 18:09:19 -07002296void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002297{
2298 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002299 // reject out of sequence requests
2300 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2301 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002302 mWaitWorkCV.signal();
2303 }
2304}
2305
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002306void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002307{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002308 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002309 mSampleRate = mOutput->getSampleRate();
2310 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002311 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002312 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002313 }
Andy Hung9a592762014-07-21 21:56:01 -07002314 if ((mType == MIXER || mType == DUPLICATING)
2315 && !isValidPcmSinkChannelMask(mChannelMask)) {
2316 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2317 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002318 }
Andy Hunge5412692014-05-16 11:25:07 -07002319 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002320
2321 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002322 status_t result = mOutput->stream->getFormat(&mHALFormat);
2323 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002324 // Get format from the shim, which will be different than the HAL format
2325 // if playing compressed audio over HDMI passthrough.
2326 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002327 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002328 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002329 }
Andy Hung6146c082014-03-18 11:56:15 -07002330 if ((mType == MIXER || mType == DUPLICATING)
2331 && !isValidPcmSinkFormat(mFormat)) {
2332 LOG_FATAL("HAL format %#x not supported for mixed output",
2333 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002334 }
Phil Burk062e67a2015-02-11 13:40:50 -08002335 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002336 result = mOutput->stream->getBufferSize(&mBufferSize);
2337 LOG_ALWAYS_FATAL_IF(result != OK,
2338 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002339 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002340 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002341 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002342 mFrameCount);
2343 }
2344
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002345 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2346 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002347 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002348 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002349 }
2350 }
2351
Eric Laurentd1f69b02014-12-15 14:33:13 -08002352 mHwSupportsPause = false;
2353 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002354 bool supportsPause = false, supportsResume = false;
2355 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2356 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002357 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002358 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002359 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002360 } else if (supportsResume) {
2361 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002362 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002363 }
2364 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002365 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2366 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2367 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002368
Andy Hungfbfc3952015-01-15 13:33:51 -08002369 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2370 // For best precision, we use float instead of the associated output
2371 // device format (typically PCM 16 bit).
2372
2373 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2374 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2375 mBufferSize = mFrameSize * mFrameCount;
2376
2377 // TODO: We currently use the associated output device channel mask and sample rate.
2378 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2379 // (if a valid mask) to avoid premature downmix.
2380 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2381 // instead of the output device sample rate to avoid loss of high frequency information.
2382 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2383 }
2384
Andy Hung09a50072014-02-27 14:30:47 -08002385 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002386 double multiplier = 1.0;
2387 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2388 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002389 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2390 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002391
Eric Laurent81784c32012-11-19 14:55:58 -08002392 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2393 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2394 maxNormalFrameCount = maxNormalFrameCount & ~15;
2395 if (maxNormalFrameCount < minNormalFrameCount) {
2396 maxNormalFrameCount = minNormalFrameCount;
2397 }
2398 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2399 if (multiplier <= 1.0) {
2400 multiplier = 1.0;
2401 } else if (multiplier <= 2.0) {
2402 if (2 * mFrameCount <= maxNormalFrameCount) {
2403 multiplier = 2.0;
2404 } else {
2405 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2406 }
2407 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002408 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002409 }
2410 }
2411 mNormalFrameCount = multiplier * mFrameCount;
2412 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002413 if (mType == MIXER || mType == DUPLICATING) {
2414 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2415 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002416 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002417 mNormalFrameCount);
2418
Andy Hung08fb1742015-05-31 23:22:10 -07002419 // Check if we want to throttle the processing to no more than 2x normal rate
2420 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002421 mThreadThrottleTimeMs = 0;
2422 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002423 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2424
Andy Hung010a1a12014-03-13 13:57:33 -07002425 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2426 // Originally this was int16_t[] array, need to remove legacy implications.
2427 free(mSinkBuffer);
2428 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002429 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2430 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2431 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002432 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002433
Andy Hung69aed5f2014-02-25 17:24:40 -08002434 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2435 // drives the output.
2436 free(mMixerBuffer);
2437 mMixerBuffer = NULL;
2438 if (mMixerBufferEnabled) {
2439 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2440 mMixerBufferSize = mNormalFrameCount * mChannelCount
2441 * audio_bytes_per_sample(mMixerBufferFormat);
2442 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2443 }
Andy Hung98ef9782014-03-04 14:46:50 -08002444 free(mEffectBuffer);
2445 mEffectBuffer = NULL;
2446 if (mEffectBufferEnabled) {
2447 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2448 mEffectBufferSize = mNormalFrameCount * mChannelCount
2449 * audio_bytes_per_sample(mEffectBufferFormat);
2450 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2451 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002452
Eric Laurent81784c32012-11-19 14:55:58 -08002453 // force reconfiguration of effect chains and engines to take new buffer size and audio
2454 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002455 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002456 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2457 // matter.
2458 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2459 Vector< sp<EffectChain> > effectChains = mEffectChains;
2460 for (size_t i = 0; i < effectChains.size(); i ++) {
2461 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2462 }
2463}
2464
2465
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002466status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002467{
2468 if (halFrames == NULL || dspFrames == NULL) {
2469 return BAD_VALUE;
2470 }
2471 Mutex::Autolock _l(mLock);
2472 if (initCheck() != NO_ERROR) {
2473 return INVALID_OPERATION;
2474 }
Andy Hung818e7a32016-02-16 18:08:07 -08002475 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002476 *halFrames = framesWritten;
2477
2478 if (isSuspended()) {
2479 // return an estimation of rendered frames when the output is suspended
2480 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002481 *dspFrames = (uint32_t)
2482 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002483 return NO_ERROR;
2484 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002485 status_t status;
2486 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002487 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002488 *dspFrames = (size_t)frames;
2489 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002490 }
2491}
2492
Eric Laurent4c415062016-06-17 16:14:16 -07002493// hasAudioSession_l() must be called with ThreadBase::mLock held
2494uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002495{
Eric Laurent81784c32012-11-19 14:55:58 -08002496 uint32_t result = 0;
2497 if (getEffectChain_l(sessionId) != 0) {
2498 result = EFFECT_SESSION;
2499 }
2500
2501 for (size_t i = 0; i < mTracks.size(); ++i) {
2502 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002503 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002504 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002505 if (track->isFastTrack()) {
2506 result |= FAST_SESSION;
2507 }
Eric Laurent81784c32012-11-19 14:55:58 -08002508 break;
2509 }
2510 }
2511
2512 return result;
2513}
2514
Glenn Kastend848eb42016-03-08 13:42:11 -08002515uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002516{
2517 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2518 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2519 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2520 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2521 }
2522 for (size_t i = 0; i < mTracks.size(); i++) {
2523 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002524 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002525 return AudioSystem::getStrategyForStream(track->streamType());
2526 }
2527 }
2528 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2529}
2530
2531
Phil Burk062e67a2015-02-11 13:40:50 -08002532AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002533{
2534 Mutex::Autolock _l(mLock);
2535 return mOutput;
2536}
2537
Phil Burk062e67a2015-02-11 13:40:50 -08002538AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002539{
2540 Mutex::Autolock _l(mLock);
2541 AudioStreamOut *output = mOutput;
2542 mOutput = NULL;
2543 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2544 // must push a NULL and wait for ack
2545 mOutputSink.clear();
2546 mPipeSink.clear();
2547 mNormalSink.clear();
2548 return output;
2549}
2550
2551// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002552sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002553{
2554 if (mOutput == NULL) {
2555 return NULL;
2556 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002557 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002558}
2559
2560uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2561{
2562 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2563}
2564
2565status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2566{
2567 if (!isValidSyncEvent(event)) {
2568 return BAD_VALUE;
2569 }
2570
2571 Mutex::Autolock _l(mLock);
2572
2573 for (size_t i = 0; i < mTracks.size(); ++i) {
2574 sp<Track> track = mTracks[i];
2575 if (event->triggerSession() == track->sessionId()) {
2576 (void) track->setSyncEvent(event);
2577 return NO_ERROR;
2578 }
2579 }
2580
2581 return NAME_NOT_FOUND;
2582}
2583
2584bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2585{
2586 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2587}
2588
2589void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2590 const Vector< sp<Track> >& tracksToRemove)
2591{
2592 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002593 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002594 for (size_t i = 0 ; i < count ; i++) {
2595 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002596 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002597 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002598 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599#ifdef ADD_BATTERY_DATA
2600 // to track the speaker usage
2601 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2602#endif
2603 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002604 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002605 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002606 }
Eric Laurent81784c32012-11-19 14:55:58 -08002607 }
2608 }
2609 }
Eric Laurent81784c32012-11-19 14:55:58 -08002610}
2611
2612void AudioFlinger::PlaybackThread::checkSilentMode_l()
2613{
2614 if (!mMasterMute) {
2615 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002616 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2617 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2618 return;
2619 }
Eric Laurent81784c32012-11-19 14:55:58 -08002620 if (property_get("ro.audio.silent", value, "0") > 0) {
2621 char *endptr;
2622 unsigned long ul = strtoul(value, &endptr, 0);
2623 if (*endptr == '\0' && ul != 0) {
2624 ALOGD("Silence is golden");
2625 // The setprop command will not allow a property to be changed after
2626 // the first time it is set, so we don't have to worry about un-muting.
2627 setMasterMute_l(true);
2628 }
2629 }
2630 }
2631}
2632
2633// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002634ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002635{
Eric Laurent81784c32012-11-19 14:55:58 -08002636 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002637 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002638 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002639
2640 // If an NBAIO sink is present, use it to write the normal mixer's submix
2641 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002642
Andy Hung010a1a12014-03-13 13:57:33 -07002643 const size_t count = mBytesRemaining / mFrameSize;
2644
Simon Wilson2d590962012-11-29 15:18:50 -08002645 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002646 // update the setpoint when AudioFlinger::mScreenState changes
2647 uint32_t screenState = AudioFlinger::mScreenState;
2648 if (screenState != mScreenState) {
2649 mScreenState = screenState;
2650 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2651 if (pipe != NULL) {
2652 pipe->setAvgFrames((mScreenState & 1) ?
2653 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2654 }
2655 }
Andy Hung010a1a12014-03-13 13:57:33 -07002656 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002657 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002658 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002659 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002660 } else {
2661 bytesWritten = framesWritten;
2662 }
2663 // otherwise use the HAL / AudioStreamOut directly
2664 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002665 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002666
Eric Laurentbfb1b832013-01-07 09:53:42 -08002667 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002668 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2669 mWriteAckSequence += 2;
2670 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002672 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002674 // FIXME We should have an implementation of timestamps for direct output threads.
2675 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002676 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002677
Eric Laurentbfb1b832013-01-07 09:53:42 -08002678 if (mUseAsyncWrite &&
2679 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2680 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002681 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002683 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002684 }
Eric Laurent81784c32012-11-19 14:55:58 -08002685 }
2686
Eric Laurent81784c32012-11-19 14:55:58 -08002687 mNumWrites++;
2688 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002689 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002690 return bytesWritten;
2691}
2692
2693void AudioFlinger::PlaybackThread::threadLoop_drain()
2694{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002695 bool supportsDrain = false;
2696 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002697 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2698 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002699 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2700 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002701 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002702 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002703 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002704 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002705 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002706 }
2707}
2708
2709void AudioFlinger::PlaybackThread::threadLoop_exit()
2710{
Eric Laurent275e8e92014-11-30 15:14:47 -08002711 {
2712 Mutex::Autolock _l(mLock);
2713 for (size_t i = 0; i < mTracks.size(); i++) {
2714 sp<Track> track = mTracks[i];
2715 track->invalidate();
2716 }
Andy Hungdae27702016-10-31 14:01:16 -07002717 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2718 // After we exit there are no more track changes sent to BatteryNotifier
2719 // because that requires an active threadLoop.
2720 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2721 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002722 }
Eric Laurent81784c32012-11-19 14:55:58 -08002723}
2724
2725/*
2726The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002727 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002728 - mActiveSleepTimeUs from activeSleepTimeUs()
2729 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002730 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2731 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002732 - maxPeriod from frame count and sample rate (MIXER only)
2733
2734The parameters that affect these derived values are:
2735 - frame count
2736 - frame size
2737 - sample rate
2738 - device type: A2DP or not
2739 - device latency
2740 - format: PCM or not
2741 - active sleep time
2742 - idle sleep time
2743*/
2744
2745void AudioFlinger::PlaybackThread::cacheParameters_l()
2746{
Andy Hung25c2dac2014-02-27 14:56:00 -08002747 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002748 mActiveSleepTimeUs = activeSleepTimeUs();
2749 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002750
2751 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2752 // truncating audio when going to standby.
2753 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2754 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2755 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2756 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2757 }
2758 }
Eric Laurent81784c32012-11-19 14:55:58 -08002759}
2760
Eric Laurent13084622016-05-17 10:51:49 -07002761bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002762{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002763 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002764 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002765 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002766 size_t size = mTracks.size();
2767 for (size_t i = 0; i < size; i++) {
2768 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002769 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002770 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002771 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002772 }
2773 }
Eric Laurent13084622016-05-17 10:51:49 -07002774 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002775}
2776
Haynes Mathew George05317d22016-05-03 16:34:26 -07002777void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2778{
2779 Mutex::Autolock _l(mLock);
2780 invalidateTracks_l(streamType);
2781}
2782
Eric Laurent81784c32012-11-19 14:55:58 -08002783status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2784{
Glenn Kastend848eb42016-03-08 13:42:11 -08002785 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002786 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2787 status_t result = EffectBufferHalInterface::mirror(
2788 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2789 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2790 &halInBuffer);
2791 if (result != OK) return result;
2792 halOutBuffer = halInBuffer;
2793 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002794
2795 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002796 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002797 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002798 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002799 if (mType != DIRECT) {
2800 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002801 status_t result = EffectBufferHalInterface::allocate(
2802 numSamples * sizeof(int16_t),
2803 &halInBuffer);
2804 if (result != OK) return result;
2805 buffer = halInBuffer->audioBuffer()->s16;
2806 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2807 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002808 }
2809
2810 // Attach all tracks with same session ID to this chain.
2811 for (size_t i = 0; i < mTracks.size(); ++i) {
2812 sp<Track> track = mTracks[i];
2813 if (session == track->sessionId()) {
2814 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2815 buffer);
2816 track->setMainBuffer(buffer);
2817 chain->incTrackCnt();
2818 }
2819 }
2820
2821 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002822 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002823 if (session == track->sessionId()) {
2824 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2825 chain->incActiveTrackCnt();
2826 }
2827 }
2828 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002829 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002830 chain->setInBuffer(halInBuffer);
2831 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002832 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002833 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002834 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2835 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002836 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002837 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002838 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002839 // Effect chain for other sessions are inserted at beginning of effect
2840 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002841 // sessions is not important.
2842 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2843 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2844 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002845 size_t size = mEffectChains.size();
2846 size_t i = 0;
2847 for (i = 0; i < size; i++) {
2848 if (mEffectChains[i]->sessionId() < session) {
2849 break;
2850 }
2851 }
2852 mEffectChains.insertAt(chain, i);
2853 checkSuspendOnAddEffectChain_l(chain);
2854
2855 return NO_ERROR;
2856}
2857
2858size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2859{
Glenn Kastend848eb42016-03-08 13:42:11 -08002860 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002861
2862 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2863
2864 for (size_t i = 0; i < mEffectChains.size(); i++) {
2865 if (chain == mEffectChains[i]) {
2866 mEffectChains.removeAt(i);
2867 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002868 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002869 if (session == track->sessionId()) {
2870 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2871 chain.get(), session);
2872 chain->decActiveTrackCnt();
2873 }
2874 }
2875
2876 // detach all tracks with same session ID from this chain
2877 for (size_t i = 0; i < mTracks.size(); ++i) {
2878 sp<Track> track = mTracks[i];
2879 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002880 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002881 chain->decTrackCnt();
2882 }
2883 }
2884 break;
2885 }
2886 }
2887 return mEffectChains.size();
2888}
2889
2890status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002891 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002892{
2893 Mutex::Autolock _l(mLock);
2894 return attachAuxEffect_l(track, EffectId);
2895}
2896
2897status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002898 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002899{
2900 status_t status = NO_ERROR;
2901
2902 if (EffectId == 0) {
2903 track->setAuxBuffer(0, NULL);
2904 } else {
2905 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2906 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2907 if (effect != 0) {
2908 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2909 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2910 } else {
2911 status = INVALID_OPERATION;
2912 }
2913 } else {
2914 status = BAD_VALUE;
2915 }
2916 }
2917 return status;
2918}
2919
2920void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2921{
2922 for (size_t i = 0; i < mTracks.size(); ++i) {
2923 sp<Track> track = mTracks[i];
2924 if (track->auxEffectId() == effectId) {
2925 attachAuxEffect_l(track, 0);
2926 }
2927 }
2928}
2929
2930bool AudioFlinger::PlaybackThread::threadLoop()
2931{
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002932 logWriterTLS = mNBLogWriter.get();
2933
Eric Laurent81784c32012-11-19 14:55:58 -08002934 Vector< sp<Track> > tracksToRemove;
2935
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002936 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002937 nsecs_t lastWriteFinished = -1; // time last server write completed
2938 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002939
2940 // MIXER
2941 nsecs_t lastWarning = 0;
2942
2943 // DUPLICATING
2944 // FIXME could this be made local to while loop?
2945 writeFrames = 0;
2946
2947 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002948 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002949
2950 if (mType == MIXER) {
2951 sleepTimeShift = 0;
2952 }
2953
2954 CpuStats cpuStats;
2955 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2956
2957 acquireWakeLock();
2958
Glenn Kasten9e58b552013-01-18 15:09:48 -08002959 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2960 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2961 // and then that string will be logged at the next convenient opportunity.
2962 const char *logString = NULL;
2963
Eric Laurent664539d2013-09-23 18:24:31 -07002964 checkSilentMode_l();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002965#if 0
2966 int z = 0; // used in logFormat example
2967#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002968 while (!exitPending())
2969 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002970 // Log merge requests are performed during AudioFlinger binder transactions, but
2971 // that does not cover audio playback. It's requested here for that reason.
2972 mAudioFlinger->requestLogMerge();
2973
Eric Laurent81784c32012-11-19 14:55:58 -08002974 cpuStats.sample(myName);
2975
2976 Vector< sp<EffectChain> > effectChains;
2977
Eric Laurent81784c32012-11-19 14:55:58 -08002978 { // scope for mLock
2979
2980 Mutex::Autolock _l(mLock);
2981
Eric Laurent021cf962014-05-13 10:18:14 -07002982 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002983
Glenn Kasten9e58b552013-01-18 15:09:48 -08002984 if (logString != NULL) {
2985 mNBLogWriter->logTimestamp();
2986 mNBLogWriter->log(logString);
2987 logString = NULL;
2988 }
2989
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002990 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002991 // and associate with the sink frames written out. We need
2992 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002993 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002994 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002995 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002996 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002997 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002998 ExtendedTimestamp timestamp; // use private copy to fetch
2999 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003000
3001 // We keep track of the last valid kernel position in case we are in underrun
3002 // and the normal mixer period is the same as the fast mixer period, or there
3003 // is some error from the HAL.
3004 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3005 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3006 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3007 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3008 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3009
3010 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3011 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3012 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3013 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003014 }
3015
3016 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3017 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003018 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003019 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003020 }
3021
Andy Hung818e7a32016-02-16 18:08:07 -08003022 // copy over kernel info
3023 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003024 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3025 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003026 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3027 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003028 }
3029 // mFramesWritten for non-offloaded tracks are contiguous
3030 // even after standby() is called. This is useful for the track frame
3031 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003032 bool serverLocationUpdate = false;
3033 if (mFramesWritten != lastFramesWritten) {
3034 serverLocationUpdate = true;
3035 lastFramesWritten = mFramesWritten;
3036 }
3037 // Only update timestamps if there is a meaningful change.
3038 // Either the kernel timestamp must be valid or we have written something.
3039 if (kernelLocationUpdate || serverLocationUpdate) {
3040 if (serverLocationUpdate) {
3041 // use the time before we called the HAL write - it is a bit more accurate
3042 // to when the server last read data than the current time here.
3043 //
3044 // If we haven't written anything, mLastWriteTime will be -1
3045 // and we use systemTime().
3046 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3047 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3048 ? systemTime() : mLastWriteTime;
3049 }
Andy Hungdae27702016-10-31 14:01:16 -07003050
3051 for (const sp<Track> &t : mActiveTracks) {
3052 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003053 t->updateTrackFrameInfo(
3054 t->mAudioTrackServerProxy->framesReleased(),
3055 mFramesWritten,
3056 mTimestamp);
3057 }
Andy Hunge10393e2015-06-12 13:59:33 -07003058 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003059 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003060#if 0
3061 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003062 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003063 timespec ts;
3064 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003065 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003066 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003067 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003068 }
3069 ++z;
3070#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003071 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003072 if (mSignalPending) {
3073 // A signal was raised while we were unlocked
3074 mSignalPending = false;
3075 } else if (waitingAsyncCallback_l()) {
3076 if (exitPending()) {
3077 break;
3078 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003079 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003080 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003081 releaseWakeLock_l();
3082 released = true;
3083 }
Andy Hung10cbff12017-02-21 17:30:14 -08003084
3085 const int64_t waitNs = computeWaitTimeNs_l();
3086 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3087 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3088 if (status == TIMED_OUT) {
3089 mSignalPending = true; // if timeout recheck everything
3090 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003091 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003092 if (released) {
3093 acquireWakeLock_l();
3094 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003095 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3096 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003097
3098 continue;
3099 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003100 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003101 isSuspended()) {
3102 // put audio hardware into standby after short delay
3103 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003104
3105 threadLoop_standby();
3106
3107 mStandby = true;
3108 }
3109
3110 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3111 // we're about to wait, flush the binder command buffer
3112 IPCThreadState::self()->flushCommands();
3113
3114 clearOutputTracks();
3115
3116 if (exitPending()) {
3117 break;
3118 }
3119
3120 releaseWakeLock_l();
3121 // wait until we have something to do...
3122 ALOGV("%s going to sleep", myName.string());
3123 mWaitWorkCV.wait(mLock);
3124 ALOGV("%s waking up", myName.string());
3125 acquireWakeLock_l();
3126
3127 mMixerStatus = MIXER_IDLE;
3128 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3129 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003130 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003131 checkSilentMode_l();
3132
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003133 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3134 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003135 if (mType == MIXER) {
3136 sleepTimeShift = 0;
3137 }
3138
3139 continue;
3140 }
3141 }
Eric Laurent81784c32012-11-19 14:55:58 -08003142 // mMixerStatusIgnoringFastTracks is also updated internally
3143 mMixerStatus = prepareTracks_l(&tracksToRemove);
3144
Andy Hungdae27702016-10-31 14:01:16 -07003145 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003146
Eric Laurent81784c32012-11-19 14:55:58 -08003147 // prevent any changes in effect chain list and in each effect chain
3148 // during mixing and effect process as the audio buffers could be deleted
3149 // or modified if an effect is created or deleted
3150 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003151 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003152
Eric Laurentbfb1b832013-01-07 09:53:42 -08003153 if (mBytesRemaining == 0) {
3154 mCurrentWriteLength = 0;
3155 if (mMixerStatus == MIXER_TRACKS_READY) {
3156 // threadLoop_mix() sets mCurrentWriteLength
3157 threadLoop_mix();
3158 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3159 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003160 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003161 // must be written to HAL
3162 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003163 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003164 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003165 }
3166 }
Andy Hung98ef9782014-03-04 14:46:50 -08003167 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003168 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003169 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3170 // or mSinkBuffer (if there are no effects).
3171 //
3172 // This is done pre-effects computation; if effects change to
3173 // support higher precision, this needs to move.
3174 //
3175 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003176 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003177 if (mMixerBufferValid) {
3178 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3179 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3180
Andy Hung2ddee192015-12-18 17:34:44 -08003181 // mono blend occurs for mixer threads only (not direct or offloaded)
3182 // and is handled here if we're going directly to the sink.
3183 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003184 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3185 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003186 }
3187
Andy Hung98ef9782014-03-04 14:46:50 -08003188 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3189 mNormalFrameCount * mChannelCount);
3190 }
3191
Eric Laurentbfb1b832013-01-07 09:53:42 -08003192 mBytesRemaining = mCurrentWriteLength;
3193 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003194 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3195 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3196 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3197 mBytesWritten += mBytesRemaining;
3198 mFramesWritten += framesRemaining;
3199 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003200 mBytesRemaining = 0;
3201 }
Eric Laurent81784c32012-11-19 14:55:58 -08003202
Eric Laurentbfb1b832013-01-07 09:53:42 -08003203 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003204 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003205 for (size_t i = 0; i < effectChains.size(); i ++) {
3206 effectChains[i]->process_l();
3207 }
Eric Laurent81784c32012-11-19 14:55:58 -08003208 }
3209 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003210 // Process effect chains for offloaded thread even if no audio
3211 // was read from audio track: process only updates effect state
3212 // and thus does have to be synchronized with audio writes but may have
3213 // to be called while waiting for async write callback
3214 if (mType == OFFLOAD) {
3215 for (size_t i = 0; i < effectChains.size(); i ++) {
3216 effectChains[i]->process_l();
3217 }
3218 }
Eric Laurent81784c32012-11-19 14:55:58 -08003219
Andy Hung98ef9782014-03-04 14:46:50 -08003220 // Only if the Effects buffer is enabled and there is data in the
3221 // Effects buffer (buffer valid), we need to
3222 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003223 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003224 if (mEffectBufferValid) {
3225 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003226
3227 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003228 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3229 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003230 }
3231
Andy Hung98ef9782014-03-04 14:46:50 -08003232 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3233 mNormalFrameCount * mChannelCount);
3234 }
3235
Eric Laurent81784c32012-11-19 14:55:58 -08003236 // enable changes in effect chain
3237 unlockEffectChains(effectChains);
3238
Eric Laurentbfb1b832013-01-07 09:53:42 -08003239 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003240 // mSleepTimeUs == 0 means we must write to audio hardware
3241 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003242 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003243 // We save lastWriteFinished here, as previousLastWriteFinished,
3244 // for throttling. On thread start, previousLastWriteFinished will be
3245 // set to -1, which properly results in no throttling after the first write.
3246 nsecs_t previousLastWriteFinished = lastWriteFinished;
3247 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003248 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003249 // FIXME rewrite to reduce number of system calls
3250 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003251 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003252 lastWriteFinished = systemTime();
3253 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003254 if (ret < 0) {
3255 mBytesRemaining = 0;
3256 } else {
3257 mBytesWritten += ret;
3258 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003259 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003260 }
3261 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3262 (mMixerStatus == MIXER_DRAIN_ALL)) {
3263 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003264 }
Andy Hung08fb1742015-05-31 23:22:10 -07003265 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003266 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003267 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003268 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003269 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003270 ATRACE_NAME("underrun");
3271 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003272 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003273 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003274 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003275 }
Andy Hung08fb1742015-05-31 23:22:10 -07003276
3277 if (mThreadThrottle
3278 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3279 && ret > 0) { // we wrote something
3280 // Limit MixerThread data processing to no more than twice the
3281 // expected processing rate.
3282 //
3283 // This helps prevent underruns with NuPlayer and other applications
3284 // which may set up buffers that are close to the minimum size, or use
3285 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3286 //
3287 // The throttle smooths out sudden large data drains from the device,
3288 // e.g. when it comes out of standby, which often causes problems with
3289 // (1) mixer threads without a fast mixer (which has its own warm-up)
3290 // (2) minimum buffer sized tracks (even if the track is full,
3291 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003292 //
3293 // Total time spent in last processing cycle equals time spent in
3294 // 1. threadLoop_write, as well as time spent in
3295 // 2. threadLoop_mix (significant for heavy mixing, especially
3296 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003297
Andy Hung69488c42016-05-16 18:43:33 -07003298 // it's OK if deltaMs is an overestimate.
3299 const int32_t deltaMs =
3300 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003301 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3302 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3303 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003304 // notify of throttle start on verbose log
3305 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3306 "mixer(%p) throttle begin:"
3307 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003308 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003309 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003310 // Throttle must be attributed to the previous mixer loop's write time
3311 // to allow back-to-back throttling.
3312 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003313 } else {
3314 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3315 if (diff > 0) {
3316 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003317 // but prevent spamming for bluetooth
3318 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3319 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003320 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3321 }
Andy Hung08fb1742015-05-31 23:22:10 -07003322 }
3323 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003324 }
Eric Laurent81784c32012-11-19 14:55:58 -08003325
Eric Laurentbfb1b832013-01-07 09:53:42 -08003326 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003327 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003328 Mutex::Autolock _l(mLock);
3329 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3330 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003331 }
Glenn Kastene7754022014-10-31 12:11:26 -07003332 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003333 }
Eric Laurent81784c32012-11-19 14:55:58 -08003334 }
3335
3336 // Finally let go of removed track(s), without the lock held
3337 // since we can't guarantee the destructors won't acquire that
3338 // same lock. This will also mutate and push a new fast mixer state.
3339 threadLoop_removeTracks(tracksToRemove);
3340 tracksToRemove.clear();
3341
3342 // FIXME I don't understand the need for this here;
3343 // it was in the original code but maybe the
3344 // assignment in saveOutputTracks() makes this unnecessary?
3345 clearOutputTracks();
3346
3347 // Effect chains will be actually deleted here if they were removed from
3348 // mEffectChains list during mixing or effects processing
3349 effectChains.clear();
3350
3351 // FIXME Note that the above .clear() is no longer necessary since effectChains
3352 // is now local to this block, but will keep it for now (at least until merge done).
3353 }
3354
Eric Laurentbfb1b832013-01-07 09:53:42 -08003355 threadLoop_exit();
3356
Eric Laurentcf817a22014-08-04 20:36:31 -07003357 if (!mStandby) {
3358 threadLoop_standby();
3359 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003360 }
3361
3362 releaseWakeLock();
3363
3364 ALOGV("Thread %p type %d exiting", this, mType);
3365 return false;
3366}
3367
Eric Laurentbfb1b832013-01-07 09:53:42 -08003368// removeTracks_l() must be called with ThreadBase::mLock held
3369void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3370{
3371 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003372 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003373 for (size_t i=0 ; i<count ; i++) {
3374 const sp<Track>& track = tracksToRemove.itemAt(i);
3375 mActiveTracks.remove(track);
3376 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3377 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3378 if (chain != 0) {
3379 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3380 track->sessionId());
3381 chain->decActiveTrackCnt();
3382 }
3383 if (track->isTerminated()) {
3384 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003385 } else { // inactive but not terminated
3386 char buffer[256];
3387 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3388 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003389 }
3390 }
3391 }
3392
3393}
Eric Laurent81784c32012-11-19 14:55:58 -08003394
Eric Laurentaccc1472013-09-20 09:36:34 -07003395status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3396{
3397 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003398 ExtendedTimestamp ets;
3399 status_t status = mNormalSink->getTimestamp(ets);
3400 if (status == NO_ERROR) {
3401 status = ets.getBestTimestamp(&timestamp);
3402 }
3403 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003404 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003405 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003406 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003407 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003408 timestamp.mPosition = (uint32_t)position64;
3409 return NO_ERROR;
3410 }
3411 }
3412 return INVALID_OPERATION;
3413}
Eric Laurent1c333e22014-05-20 10:48:17 -07003414
Eric Laurent054d9d32015-04-24 08:48:48 -07003415status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3416 audio_patch_handle_t *handle)
3417{
Andy Hungf60abce2016-08-26 11:37:54 -07003418 status_t status;
3419 if (property_get_bool("af.patch_park", false /* default_value */)) {
3420 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3421 // or if HAL does not properly lock against access.
3422 AutoPark<FastMixer> park(mFastMixer);
3423 status = PlaybackThread::createAudioPatch_l(patch, handle);
3424 } else {
3425 status = PlaybackThread::createAudioPatch_l(patch, handle);
3426 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003427 return status;
3428}
3429
Eric Laurent1c333e22014-05-20 10:48:17 -07003430status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3431 audio_patch_handle_t *handle)
3432{
3433 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003434
3435 // store new device and send to effects
3436 audio_devices_t type = AUDIO_DEVICE_NONE;
3437 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3438 type |= patch->sinks[i].ext.device.type;
3439 }
3440
3441#ifdef ADD_BATTERY_DATA
3442 // when changing the audio output device, call addBatteryData to notify
3443 // the change
3444 if (mOutDevice != type) {
3445 uint32_t params = 0;
3446 // check whether speaker is on
3447 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3448 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003449 }
3450
Eric Laurent054d9d32015-04-24 08:48:48 -07003451 audio_devices_t deviceWithoutSpeaker
3452 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3453 // check if any other device (except speaker) is on
3454 if (type & deviceWithoutSpeaker) {
3455 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3456 }
3457
3458 if (params != 0) {
3459 addBatteryData(params);
3460 }
3461 }
3462#endif
3463
3464 for (size_t i = 0; i < mEffectChains.size(); i++) {
3465 mEffectChains[i]->setDevice_l(type);
3466 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003467
3468 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3469 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3470 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003471 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003472 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003473
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003474 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003475 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3476 status = hwDevice->createAudioPatch(patch->num_sources,
3477 patch->sources,
3478 patch->num_sinks,
3479 patch->sinks,
3480 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003481 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003482 char *address;
3483 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3484 //FIXME: we only support address on first sink with HAL version < 3.0
3485 address = audio_device_address_to_parameter(
3486 patch->sinks[0].ext.device.type,
3487 patch->sinks[0].ext.device.address);
3488 } else {
3489 address = (char *)calloc(1, 1);
3490 }
3491 AudioParameter param = AudioParameter(String8(address));
3492 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003493 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003494 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003495 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003496 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003497 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003498 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003499 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3500 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003501 return status;
3502}
3503
Eric Laurent054d9d32015-04-24 08:48:48 -07003504status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3505{
Andy Hungf60abce2016-08-26 11:37:54 -07003506 status_t status;
3507 if (property_get_bool("af.patch_park", false /* default_value */)) {
3508 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3509 // or if HAL does not properly lock against access.
3510 AutoPark<FastMixer> park(mFastMixer);
3511 status = PlaybackThread::releaseAudioPatch_l(handle);
3512 } else {
3513 status = PlaybackThread::releaseAudioPatch_l(handle);
3514 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003515 return status;
3516}
3517
Eric Laurent1c333e22014-05-20 10:48:17 -07003518status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3519{
3520 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003521
3522 mOutDevice = AUDIO_DEVICE_NONE;
3523
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003524 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003525 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3526 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003527 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003528 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003529 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003530 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003531 }
3532 return status;
3533}
3534
Eric Laurent83b88082014-06-20 18:31:16 -07003535void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3536{
3537 Mutex::Autolock _l(mLock);
3538 mTracks.add(track);
3539}
3540
3541void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3542{
3543 Mutex::Autolock _l(mLock);
3544 destroyTrack_l(track);
3545}
3546
3547void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3548{
3549 ThreadBase::getAudioPortConfig(config);
3550 config->role = AUDIO_PORT_ROLE_SOURCE;
3551 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3552 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3553}
3554
Eric Laurent81784c32012-11-19 14:55:58 -08003555// ----------------------------------------------------------------------------
3556
3557AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003558 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3559 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003560 // mAudioMixer below
3561 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003562 mFastMixerFutex(0),
3563 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003564 // mOutputSink below
3565 // mPipeSink below
3566 // mNormalSink below
3567{
3568 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003569 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3570 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003571 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3572 mNormalFrameCount);
3573 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3574
Andy Hungfbfc3952015-01-15 13:33:51 -08003575 if (type == DUPLICATING) {
3576 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3577 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3578 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3579 return;
3580 }
Eric Laurent81784c32012-11-19 14:55:58 -08003581 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003582 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003583 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003584 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003585#if !LOG_NDEBUG
3586 ssize_t index =
3587#else
3588 (void)
3589#endif
3590 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003591 ALOG_ASSERT(index == 0);
3592
3593 // initialize fast mixer depending on configuration
3594 bool initFastMixer;
3595 switch (kUseFastMixer) {
3596 case FastMixer_Never:
3597 initFastMixer = false;
3598 break;
3599 case FastMixer_Always:
3600 initFastMixer = true;
3601 break;
3602 case FastMixer_Static:
3603 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003604 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3605 // where the period is less than an experimentally determined threshold that can be
3606 // scheduled reliably with CFS. However, the BT A2DP HAL is
3607 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3608 initFastMixer = mFrameCount < mNormalFrameCount
3609 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003610 break;
3611 }
Andy Hungfda69402017-02-15 14:33:12 -08003612 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3613 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3614 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003615 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003616 audio_format_t fastMixerFormat;
3617 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3618 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3619 } else {
3620 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3621 }
3622 if (mFormat != fastMixerFormat) {
3623 // change our Sink format to accept our intermediate precision
3624 mFormat = fastMixerFormat;
3625 free(mSinkBuffer);
3626 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3627 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3628 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3629 }
Eric Laurent81784c32012-11-19 14:55:58 -08003630
3631 // create a MonoPipe to connect our submix to FastMixer
3632 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003633#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003634 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003635#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003636 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003637 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003638 format.mFormat = fastMixerFormat;
3639 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3640
Eric Laurent81784c32012-11-19 14:55:58 -08003641 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3642 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3643 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3644 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3645 const NBAIO_Format offers[1] = {format};
3646 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003647#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003648 ssize_t index =
3649#else
3650 (void)
3651#endif
3652 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003653 ALOG_ASSERT(index == 0);
3654 monoPipe->setAvgFrames((mScreenState & 1) ?
3655 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3656 mPipeSink = monoPipe;
3657
Glenn Kasten46909e72013-02-26 09:20:22 -08003658#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003659 if (mTeeSinkOutputEnabled) {
3660 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003661 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3662 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003663 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003664 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003665 ALOG_ASSERT(index == 0);
3666 mTeeSink = teeSink;
3667 PipeReader *teeSource = new PipeReader(*teeSink);
3668 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003669 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003670 ALOG_ASSERT(index == 0);
3671 mTeeSource = teeSource;
3672 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003673#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003674
3675 // create fast mixer and configure it initially with just one fast track for our submix
3676 mFastMixer = new FastMixer();
3677 FastMixerStateQueue *sq = mFastMixer->sq();
3678#ifdef STATE_QUEUE_DUMP
3679 sq->setObserverDump(&mStateQueueObserverDump);
3680 sq->setMutatorDump(&mStateQueueMutatorDump);
3681#endif
3682 FastMixerState *state = sq->begin();
3683 FastTrack *fastTrack = &state->mFastTracks[0];
3684 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3685 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3686 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003687 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3688 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003689 fastTrack->mGeneration++;
3690 state->mFastTracksGen++;
3691 state->mTrackMask = 1;
3692 // fast mixer will use the HAL output sink
3693 state->mOutputSink = mOutputSink.get();
3694 state->mOutputSinkGen++;
3695 state->mFrameCount = mFrameCount;
3696 state->mCommand = FastMixerState::COLD_IDLE;
3697 // already done in constructor initialization list
3698 //mFastMixerFutex = 0;
3699 state->mColdFutexAddr = &mFastMixerFutex;
3700 state->mColdGen++;
3701 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003702#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003703 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003704#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003705 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3706 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003707 sq->end();
3708 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3709
3710 // start the fast mixer
3711 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3712 pid_t tid = mFastMixer->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08003713 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003714 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003715
3716#ifdef AUDIO_WATCHDOG
3717 // create and start the watchdog
3718 mAudioWatchdog = new AudioWatchdog();
3719 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3720 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3721 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003722 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003723#endif
3724
Eric Laurent81784c32012-11-19 14:55:58 -08003725 }
3726
3727 switch (kUseFastMixer) {
3728 case FastMixer_Never:
3729 case FastMixer_Dynamic:
3730 mNormalSink = mOutputSink;
3731 break;
3732 case FastMixer_Always:
3733 mNormalSink = mPipeSink;
3734 break;
3735 case FastMixer_Static:
3736 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3737 break;
3738 }
3739}
3740
3741AudioFlinger::MixerThread::~MixerThread()
3742{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003743 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003744 FastMixerStateQueue *sq = mFastMixer->sq();
3745 FastMixerState *state = sq->begin();
3746 if (state->mCommand == FastMixerState::COLD_IDLE) {
3747 int32_t old = android_atomic_inc(&mFastMixerFutex);
3748 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003749 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003750 }
3751 }
3752 state->mCommand = FastMixerState::EXIT;
3753 sq->end();
3754 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3755 mFastMixer->join();
3756 // Though the fast mixer thread has exited, it's state queue is still valid.
3757 // We'll use that extract the final state which contains one remaining fast track
3758 // corresponding to our sub-mix.
3759 state = sq->begin();
3760 ALOG_ASSERT(state->mTrackMask == 1);
3761 FastTrack *fastTrack = &state->mFastTracks[0];
3762 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3763 delete fastTrack->mBufferProvider;
3764 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003765 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003766#ifdef AUDIO_WATCHDOG
3767 if (mAudioWatchdog != 0) {
3768 mAudioWatchdog->requestExit();
3769 mAudioWatchdog->requestExitAndWait();
3770 mAudioWatchdog.clear();
3771 }
3772#endif
3773 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003774 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003775 delete mAudioMixer;
3776}
3777
3778
3779uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3780{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003781 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003782 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3783 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3784 }
3785 return latency;
3786}
3787
3788
3789void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3790{
3791 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3792}
3793
Eric Laurentbfb1b832013-01-07 09:53:42 -08003794ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003795{
3796 // FIXME we should only do one push per cycle; confirm this is true
3797 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003798 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003799 FastMixerStateQueue *sq = mFastMixer->sq();
3800 FastMixerState *state = sq->begin();
3801 if (state->mCommand != FastMixerState::MIX_WRITE &&
3802 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3803 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003804
3805 // FIXME workaround for first HAL write being CPU bound on some devices
3806 ATRACE_BEGIN("write");
3807 mOutput->write((char *)mSinkBuffer, 0);
3808 ATRACE_END();
3809
Eric Laurent81784c32012-11-19 14:55:58 -08003810 int32_t old = android_atomic_inc(&mFastMixerFutex);
3811 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003812 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003813 }
3814#ifdef AUDIO_WATCHDOG
3815 if (mAudioWatchdog != 0) {
3816 mAudioWatchdog->resume();
3817 }
3818#endif
3819 }
3820 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003821#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003822 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003823 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003824#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003825 sq->end();
3826 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3827 if (kUseFastMixer == FastMixer_Dynamic) {
3828 mNormalSink = mPipeSink;
3829 }
3830 } else {
3831 sq->end(false /*didModify*/);
3832 }
3833 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003834 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003835}
3836
3837void AudioFlinger::MixerThread::threadLoop_standby()
3838{
3839 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003840 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003841 FastMixerStateQueue *sq = mFastMixer->sq();
3842 FastMixerState *state = sq->begin();
3843 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003844 // Report any frames trapped in the Monopipe
3845 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3846 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3847 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3848 "monoPipeWritten:%lld monoPipeLeft:%lld",
3849 (long long)mFramesWritten, (long long)mSuspendedFrames,
3850 (long long)mPipeSink->framesWritten(), pipeFrames);
3851 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3852
Eric Laurent81784c32012-11-19 14:55:58 -08003853 state->mCommand = FastMixerState::COLD_IDLE;
3854 state->mColdFutexAddr = &mFastMixerFutex;
3855 state->mColdGen++;
3856 mFastMixerFutex = 0;
3857 sq->end();
3858 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3859 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3860 if (kUseFastMixer == FastMixer_Dynamic) {
3861 mNormalSink = mOutputSink;
3862 }
3863#ifdef AUDIO_WATCHDOG
3864 if (mAudioWatchdog != 0) {
3865 mAudioWatchdog->pause();
3866 }
3867#endif
3868 } else {
3869 sq->end(false /*didModify*/);
3870 }
3871 }
3872 PlaybackThread::threadLoop_standby();
3873}
3874
Eric Laurentbfb1b832013-01-07 09:53:42 -08003875bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3876{
3877 return false;
3878}
3879
3880bool AudioFlinger::PlaybackThread::shouldStandby_l()
3881{
3882 return !mStandby;
3883}
3884
3885bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3886{
3887 Mutex::Autolock _l(mLock);
3888 return waitingAsyncCallback_l();
3889}
3890
Eric Laurent81784c32012-11-19 14:55:58 -08003891// shared by MIXER and DIRECT, overridden by DUPLICATING
3892void AudioFlinger::PlaybackThread::threadLoop_standby()
3893{
3894 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003895 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003896 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003897 // discard any pending drain or write ack by incrementing sequence
3898 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3899 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003900 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003901 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3902 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003903 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003904 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003905}
3906
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003907void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3908{
3909 ALOGV("signal playback thread");
3910 broadcast_l();
3911}
3912
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003913void AudioFlinger::PlaybackThread::onAsyncError()
3914{
3915 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3916 invalidateTracks((audio_stream_type_t)i);
3917 }
3918}
3919
Eric Laurent81784c32012-11-19 14:55:58 -08003920void AudioFlinger::MixerThread::threadLoop_mix()
3921{
Eric Laurent81784c32012-11-19 14:55:58 -08003922 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003923 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003924 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003925 // increase sleep time progressively when application underrun condition clears.
3926 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3927 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3928 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003929 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003930 sleepTimeShift--;
3931 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003932 mSleepTimeUs = 0;
3933 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003934 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003935
Eric Laurent81784c32012-11-19 14:55:58 -08003936}
3937
3938void AudioFlinger::MixerThread::threadLoop_sleepTime()
3939{
3940 // If no tracks are ready, sleep once for the duration of an output
3941 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003942 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003943 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003944 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3945 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3946 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003947 }
3948 // reduce sleep time in case of consecutive application underruns to avoid
3949 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3950 // duration we would end up writing less data than needed by the audio HAL if
3951 // the condition persists.
3952 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3953 sleepTimeShift++;
3954 }
3955 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003956 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003957 }
3958 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003959 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3960 // before effects processing or output.
3961 if (mMixerBufferValid) {
3962 memset(mMixerBuffer, 0, mMixerBufferSize);
3963 } else {
3964 memset(mSinkBuffer, 0, mSinkBufferSize);
3965 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003966 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003967 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3968 "anticipated start");
3969 }
3970 // TODO add standby time extension fct of effect tail
3971}
3972
3973// prepareTracks_l() must be called with ThreadBase::mLock held
3974AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3975 Vector< sp<Track> > *tracksToRemove)
3976{
3977
3978 mixer_state mixerStatus = MIXER_IDLE;
3979 // find out which tracks need to be processed
3980 size_t count = mActiveTracks.size();
3981 size_t mixedTracks = 0;
3982 size_t tracksWithEffect = 0;
3983 // counts only _active_ fast tracks
3984 size_t fastTracks = 0;
3985 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3986
3987 float masterVolume = mMasterVolume;
3988 bool masterMute = mMasterMute;
3989
3990 if (masterMute) {
3991 masterVolume = 0;
3992 }
3993 // Delegate master volume control to effect in output mix effect chain if needed
3994 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3995 if (chain != 0) {
3996 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3997 chain->setVolume_l(&v, &v);
3998 masterVolume = (float)((v + (1 << 23)) >> 24);
3999 chain.clear();
4000 }
4001
4002 // prepare a new state to push
4003 FastMixerStateQueue *sq = NULL;
4004 FastMixerState *state = NULL;
4005 bool didModify = false;
4006 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004007 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004008 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004009 sq = mFastMixer->sq();
4010 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004011 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004012 }
4013
Andy Hung69aed5f2014-02-25 17:24:40 -08004014 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004015 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004016
Eric Laurent81784c32012-11-19 14:55:58 -08004017 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004018 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004019
4020 // this const just means the local variable doesn't change
4021 Track* const track = t.get();
4022
4023 // process fast tracks
4024 if (track->isFastTrack()) {
4025
4026 // It's theoretically possible (though unlikely) for a fast track to be created
4027 // and then removed within the same normal mix cycle. This is not a problem, as
4028 // the track never becomes active so it's fast mixer slot is never touched.
4029 // The converse, of removing an (active) track and then creating a new track
4030 // at the identical fast mixer slot within the same normal mix cycle,
4031 // is impossible because the slot isn't marked available until the end of each cycle.
4032 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004033 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004034 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4035 FastTrack *fastTrack = &state->mFastTracks[j];
4036
4037 // Determine whether the track is currently in underrun condition,
4038 // and whether it had a recent underrun.
4039 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4040 FastTrackUnderruns underruns = ftDump->mUnderruns;
4041 uint32_t recentFull = (underruns.mBitFields.mFull -
4042 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4043 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4044 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4045 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4046 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4047 uint32_t recentUnderruns = recentPartial + recentEmpty;
4048 track->mObservedUnderruns = underruns;
4049 // don't count underruns that occur while stopping or pausing
4050 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004051 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4052 recentUnderruns > 0) {
4053 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4054 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004055 } else {
4056 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004057 }
4058
4059 // This is similar to the state machine for normal tracks,
4060 // with a few modifications for fast tracks.
4061 bool isActive = true;
4062 switch (track->mState) {
4063 case TrackBase::STOPPING_1:
4064 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004065 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004066 track->mState = TrackBase::STOPPING_2;
4067 }
4068 break;
4069 case TrackBase::PAUSING:
4070 // ramp down is not yet implemented
4071 track->setPaused();
4072 break;
4073 case TrackBase::RESUMING:
4074 // ramp up is not yet implemented
4075 track->mState = TrackBase::ACTIVE;
4076 break;
4077 case TrackBase::ACTIVE:
4078 if (recentFull > 0 || recentPartial > 0) {
4079 // track has provided at least some frames recently: reset retry count
4080 track->mRetryCount = kMaxTrackRetries;
4081 }
4082 if (recentUnderruns == 0) {
4083 // no recent underruns: stay active
4084 break;
4085 }
4086 // there has recently been an underrun of some kind
4087 if (track->sharedBuffer() == 0) {
4088 // were any of the recent underruns "empty" (no frames available)?
4089 if (recentEmpty == 0) {
4090 // no, then ignore the partial underruns as they are allowed indefinitely
4091 break;
4092 }
4093 // there has recently been an "empty" underrun: decrement the retry counter
4094 if (--(track->mRetryCount) > 0) {
4095 break;
4096 }
4097 // indicate to client process that the track was disabled because of underrun;
4098 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004099 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004100 // remove from active list, but state remains ACTIVE [confusing but true]
4101 isActive = false;
4102 break;
4103 }
4104 // fall through
4105 case TrackBase::STOPPING_2:
4106 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004107 case TrackBase::STOPPED:
4108 case TrackBase::FLUSHED: // flush() while active
4109 // Check for presentation complete if track is inactive
4110 // We have consumed all the buffers of this track.
4111 // This would be incomplete if we auto-paused on underrun
4112 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004113 uint32_t latency = 0;
4114 status_t result = mOutput->stream->getLatency(&latency);
4115 ALOGE_IF(result != OK,
4116 "Error when retrieving output stream latency: %d", result);
4117 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004118 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004119 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4120 // track stays in active list until presentation is complete
4121 break;
4122 }
4123 }
4124 if (track->isStopping_2()) {
4125 track->mState = TrackBase::STOPPED;
4126 }
4127 if (track->isStopped()) {
4128 // Can't reset directly, as fast mixer is still polling this track
4129 // track->reset();
4130 // So instead mark this track as needing to be reset after push with ack
4131 resetMask |= 1 << i;
4132 }
4133 isActive = false;
4134 break;
4135 case TrackBase::IDLE:
4136 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004137 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004138 }
4139
4140 if (isActive) {
4141 // was it previously inactive?
4142 if (!(state->mTrackMask & (1 << j))) {
4143 ExtendedAudioBufferProvider *eabp = track;
4144 VolumeProvider *vp = track;
4145 fastTrack->mBufferProvider = eabp;
4146 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004147 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004148 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004149 fastTrack->mGeneration++;
4150 state->mTrackMask |= 1 << j;
4151 didModify = true;
4152 // no acknowledgement required for newly active tracks
4153 }
4154 // cache the combined master volume and stream type volume for fast mixer; this
4155 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004156 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004157 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004158 track->mCachedVolume = masterVolume
4159 * mStreamTypes[track->streamType()].volume
4160 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004161 ++fastTracks;
4162 } else {
4163 // was it previously active?
4164 if (state->mTrackMask & (1 << j)) {
4165 fastTrack->mBufferProvider = NULL;
4166 fastTrack->mGeneration++;
4167 state->mTrackMask &= ~(1 << j);
4168 didModify = true;
4169 // If any fast tracks were removed, we must wait for acknowledgement
4170 // because we're about to decrement the last sp<> on those tracks.
4171 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4172 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004173 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4174 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4175 j, track->mState, state->mTrackMask, recentUnderruns,
4176 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004177 }
4178 tracksToRemove->add(track);
4179 // Avoids a misleading display in dumpsys
4180 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4181 }
4182 continue;
4183 }
4184
4185 { // local variable scope to avoid goto warning
4186
4187 audio_track_cblk_t* cblk = track->cblk();
4188
4189 // The first time a track is added we wait
4190 // for all its buffers to be filled before processing it
4191 int name = track->name();
4192 // make sure that we have enough frames to mix one full buffer.
4193 // enforce this condition only once to enable draining the buffer in case the client
4194 // app does not call stop() and relies on underrun to stop:
4195 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4196 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004197 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004198 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004199 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004200
4201 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004202 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004203 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4204 // add frames already consumed but not yet released by the resampler
4205 // because mAudioTrackServerProxy->framesReady() will include these frames
4206 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4207
Eric Laurent81784c32012-11-19 14:55:58 -08004208 uint32_t minFrames = 1;
4209 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4210 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004211 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004212 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004213
4214 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004215 if (ATRACE_ENABLED()) {
4216 // I wish we had formatted trace names
4217 char traceName[16];
4218 strcpy(traceName, "nRdy");
4219 int name = track->name();
4220 if (AudioMixer::TRACK0 <= name &&
4221 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4222 name -= AudioMixer::TRACK0;
4223 traceName[4] = (name / 10) + '0';
4224 traceName[5] = (name % 10) + '0';
4225 } else {
4226 traceName[4] = '?';
4227 traceName[5] = '?';
4228 }
4229 traceName[6] = '\0';
4230 ATRACE_INT(traceName, framesReady);
4231 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004232 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004233 !track->isPaused() && !track->isTerminated())
4234 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004235 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004236
4237 mixedTracks++;
4238
Andy Hung69aed5f2014-02-25 17:24:40 -08004239 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4240 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004241 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004242 if (track->mainBuffer() != mSinkBuffer &&
4243 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004244 if (mEffectBufferEnabled) {
4245 mEffectBufferValid = true; // Later can set directly.
4246 }
Eric Laurent81784c32012-11-19 14:55:58 -08004247 chain = getEffectChain_l(track->sessionId());
4248 // Delegate volume control to effect in track effect chain if needed
4249 if (chain != 0) {
4250 tracksWithEffect++;
4251 } else {
4252 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4253 "session %d",
4254 name, track->sessionId());
4255 }
4256 }
4257
4258
4259 int param = AudioMixer::VOLUME;
4260 if (track->mFillingUpStatus == Track::FS_FILLED) {
4261 // no ramp for the first volume setting
4262 track->mFillingUpStatus = Track::FS_ACTIVE;
4263 if (track->mState == TrackBase::RESUMING) {
4264 track->mState = TrackBase::ACTIVE;
4265 param = AudioMixer::RAMP_VOLUME;
4266 }
4267 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004268 // FIXME should not make a decision based on mServer
4269 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004270 // If the track is stopped before the first frame was mixed,
4271 // do not apply ramp
4272 param = AudioMixer::RAMP_VOLUME;
4273 }
4274
4275 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004276 uint32_t vl, vr; // in U8.24 integer format
4277 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004278 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004279 vl = vr = 0;
4280 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004281 if (track->isPausing()) {
4282 track->setPaused();
4283 }
4284 } else {
4285
4286 // read original volumes with volume control
4287 float typeVolume = mStreamTypes[track->streamType()].volume;
4288 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004289 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004290 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004291 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4292 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004293 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004294 if (vlf > GAIN_FLOAT_UNITY) {
4295 ALOGV("Track left volume out of range: %.3g", vlf);
4296 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004297 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004298 if (vrf > GAIN_FLOAT_UNITY) {
4299 ALOGV("Track right volume out of range: %.3g", vrf);
4300 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004301 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004302 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004303 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004304 // now apply the master volume and stream type volume and shaper volume
4305 vlf *= v * vh;
4306 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004307 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004308 // then derive vl and vr as U8.24 versions for the effect chain
4309 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4310 vl = (uint32_t) (scaleto8_24 * vlf);
4311 vr = (uint32_t) (scaleto8_24 * vrf);
4312 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004313 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004314 // send level comes from shared memory and so may be corrupt
4315 if (sendLevel > MAX_GAIN_INT) {
4316 ALOGV("Track send level out of range: %04X", sendLevel);
4317 sendLevel = MAX_GAIN_INT;
4318 }
Andy Hung6be49402014-05-30 10:42:03 -07004319 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4320 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004321 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004322
Eric Laurent81784c32012-11-19 14:55:58 -08004323 // Delegate volume control to effect in track effect chain if needed
4324 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4325 // Do not ramp volume if volume is controlled by effect
4326 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004327 // Update remaining floating point volume levels
4328 vlf = (float)vl / (1 << 24);
4329 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004330 track->mHasVolumeController = true;
4331 } else {
4332 // force no volume ramp when volume controller was just disabled or removed
4333 // from effect chain to avoid volume spike
4334 if (track->mHasVolumeController) {
4335 param = AudioMixer::VOLUME;
4336 }
4337 track->mHasVolumeController = false;
4338 }
4339
Eric Laurent81784c32012-11-19 14:55:58 -08004340 // XXX: these things DON'T need to be done each time
4341 mAudioMixer->setBufferProvider(name, track);
4342 mAudioMixer->enable(name);
4343
Andy Hung6be49402014-05-30 10:42:03 -07004344 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4345 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4346 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004347 mAudioMixer->setParameter(
4348 name,
4349 AudioMixer::TRACK,
4350 AudioMixer::FORMAT, (void *)track->format());
4351 mAudioMixer->setParameter(
4352 name,
4353 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004354 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004355 mAudioMixer->setParameter(
4356 name,
4357 AudioMixer::TRACK,
4358 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004359 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004360 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004361 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004362 if (reqSampleRate == 0) {
4363 reqSampleRate = mSampleRate;
4364 } else if (reqSampleRate > maxSampleRate) {
4365 reqSampleRate = maxSampleRate;
4366 }
Eric Laurent81784c32012-11-19 14:55:58 -08004367 mAudioMixer->setParameter(
4368 name,
4369 AudioMixer::RESAMPLE,
4370 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004371 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004372
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004373 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004374 mAudioMixer->setParameter(
4375 name,
4376 AudioMixer::TIMESTRETCH,
4377 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004378 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004379
Andy Hung69aed5f2014-02-25 17:24:40 -08004380 /*
4381 * Select the appropriate output buffer for the track.
4382 *
Andy Hung98ef9782014-03-04 14:46:50 -08004383 * Tracks with effects go into their own effects chain buffer
4384 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004385 *
4386 * Other tracks can use mMixerBuffer for higher precision
4387 * channel accumulation. If this buffer is enabled
4388 * (mMixerBufferEnabled true), then selected tracks will accumulate
4389 * into it.
4390 *
4391 */
4392 if (mMixerBufferEnabled
4393 && (track->mainBuffer() == mSinkBuffer
4394 || track->mainBuffer() == mMixerBuffer)) {
4395 mAudioMixer->setParameter(
4396 name,
4397 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004398 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004399 mAudioMixer->setParameter(
4400 name,
4401 AudioMixer::TRACK,
4402 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4403 // TODO: override track->mainBuffer()?
4404 mMixerBufferValid = true;
4405 } else {
4406 mAudioMixer->setParameter(
4407 name,
4408 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004409 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004410 mAudioMixer->setParameter(
4411 name,
4412 AudioMixer::TRACK,
4413 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4414 }
Eric Laurent81784c32012-11-19 14:55:58 -08004415 mAudioMixer->setParameter(
4416 name,
4417 AudioMixer::TRACK,
4418 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4419
4420 // reset retry count
4421 track->mRetryCount = kMaxTrackRetries;
4422
4423 // If one track is ready, set the mixer ready if:
4424 // - the mixer was not ready during previous round OR
4425 // - no other track is not ready
4426 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4427 mixerStatus != MIXER_TRACKS_ENABLED) {
4428 mixerStatus = MIXER_TRACKS_READY;
4429 }
4430 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004431 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004432 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4433 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004434 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004435 } else {
4436 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004437 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004438
Eric Laurent81784c32012-11-19 14:55:58 -08004439 // clear effect chain input buffer if an active track underruns to avoid sending
4440 // previous audio buffer again to effects
4441 chain = getEffectChain_l(track->sessionId());
4442 if (chain != 0) {
4443 chain->clearInputBuffer();
4444 }
4445
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004446 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004447 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4448 track->isStopped() || track->isPaused()) {
4449 // We have consumed all the buffers of this track.
4450 // Remove it from the list of active tracks.
4451 // TODO: use actual buffer filling status instead of latency when available from
4452 // audio HAL
4453 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004454 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004455 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4456 if (track->isStopped()) {
4457 track->reset();
4458 }
4459 tracksToRemove->add(track);
4460 }
4461 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004462 // No buffers for this track. Give it a few chances to
4463 // fill a buffer, then remove it from active list.
4464 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004465 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004466 tracksToRemove->add(track);
4467 // indicate to client process that the track was disabled because of underrun;
4468 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004469 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004470 // If one track is not ready, mark the mixer also not ready if:
4471 // - the mixer was ready during previous round OR
4472 // - no other track is ready
4473 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4474 mixerStatus != MIXER_TRACKS_READY) {
4475 mixerStatus = MIXER_TRACKS_ENABLED;
4476 }
4477 }
4478 mAudioMixer->disable(name);
4479 }
4480
4481 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004482
4483 }
4484
4485 // Push the new FastMixer state if necessary
4486 bool pauseAudioWatchdog = false;
4487 if (didModify) {
4488 state->mFastTracksGen++;
4489 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4490 if (kUseFastMixer == FastMixer_Dynamic &&
4491 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4492 state->mCommand = FastMixerState::COLD_IDLE;
4493 state->mColdFutexAddr = &mFastMixerFutex;
4494 state->mColdGen++;
4495 mFastMixerFutex = 0;
4496 if (kUseFastMixer == FastMixer_Dynamic) {
4497 mNormalSink = mOutputSink;
4498 }
4499 // If we go into cold idle, need to wait for acknowledgement
4500 // so that fast mixer stops doing I/O.
4501 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4502 pauseAudioWatchdog = true;
4503 }
Eric Laurent81784c32012-11-19 14:55:58 -08004504 }
4505 if (sq != NULL) {
4506 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004507 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4508 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4509 // when bringing the output sink into standby.)
4510 //
4511 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4512 //
4513 // This occurs with BT suspend when we idle the FastMixer with
4514 // active tracks, which may be added or removed.
4515 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004516 }
4517#ifdef AUDIO_WATCHDOG
4518 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4519 mAudioWatchdog->pause();
4520 }
4521#endif
4522
4523 // Now perform the deferred reset on fast tracks that have stopped
4524 while (resetMask != 0) {
4525 size_t i = __builtin_ctz(resetMask);
4526 ALOG_ASSERT(i < count);
4527 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004528 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004529 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4530 track->reset();
4531 }
4532
4533 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004534 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004535
Eric Laurent97d547d2014-09-02 14:45:53 -07004536 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4537 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004538 }
4539
4540 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004541 // as long as there are effects we should clear the effects buffer, to avoid
4542 // passing a non-clean buffer to the effect chain
4543 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004544 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004545 // sink or mix buffer must be cleared if all tracks are connected to an
4546 // effect chain as in this case the mixer will not write to the sink or mix buffer
4547 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004548 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4549 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004550 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004551 if (mMixerBufferValid) {
4552 memset(mMixerBuffer, 0, mMixerBufferSize);
4553 // TODO: In testing, mSinkBuffer below need not be cleared because
4554 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4555 // after mixing.
4556 //
4557 // To enforce this guarantee:
4558 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4559 // (mixedTracks == 0 && fastTracks > 0))
4560 // must imply MIXER_TRACKS_READY.
4561 // Later, we may clear buffers regardless, and skip much of this logic.
4562 }
Andy Hung98ef9782014-03-04 14:46:50 -08004563 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004564 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004565 }
4566
4567 // if any fast tracks, then status is ready
4568 mMixerStatusIgnoringFastTracks = mixerStatus;
4569 if (fastTracks > 0) {
4570 mixerStatus = MIXER_TRACKS_READY;
4571 }
4572 return mixerStatus;
4573}
4574
Eric Laurentad7dd962016-09-22 12:38:37 -07004575// trackCountForUid_l() must be called with ThreadBase::mLock held
4576uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4577{
4578 uint32_t trackCount = 0;
4579 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004580 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004581 trackCount++;
4582 }
4583 }
4584 return trackCount;
4585}
4586
Eric Laurent81784c32012-11-19 14:55:58 -08004587// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004588int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004589 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004590{
Eric Laurentad7dd962016-09-22 12:38:37 -07004591 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4592 return -1;
4593 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004594 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004595}
4596
4597// deleteTrackName_l() must be called with ThreadBase::mLock held
4598void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4599{
4600 ALOGV("remove track (%d) and delete from mixer", name);
4601 mAudioMixer->deleteTrackName(name);
4602}
4603
Eric Laurent10351942014-05-08 18:49:52 -07004604// checkForNewParameter_l() must be called with ThreadBase::mLock held
4605bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4606 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004607{
Eric Laurent81784c32012-11-19 14:55:58 -08004608 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004609 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004610
Eric Laurent10351942014-05-08 18:49:52 -07004611 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004612
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004613 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004614
Eric Laurent10351942014-05-08 18:49:52 -07004615 AudioParameter param = AudioParameter(keyValuePair);
4616 int value;
4617 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4618 reconfig = true;
4619 }
4620 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004621 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004622 status = BAD_VALUE;
4623 } else {
4624 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004625 reconfig = true;
4626 }
Eric Laurent10351942014-05-08 18:49:52 -07004627 }
4628 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004629 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004630 status = BAD_VALUE;
4631 } else {
4632 // no need to save value, since it's constant
4633 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004634 }
Eric Laurent10351942014-05-08 18:49:52 -07004635 }
4636 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4637 // do not accept frame count changes if tracks are open as the track buffer
4638 // size depends on frame count and correct behavior would not be guaranteed
4639 // if frame count is changed after track creation
4640 if (!mTracks.isEmpty()) {
4641 status = INVALID_OPERATION;
4642 } else {
4643 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004644 }
Eric Laurent10351942014-05-08 18:49:52 -07004645 }
4646 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004647#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004648 // when changing the audio output device, call addBatteryData to notify
4649 // the change
4650 if (mOutDevice != value) {
4651 uint32_t params = 0;
4652 // check whether speaker is on
4653 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4654 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004655 }
Eric Laurent10351942014-05-08 18:49:52 -07004656
4657 audio_devices_t deviceWithoutSpeaker
4658 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4659 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004660 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004661 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4662 }
4663
4664 if (params != 0) {
4665 addBatteryData(params);
4666 }
4667 }
Eric Laurent81784c32012-11-19 14:55:58 -08004668#endif
4669
Eric Laurent10351942014-05-08 18:49:52 -07004670 // forward device change to effects that have requested to be
4671 // aware of attached audio device.
4672 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004673 a2dpDeviceChanged =
4674 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004675 mOutDevice = value;
4676 for (size_t i = 0; i < mEffectChains.size(); i++) {
4677 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004678 }
4679 }
Eric Laurent10351942014-05-08 18:49:52 -07004680 }
Eric Laurent81784c32012-11-19 14:55:58 -08004681
Eric Laurent10351942014-05-08 18:49:52 -07004682 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004683 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004684 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004685 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004686 mStandby = true;
4687 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004688 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004689 }
Eric Laurent10351942014-05-08 18:49:52 -07004690 if (status == NO_ERROR && reconfig) {
4691 readOutputParameters_l();
4692 delete mAudioMixer;
4693 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4694 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004695 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004696 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004697 if (name < 0) {
4698 break;
4699 }
4700 mTracks[i]->mName = name;
4701 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004702 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004703 }
Eric Laurent81784c32012-11-19 14:55:58 -08004704 }
4705
Eric Laurent42537be2016-01-08 17:16:42 -08004706 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004707}
4708
4709
4710void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4711{
Eric Laurent81784c32012-11-19 14:55:58 -08004712 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004713 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004714 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004715 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004716
4717 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004718 // while we are dumping it. It may be inconsistent, but it won't mutate!
4719 // This is a large object so we place it on the heap.
4720 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4721 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4722 copy->dump(fd);
4723 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004724
4725#ifdef STATE_QUEUE_DUMP
4726 // Similar for state queue
4727 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4728 observerCopy.dump(fd);
4729 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4730 mutatorCopy.dump(fd);
4731#endif
4732
Glenn Kasten46909e72013-02-26 09:20:22 -08004733#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004734 // Write the tee output to a .wav file
4735 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004736#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004737
4738#ifdef AUDIO_WATCHDOG
4739 if (mAudioWatchdog != 0) {
4740 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4741 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4742 wdCopy.dump(fd);
4743 }
4744#endif
4745}
4746
4747uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4748{
4749 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4750}
4751
4752uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4753{
4754 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4755}
4756
4757void AudioFlinger::MixerThread::cacheParameters_l()
4758{
4759 PlaybackThread::cacheParameters_l();
4760
4761 // FIXME: Relaxed timing because of a certain device that can't meet latency
4762 // Should be reduced to 2x after the vendor fixes the driver issue
4763 // increase threshold again due to low power audio mode. The way this warning
4764 // threshold is calculated and its usefulness should be reconsidered anyway.
4765 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4766}
4767
4768// ----------------------------------------------------------------------------
4769
4770AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004771 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4772 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004773 // mLeftVolFloat, mRightVolFloat
4774{
4775}
4776
Eric Laurentbfb1b832013-01-07 09:53:42 -08004777AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4778 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004779 ThreadBase::type_t type, bool systemReady)
4780 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004781 // mLeftVolFloat, mRightVolFloat
Andy Hung10cbff12017-02-21 17:30:14 -08004782 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004783{
4784}
4785
Eric Laurent81784c32012-11-19 14:55:58 -08004786AudioFlinger::DirectOutputThread::~DirectOutputThread()
4787{
4788}
4789
Eric Laurent5850c4c2016-11-10 13:04:31 -08004790void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004791{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004792 float left, right;
4793
4794 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4795 left = right = 0;
4796 } else {
4797 float typeVolume = mStreamTypes[track->streamType()].volume;
4798 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004799 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004800
Andy Hung10cbff12017-02-21 17:30:14 -08004801 // Get volumeshaper scaling
4802 std::pair<float /* volume */, bool /* active */>
4803 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004804 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004805 v *= vh.first;
4806 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004807
Glenn Kastenc56f3422014-03-21 17:53:17 -07004808 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4809 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4810 if (left > GAIN_FLOAT_UNITY) {
4811 left = GAIN_FLOAT_UNITY;
4812 }
4813 left *= v;
4814 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4815 if (right > GAIN_FLOAT_UNITY) {
4816 right = GAIN_FLOAT_UNITY;
4817 }
4818 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004819 }
4820
4821 if (lastTrack) {
4822 if (left != mLeftVolFloat || right != mRightVolFloat) {
4823 mLeftVolFloat = left;
4824 mRightVolFloat = right;
4825
4826 // Convert volumes from float to 8.24
4827 uint32_t vl = (uint32_t)(left * (1 << 24));
4828 uint32_t vr = (uint32_t)(right * (1 << 24));
4829
4830 // Delegate volume control to effect in track effect chain if needed
4831 // only one effect chain can be present on DirectOutputThread, so if
4832 // there is one, the track is connected to it
4833 if (!mEffectChains.isEmpty()) {
4834 mEffectChains[0]->setVolume_l(&vl, &vr);
4835 left = (float)vl / (1 << 24);
4836 right = (float)vr / (1 << 24);
4837 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004838 status_t result = mOutput->stream->setVolume(left, right);
4839 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004840 }
4841 }
4842}
4843
Phil Burk43b4dcc2015-06-09 16:53:44 -07004844void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4845{
4846 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004847 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004848
Eric Laurent0f0631e2015-07-06 18:01:25 -07004849 if (previousTrack != 0 && latestTrack != 0) {
4850 if (mType == DIRECT) {
4851 if (previousTrack.get() != latestTrack.get()) {
4852 mFlushPending = true;
4853 }
4854 } else /* mType == OFFLOAD */ {
4855 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4856 mFlushPending = true;
4857 }
4858 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004859 }
4860 PlaybackThread::onAddNewTrack_l();
4861}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004862
Eric Laurent81784c32012-11-19 14:55:58 -08004863AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4864 Vector< sp<Track> > *tracksToRemove
4865)
4866{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004867 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004868 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004869 bool doHwPause = false;
4870 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004871
4872 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004873 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004874 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004875 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004876 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004877 continue;
4878 }
4879
Eric Laurent5850c4c2016-11-10 13:04:31 -08004880 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004881#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004882 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004883#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004884 // Only consider last track started for volume and mixer state control.
4885 // In theory an older track could underrun and restart after the new one starts
4886 // but as we only care about the transition phase between two tracks on a
4887 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004888 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004889 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004890
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004891 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004892 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004893 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004894 doHwPause = true;
4895 mHwPaused = true;
4896 }
4897 tracksToRemove->add(track);
4898 } else if (track->isFlushPending()) {
4899 track->flushAck();
4900 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004901 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004902 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004903 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004904 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004905 if (last) {
4906 mLeftVolFloat = mRightVolFloat = -1.0;
4907 if (mHwPaused) {
4908 doHwResume = true;
4909 mHwPaused = false;
4910 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004911 }
4912 }
4913
Eric Laurent81784c32012-11-19 14:55:58 -08004914 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004915 // for all its buffers to be filled before processing it.
4916 // Allow draining the buffer in case the client
4917 // app does not call stop() and relies on underrun to stop:
4918 // hence the test on (track->mRetryCount > 1).
4919 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004920 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004921 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004922 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004923 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004924 minFrames = mNormalFrameCount;
4925 } else {
4926 minFrames = 1;
4927 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004928
Eric Laurentab5cdba2014-06-09 17:22:27 -07004929 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4930 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004931 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004932 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004933
4934 if (track->mFillingUpStatus == Track::FS_FILLED) {
4935 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004936 if (last) {
4937 // make sure processVolume_l() will apply new volume even if 0
4938 mLeftVolFloat = mRightVolFloat = -1.0;
4939 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004940 if (!mHwSupportsPause) {
4941 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004942 }
4943 }
4944
4945 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004946 processVolume_l(track, last);
4947 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004948 sp<Track> previousTrack = mPreviousTrack.promote();
4949 if (previousTrack != 0) {
4950 if (track != previousTrack.get()) {
4951 // Flush any data still being written from last track
4952 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004953 // Invalidate previous track to force a seek when resuming.
4954 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004955 }
4956 }
4957 mPreviousTrack = track;
4958
Eric Laurentd595b7c2013-04-03 17:27:56 -07004959 // reset retry count
4960 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004961 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004962 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004963 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004964 doHwResume = true;
4965 mHwPaused = false;
4966 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004967 }
Eric Laurent81784c32012-11-19 14:55:58 -08004968 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004969 // clear effect chain input buffer if the last active track started underruns
4970 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004971 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004972 mEffectChains[0]->clearInputBuffer();
4973 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004974 if (track->isStopping_1()) {
4975 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004976 if (last && mHwPaused) {
4977 doHwResume = true;
4978 mHwPaused = false;
4979 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004980 }
4981 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4982 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004983 // We have consumed all the buffers of this track.
4984 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004985 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004986 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004987 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4988 } else {
4989 audioHALFrames = 0;
4990 }
4991
Andy Hung818e7a32016-02-16 18:08:07 -08004992 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004993 if (mStandby || !last ||
4994 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004995 if (track->isStopping_2()) {
4996 track->mState = TrackBase::STOPPED;
4997 }
Eric Laurent81784c32012-11-19 14:55:58 -08004998 if (track->isStopped()) {
4999 track->reset();
5000 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005001 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005002 }
5003 } else {
5004 // No buffers for this track. Give it a few chances to
5005 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005006 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005007 if (--(track->mRetryCount) <= 0) {
5008 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005009 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005010 // indicate to client process that the track was disabled because of underrun;
5011 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005012 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005013 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005014 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5015 "minFrames = %u, mFormat = %#x",
5016 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005017 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005018 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005019 doHwPause = true;
5020 mHwPaused = true;
5021 }
Eric Laurent81784c32012-11-19 14:55:58 -08005022 }
5023 }
5024 }
5025 }
5026
Eric Laurentd1f69b02014-12-15 14:33:13 -08005027 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005028 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005029 for (size_t i = 0; i < mTracks.size(); i++) {
5030 if (mTracks[i]->isFlushPending()) {
5031 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005032 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005033 }
5034 }
5035 }
5036
5037 // make sure the pause/flush/resume sequence is executed in the right order.
5038 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5039 // before flush and then resume HW. This can happen in case of pause/flush/resume
5040 // if resume is received before pause is executed.
5041 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005042 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005043 status_t result = mOutput->stream->pause();
5044 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005045 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005046 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005047 flushHw_l();
5048 }
5049 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005050 status_t result = mOutput->stream->resume();
5051 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005052 }
Eric Laurent81784c32012-11-19 14:55:58 -08005053 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005054 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005055
5056 return mixerStatus;
5057}
5058
5059void AudioFlinger::DirectOutputThread::threadLoop_mix()
5060{
Eric Laurent81784c32012-11-19 14:55:58 -08005061 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005062 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005063 // output audio to hardware
5064 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005065 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005066 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005067 status_t status = mActiveTrack->getNextBuffer(&buffer);
5068 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005069 // no need to pad with 0 for compressed audio
5070 if (audio_has_proportional_frames(mFormat)) {
5071 memset(curBuf, 0, frameCount * mFrameSize);
5072 }
Eric Laurent81784c32012-11-19 14:55:58 -08005073 break;
5074 }
5075 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5076 frameCount -= buffer.frameCount;
5077 curBuf += buffer.frameCount * mFrameSize;
5078 mActiveTrack->releaseBuffer(&buffer);
5079 }
Andy Hung2098f272014-02-27 14:00:06 -08005080 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005081 mSleepTimeUs = 0;
5082 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005083 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005084}
5085
5086void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5087{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005088 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005089 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005090 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005091 return;
5092 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005093 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005094 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005095 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005096 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005097 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005098 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005099 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005100 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005101 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005102 }
5103}
5104
Eric Laurentd1f69b02014-12-15 14:33:13 -08005105void AudioFlinger::DirectOutputThread::threadLoop_exit()
5106{
5107 {
5108 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005109 for (size_t i = 0; i < mTracks.size(); i++) {
5110 if (mTracks[i]->isFlushPending()) {
5111 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005112 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005113 }
5114 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005115 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005116 flushHw_l();
5117 }
5118 }
5119 PlaybackThread::threadLoop_exit();
5120}
5121
5122// must be called with thread mutex locked
5123bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5124{
5125 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005126 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005127
vivek mehta9cd7ad12016-03-17 00:18:29 -07005128 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5129 return !mStandby;
5130 }
5131
Eric Laurentd1f69b02014-12-15 14:33:13 -08005132 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5133 // after a timeout and we will enter standby then.
5134 if (mTracks.size() > 0) {
5135 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005136 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5137 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005138 }
5139
Eric Laurent5cff4032015-05-26 13:49:58 -07005140 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005141}
5142
Eric Laurent81784c32012-11-19 14:55:58 -08005143// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005144int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005145 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005146{
Eric Laurentad7dd962016-09-22 12:38:37 -07005147 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5148 return -1;
5149 }
Eric Laurent81784c32012-11-19 14:55:58 -08005150 return 0;
5151}
5152
5153// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005154void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005155{
5156}
5157
Eric Laurent10351942014-05-08 18:49:52 -07005158// checkForNewParameter_l() must be called with ThreadBase::mLock held
5159bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5160 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005161{
5162 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005163 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005164
Eric Laurent10351942014-05-08 18:49:52 -07005165 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005166
Eric Laurent10351942014-05-08 18:49:52 -07005167 AudioParameter param = AudioParameter(keyValuePair);
5168 int value;
5169 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5170 // forward device change to effects that have requested to be
5171 // aware of attached audio device.
5172 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005173 a2dpDeviceChanged =
5174 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005175 mOutDevice = value;
5176 for (size_t i = 0; i < mEffectChains.size(); i++) {
5177 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005178 }
5179 }
Eric Laurent81784c32012-11-19 14:55:58 -08005180 }
Eric Laurent10351942014-05-08 18:49:52 -07005181 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5182 // do not accept frame count changes if tracks are open as the track buffer
5183 // size depends on frame count and correct behavior would not be garantied
5184 // if frame count is changed after track creation
5185 if (!mTracks.isEmpty()) {
5186 status = INVALID_OPERATION;
5187 } else {
5188 reconfig = true;
5189 }
5190 }
5191 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005192 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005193 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005194 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005195 mStandby = true;
5196 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005197 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005198 }
5199 if (status == NO_ERROR && reconfig) {
5200 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005201 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005202 }
5203 }
5204
Eric Laurent42537be2016-01-08 17:16:42 -08005205 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005206}
5207
5208uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5209{
5210 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005211 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005212 time = PlaybackThread::activeSleepTimeUs();
5213 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005214 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005215 }
5216 return time;
5217}
5218
5219uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5220{
5221 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005222 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005223 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5224 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005225 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005226 }
5227 return time;
5228}
5229
5230uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5231{
5232 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005233 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005234 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5235 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005236 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005237 }
5238 return time;
5239}
5240
5241void AudioFlinger::DirectOutputThread::cacheParameters_l()
5242{
5243 PlaybackThread::cacheParameters_l();
5244
5245 // use shorter standby delay as on normal output to release
5246 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005247 // no delay on outputs with HW A/V sync
5248 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005249 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005250 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005251 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005252 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005253 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005254 }
Eric Laurent81784c32012-11-19 14:55:58 -08005255}
5256
Eric Laurente659ef42014-09-29 13:06:46 -07005257void AudioFlinger::DirectOutputThread::flushHw_l()
5258{
Phil Burk062e67a2015-02-11 13:40:50 -08005259 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005260 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005261 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005262}
5263
Andy Hung10cbff12017-02-21 17:30:14 -08005264int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5265 // If a VolumeShaper is active, we must wake up periodically to update volume.
5266 const int64_t NS_PER_MS = 1000000;
5267 return mVolumeShaperActive ?
5268 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5269}
5270
Eric Laurent81784c32012-11-19 14:55:58 -08005271// ----------------------------------------------------------------------------
5272
Eric Laurentbfb1b832013-01-07 09:53:42 -08005273AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005274 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005275 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005276 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005277 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005278 mDrainSequence(0),
5279 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005280{
5281}
5282
5283AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5284{
5285}
5286
5287void AudioFlinger::AsyncCallbackThread::onFirstRef()
5288{
5289 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5290}
5291
5292bool AudioFlinger::AsyncCallbackThread::threadLoop()
5293{
5294 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005295 uint32_t writeAckSequence;
5296 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005297 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005298
5299 {
5300 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005301 while (!((mWriteAckSequence & 1) ||
5302 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005303 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005304 exitPending())) {
5305 mWaitWorkCV.wait(mLock);
5306 }
5307
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308 if (exitPending()) {
5309 break;
5310 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005311 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5312 mWriteAckSequence, mDrainSequence);
5313 writeAckSequence = mWriteAckSequence;
5314 mWriteAckSequence &= ~1;
5315 drainSequence = mDrainSequence;
5316 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005317 asyncError = mAsyncError;
5318 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005319 }
5320 {
Eric Laurent4de95592013-09-26 15:28:21 -07005321 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5322 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005323 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005324 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005325 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005326 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005327 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005328 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005329 if (asyncError) {
5330 playbackThread->onAsyncError();
5331 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005332 }
5333 }
5334 }
5335 return false;
5336}
5337
5338void AudioFlinger::AsyncCallbackThread::exit()
5339{
5340 ALOGV("AsyncCallbackThread::exit");
5341 Mutex::Autolock _l(mLock);
5342 requestExit();
5343 mWaitWorkCV.broadcast();
5344}
5345
Eric Laurent3b4529e2013-09-05 18:09:19 -07005346void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005347{
5348 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005349 // bit 0 is cleared
5350 mWriteAckSequence = sequence << 1;
5351}
5352
5353void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5354{
5355 Mutex::Autolock _l(mLock);
5356 // ignore unexpected callbacks
5357 if (mWriteAckSequence & 2) {
5358 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005359 mWaitWorkCV.signal();
5360 }
5361}
5362
Eric Laurent3b4529e2013-09-05 18:09:19 -07005363void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005364{
5365 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005366 // bit 0 is cleared
5367 mDrainSequence = sequence << 1;
5368}
5369
5370void AudioFlinger::AsyncCallbackThread::resetDraining()
5371{
5372 Mutex::Autolock _l(mLock);
5373 // ignore unexpected callbacks
5374 if (mDrainSequence & 2) {
5375 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005376 mWaitWorkCV.signal();
5377 }
5378}
5379
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005380void AudioFlinger::AsyncCallbackThread::setAsyncError()
5381{
5382 Mutex::Autolock _l(mLock);
5383 mAsyncError = true;
5384 mWaitWorkCV.signal();
5385}
5386
Eric Laurentbfb1b832013-01-07 09:53:42 -08005387
5388// ----------------------------------------------------------------------------
5389AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005390 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5391 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005392 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5393 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005394{
Eric Laurentfd477972013-10-25 18:10:40 -07005395 //FIXME: mStandby should be set to true by ThreadBase constructor
5396 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005397 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005398}
5399
Eric Laurentbfb1b832013-01-07 09:53:42 -08005400void AudioFlinger::OffloadThread::threadLoop_exit()
5401{
5402 if (mFlushPending || mHwPaused) {
5403 // If a flush is pending or track was paused, just discard buffered data
5404 flushHw_l();
5405 } else {
5406 mMixerStatus = MIXER_DRAIN_ALL;
5407 threadLoop_drain();
5408 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005409 if (mUseAsyncWrite) {
5410 ALOG_ASSERT(mCallbackThread != 0);
5411 mCallbackThread->exit();
5412 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005413 PlaybackThread::threadLoop_exit();
5414}
5415
5416AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5417 Vector< sp<Track> > *tracksToRemove
5418)
5419{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005420 size_t count = mActiveTracks.size();
5421
5422 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005423 bool doHwPause = false;
5424 bool doHwResume = false;
5425
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005426 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005427
Eric Laurentbfb1b832013-01-07 09:53:42 -08005428 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005429 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005430 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005431#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005433#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005434 // Only consider last track started for volume and mixer state control.
5435 // In theory an older track could underrun and restart after the new one starts
5436 // but as we only care about the transition phase between two tracks on a
5437 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005438 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005439 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005440
Haynes Mathew George7844f672014-01-15 12:32:55 -08005441 if (track->isInvalid()) {
5442 ALOGW("An invalidated track shouldn't be in active list");
5443 tracksToRemove->add(track);
5444 continue;
5445 }
5446
5447 if (track->mState == TrackBase::IDLE) {
5448 ALOGW("An idle track shouldn't be in active list");
5449 continue;
5450 }
5451
Eric Laurentbfb1b832013-01-07 09:53:42 -08005452 if (track->isPausing()) {
5453 track->setPaused();
5454 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005455 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005456 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005457 mHwPaused = true;
5458 }
5459 // If we were part way through writing the mixbuffer to
5460 // the HAL we must save this until we resume
5461 // BUG - this will be wrong if a different track is made active,
5462 // in that case we want to discard the pending data in the
5463 // mixbuffer and tell the client to present it again when the
5464 // track is resumed
5465 mPausedWriteLength = mCurrentWriteLength;
5466 mPausedBytesRemaining = mBytesRemaining;
5467 mBytesRemaining = 0; // stop writing
5468 }
5469 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005470 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005471 if (track->isStopping_1()) {
5472 track->mRetryCount = kMaxTrackStopRetriesOffload;
5473 } else {
5474 track->mRetryCount = kMaxTrackRetriesOffload;
5475 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005476 track->flushAck();
5477 if (last) {
5478 mFlushPending = true;
5479 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005480 } else if (track->isResumePending()){
5481 track->resumeAck();
5482 if (last) {
5483 if (mPausedBytesRemaining) {
5484 // Need to continue write that was interrupted
5485 mCurrentWriteLength = mPausedWriteLength;
5486 mBytesRemaining = mPausedBytesRemaining;
5487 mPausedBytesRemaining = 0;
5488 }
5489 if (mHwPaused) {
5490 doHwResume = true;
5491 mHwPaused = false;
5492 // threadLoop_mix() will handle the case that we need to
5493 // resume an interrupted write
5494 }
5495 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005496 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005497
Eric Laurent3df841a2016-07-15 15:15:40 -07005498 mLeftVolFloat = mRightVolFloat = -1.0;
5499
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005500 // Do not handle new data in this iteration even if track->framesReady()
5501 mixerStatus = MIXER_TRACKS_ENABLED;
5502 }
5503 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005504 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005505 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005506 if (track->mFillingUpStatus == Track::FS_FILLED) {
5507 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005508 if (last) {
5509 // make sure processVolume_l() will apply new volume even if 0
5510 mLeftVolFloat = mRightVolFloat = -1.0;
5511 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005512 }
5513
5514 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005515 sp<Track> previousTrack = mPreviousTrack.promote();
5516 if (previousTrack != 0) {
5517 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005518 // Flush any data still being written from last track
5519 mBytesRemaining = 0;
5520 if (mPausedBytesRemaining) {
5521 // Last track was paused so we also need to flush saved
5522 // mixbuffer state and invalidate track so that it will
5523 // re-submit that unwritten data when it is next resumed
5524 mPausedBytesRemaining = 0;
5525 // Invalidate is a bit drastic - would be more efficient
5526 // to have a flag to tell client that some of the
5527 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005528 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005529 }
5530 // flush data already sent to the DSP if changing audio session as audio
5531 // comes from a different source. Also invalidate previous track to force a
5532 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005533 if (previousTrack->sessionId() != track->sessionId()) {
5534 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005535 }
5536 }
5537 }
5538 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005539 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005540 if (track->isStopping_1()) {
5541 track->mRetryCount = kMaxTrackStopRetriesOffload;
5542 } else {
5543 track->mRetryCount = kMaxTrackRetriesOffload;
5544 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005545 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005546 mixerStatus = MIXER_TRACKS_READY;
5547 }
5548 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005549 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005550 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005551 if (--(track->mRetryCount) <= 0) {
5552 // Hardware buffer can hold a large amount of audio so we must
5553 // wait for all current track's data to drain before we say
5554 // that the track is stopped.
5555 if (mBytesRemaining == 0) {
5556 // Only start draining when all data in mixbuffer
5557 // has been written
5558 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5559 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5560 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5561 if (last && !mStandby) {
5562 // do not modify drain sequence if we are already draining. This happens
5563 // when resuming from pause after drain.
5564 if ((mDrainSequence & 1) == 0) {
5565 mSleepTimeUs = 0;
5566 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5567 mixerStatus = MIXER_DRAIN_TRACK;
5568 mDrainSequence += 2;
5569 }
5570 if (mHwPaused) {
5571 // It is possible to move from PAUSED to STOPPING_1 without
5572 // a resume so we must ensure hardware is running
5573 doHwResume = true;
5574 mHwPaused = false;
5575 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005576 }
5577 }
Eric Laurente93cc032016-05-05 10:15:10 -07005578 } else if (last) {
5579 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5580 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581 }
5582 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005583 // Drain has completed or we are in standby, signal presentation complete
5584 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005585 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005586 uint32_t latency = 0;
5587 status_t result = mOutput->stream->getLatency(&latency);
5588 ALOGE_IF(result != OK,
5589 "Error when retrieving output stream latency: %d", result);
5590 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005591 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005592 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005593 track->presentationComplete(framesWritten, audioHALFrames);
5594 track->reset();
5595 tracksToRemove->add(track);
5596 }
5597 } else {
5598 // No buffers for this track. Give it a few chances to
5599 // fill a buffer, then remove it from active list.
5600 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005601 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005602 uint64_t position = 0;
5603 struct timespec unused;
5604 // The running check restarts the retry counter at least once.
5605 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5606 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5607 running = true;
5608 mOffloadUnderrunPosition = position;
5609 }
5610 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005611 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5612 (long long)position, (long long)mOffloadUnderrunPosition);
5613 }
5614 if (running) { // still running, give us more time.
5615 track->mRetryCount = kMaxTrackRetriesOffload;
5616 } else {
5617 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5618 track->name());
5619 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005620 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005621 // it will then automatically call start() when data is available
5622 track->disable();
5623 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005624 } else if (last){
5625 mixerStatus = MIXER_TRACKS_ENABLED;
5626 }
5627 }
5628 }
5629 // compute volume for this track
5630 processVolume_l(track, last);
5631 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005632
Eric Laurentea0fade2013-10-04 16:23:48 -07005633 // make sure the pause/flush/resume sequence is executed in the right order.
5634 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5635 // before flush and then resume HW. This can happen in case of pause/flush/resume
5636 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005637 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005638 status_t result = mOutput->stream->pause();
5639 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005640 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005641 if (mFlushPending) {
5642 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005643 }
Eric Laurentfd477972013-10-25 18:10:40 -07005644 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005645 status_t result = mOutput->stream->resume();
5646 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005647 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005648
Eric Laurentbfb1b832013-01-07 09:53:42 -08005649 // remove all the tracks that need to be...
5650 removeTracks_l(*tracksToRemove);
5651
5652 return mixerStatus;
5653}
5654
Eric Laurentbfb1b832013-01-07 09:53:42 -08005655// must be called with thread mutex locked
5656bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5657{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005658 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5659 mWriteAckSequence, mDrainSequence);
5660 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005661 return true;
5662 }
5663 return false;
5664}
5665
Eric Laurentbfb1b832013-01-07 09:53:42 -08005666bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5667{
5668 Mutex::Autolock _l(mLock);
5669 return waitingAsyncCallback_l();
5670}
5671
5672void AudioFlinger::OffloadThread::flushHw_l()
5673{
Eric Laurente659ef42014-09-29 13:06:46 -07005674 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005675 // Flush anything still waiting in the mixbuffer
5676 mCurrentWriteLength = 0;
5677 mBytesRemaining = 0;
5678 mPausedWriteLength = 0;
5679 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005680 // reset bytes written count to reflect that DSP buffers are empty after flush.
5681 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005682 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005683
Eric Laurentbfb1b832013-01-07 09:53:42 -08005684 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005685 // discard any pending drain or write ack by incrementing sequence
5686 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5687 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005688 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005689 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5690 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005691 }
5692}
5693
Haynes Mathew George05317d22016-05-03 16:34:26 -07005694void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5695{
5696 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005697 if (PlaybackThread::invalidateTracks_l(streamType)) {
5698 mFlushPending = true;
5699 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005700}
5701
Eric Laurentbfb1b832013-01-07 09:53:42 -08005702// ----------------------------------------------------------------------------
5703
Eric Laurent81784c32012-11-19 14:55:58 -08005704AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005705 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005706 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005707 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005708 mWaitTimeMs(UINT_MAX)
5709{
5710 addOutputTrack(mainThread);
5711}
5712
5713AudioFlinger::DuplicatingThread::~DuplicatingThread()
5714{
5715 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5716 mOutputTracks[i]->destroy();
5717 }
5718}
5719
5720void AudioFlinger::DuplicatingThread::threadLoop_mix()
5721{
5722 // mix buffers...
5723 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005724 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005725 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005726 if (mMixerBufferValid) {
5727 memset(mMixerBuffer, 0, mMixerBufferSize);
5728 } else {
5729 memset(mSinkBuffer, 0, mSinkBufferSize);
5730 }
Eric Laurent81784c32012-11-19 14:55:58 -08005731 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005732 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005733 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005734 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005735 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005736}
5737
5738void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5739{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005740 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005741 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005742 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005743 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005744 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005745 }
5746 } else if (mBytesWritten != 0) {
5747 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5748 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005749 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005750 } else {
5751 // flush remaining overflow buffers in output tracks
5752 writeFrames = 0;
5753 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005754 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005755 }
5756}
5757
Eric Laurentbfb1b832013-01-07 09:53:42 -08005758ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005759{
5760 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005761 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005762 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005763 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005764 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005765}
5766
5767void AudioFlinger::DuplicatingThread::threadLoop_standby()
5768{
5769 // DuplicatingThread implements standby by stopping all tracks
5770 for (size_t i = 0; i < outputTracks.size(); i++) {
5771 outputTracks[i]->stop();
5772 }
5773}
5774
5775void AudioFlinger::DuplicatingThread::saveOutputTracks()
5776{
5777 outputTracks = mOutputTracks;
5778}
5779
5780void AudioFlinger::DuplicatingThread::clearOutputTracks()
5781{
5782 outputTracks.clear();
5783}
5784
5785void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5786{
5787 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005788 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5789 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5790 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5791 const size_t frameCount =
5792 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5793 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5794 // from different OutputTracks and their associated MixerThreads (e.g. one may
5795 // nearly empty and the other may be dropping data).
5796
5797 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005798 this,
5799 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005800 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005801 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005802 frameCount,
5803 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005804 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5805 if (status != NO_ERROR) {
5806 ALOGE("addOutputTrack() initCheck failed %d", status);
5807 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005808 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005809 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5810 mOutputTracks.add(outputTrack);
5811 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5812 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005813}
5814
5815void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5816{
5817 Mutex::Autolock _l(mLock);
5818 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5819 if (mOutputTracks[i]->thread() == thread) {
5820 mOutputTracks[i]->destroy();
5821 mOutputTracks.removeAt(i);
5822 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005823 if (thread->getOutput() == mOutput) {
5824 mOutput = NULL;
5825 }
Eric Laurent81784c32012-11-19 14:55:58 -08005826 return;
5827 }
5828 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005829 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005830}
5831
5832// caller must hold mLock
5833void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5834{
5835 mWaitTimeMs = UINT_MAX;
5836 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5837 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5838 if (strong != 0) {
5839 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5840 if (waitTimeMs < mWaitTimeMs) {
5841 mWaitTimeMs = waitTimeMs;
5842 }
5843 }
5844 }
5845}
5846
5847
5848bool AudioFlinger::DuplicatingThread::outputsReady(
5849 const SortedVector< sp<OutputTrack> > &outputTracks)
5850{
5851 for (size_t i = 0; i < outputTracks.size(); i++) {
5852 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5853 if (thread == 0) {
5854 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5855 outputTracks[i].get());
5856 return false;
5857 }
5858 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5859 // see note at standby() declaration
5860 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5861 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5862 thread.get());
5863 return false;
5864 }
5865 }
5866 return true;
5867}
5868
5869uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5870{
5871 return (mWaitTimeMs * 1000) / 2;
5872}
5873
5874void AudioFlinger::DuplicatingThread::cacheParameters_l()
5875{
5876 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5877 updateWaitTime_l();
5878
5879 MixerThread::cacheParameters_l();
5880}
5881
Eric Laurent6acd1d42017-01-04 14:23:29 -08005882
Eric Laurent81784c32012-11-19 14:55:58 -08005883// ----------------------------------------------------------------------------
5884// Record
5885// ----------------------------------------------------------------------------
5886
5887AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5888 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005889 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005890 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005891 audio_devices_t inDevice,
5892 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005893#ifdef TEE_SINK
5894 , const sp<NBAIO_Sink>& teeSink
5895#endif
5896 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005897 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005898 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005899 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005900 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005901#ifdef TEE_SINK
5902 , mTeeSink(teeSink)
5903#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005904 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5905 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005906 // mFastCapture below
5907 , mFastCaptureFutex(0)
5908 // mInputSource
5909 // mPipeSink
5910 // mPipeSource
5911 , mPipeFramesP2(0)
5912 // mPipeMemory
5913 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005914 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005915{
Glenn Kastend7dca052015-03-05 16:05:54 -08005916 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5917 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005918
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005919 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005920
5921 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005922 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005923 size_t numCounterOffers = 0;
5924 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005925#if !LOG_NDEBUG
5926 ssize_t index =
5927#else
5928 (void)
5929#endif
5930 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005931 ALOG_ASSERT(index == 0);
5932
5933 // initialize fast capture depending on configuration
5934 bool initFastCapture;
5935 switch (kUseFastCapture) {
5936 case FastCapture_Never:
5937 initFastCapture = false;
5938 break;
5939 case FastCapture_Always:
5940 initFastCapture = true;
5941 break;
5942 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005943 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005944 break;
5945 // case FastCapture_Dynamic:
5946 }
5947
5948 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005949 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005950 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005951 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5952 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005953 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5954 void *pipeBuffer;
5955 const sp<MemoryDealer> roHeap(readOnlyHeap());
5956 sp<IMemory> pipeMemory;
5957 if ((roHeap == 0) ||
5958 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5959 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5960 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5961 goto failed;
5962 }
5963 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5964 memset(pipeBuffer, 0, pipeSize);
5965 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5966 const NBAIO_Format offers[1] = {format};
5967 size_t numCounterOffers = 0;
5968 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5969 ALOG_ASSERT(index == 0);
5970 mPipeSink = pipe;
5971 PipeReader *pipeReader = new PipeReader(*pipe);
5972 numCounterOffers = 0;
5973 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5974 ALOG_ASSERT(index == 0);
5975 mPipeSource = pipeReader;
5976 mPipeFramesP2 = pipeFramesP2;
5977 mPipeMemory = pipeMemory;
5978
5979 // create fast capture
5980 mFastCapture = new FastCapture();
5981 FastCaptureStateQueue *sq = mFastCapture->sq();
5982#ifdef STATE_QUEUE_DUMP
5983 // FIXME
5984#endif
5985 FastCaptureState *state = sq->begin();
5986 state->mCblk = NULL;
5987 state->mInputSource = mInputSource.get();
5988 state->mInputSourceGen++;
5989 state->mPipeSink = pipe;
5990 state->mPipeSinkGen++;
5991 state->mFrameCount = mFrameCount;
5992 state->mCommand = FastCaptureState::COLD_IDLE;
5993 // already done in constructor initialization list
5994 //mFastCaptureFutex = 0;
5995 state->mColdFutexAddr = &mFastCaptureFutex;
5996 state->mColdGen++;
5997 state->mDumpState = &mFastCaptureDumpState;
5998#ifdef TEE_SINK
5999 // FIXME
6000#endif
6001 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6002 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6003 sq->end();
6004 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6005
6006 // start the fast capture
6007 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6008 pid_t tid = mFastCapture->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08006009 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006010 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006011#ifdef AUDIO_WATCHDOG
6012 // FIXME
6013#endif
6014
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006015 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006016 }
6017failed: ;
6018
6019 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006020}
6021
Eric Laurent81784c32012-11-19 14:55:58 -08006022AudioFlinger::RecordThread::~RecordThread()
6023{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006024 if (mFastCapture != 0) {
6025 FastCaptureStateQueue *sq = mFastCapture->sq();
6026 FastCaptureState *state = sq->begin();
6027 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6028 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6029 if (old == -1) {
6030 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6031 }
6032 }
6033 state->mCommand = FastCaptureState::EXIT;
6034 sq->end();
6035 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6036 mFastCapture->join();
6037 mFastCapture.clear();
6038 }
6039 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006040 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006041 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006042}
6043
6044void AudioFlinger::RecordThread::onFirstRef()
6045{
Glenn Kastend7dca052015-03-05 16:05:54 -08006046 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006047}
6048
Eric Laurent555530a2017-02-07 18:17:24 -08006049void AudioFlinger::RecordThread::preExit()
6050{
6051 ALOGV(" preExit()");
6052 Mutex::Autolock _l(mLock);
6053 for (size_t i = 0; i < mTracks.size(); i++) {
6054 sp<RecordTrack> track = mTracks[i];
6055 track->invalidate();
6056 }
6057 mActiveTracks.clear();
6058 mStartStopCond.broadcast();
6059}
6060
Eric Laurent81784c32012-11-19 14:55:58 -08006061bool AudioFlinger::RecordThread::threadLoop()
6062{
Eric Laurent81784c32012-11-19 14:55:58 -08006063 nsecs_t lastWarning = 0;
6064
6065 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006066
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006067reacquire_wakelock:
6068 sp<RecordTrack> activeTrack;
6069 {
6070 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006071 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006072 }
6073
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006074 // used to request a deferred sleep, to be executed later while mutex is unlocked
6075 uint32_t sleepUs = 0;
6076
6077 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006078 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006079 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006080
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006081 // activeTracks accumulates a copy of a subset of mActiveTracks
6082 Vector< sp<RecordTrack> > activeTracks;
6083
Glenn Kasten735f45f2014-08-18 15:51:59 -07006084 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006085 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006086
Glenn Kasten735f45f2014-08-18 15:51:59 -07006087 // reference to a fast track which is about to be removed
6088 sp<RecordTrack> fastTrackToRemove;
6089
Eric Laurent81784c32012-11-19 14:55:58 -08006090 { // scope for mLock
6091 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006092
Eric Laurent021cf962014-05-13 10:18:14 -07006093 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006094
Eric Laurent000a4192014-01-29 15:17:32 -08006095 // check exitPending here because checkForNewParameters_l() and
6096 // checkForNewParameters_l() can temporarily release mLock
6097 if (exitPending()) {
6098 break;
6099 }
6100
Eric Laurent5c25d562016-07-13 17:17:45 -07006101 // sleep with mutex unlocked
6102 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006103 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006104 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6105 ATRACE_END();
6106 sleepUs = 0;
6107 continue;
6108 }
6109
Glenn Kasten2b806402013-11-20 16:37:38 -08006110 // if no active track(s), then standby and release wakelock
6111 size_t size = mActiveTracks.size();
6112 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006113 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006114 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006115 releaseWakeLock_l();
6116 ALOGV("RecordThread: loop stopping");
6117 // go to sleep
6118 mWaitWorkCV.wait(mLock);
6119 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006120 goto reacquire_wakelock;
6121 }
6122
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006124 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006125 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006126
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006127 activeTrack = mActiveTracks[i];
6128 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006129 if (activeTrack->isFastTrack()) {
6130 ALOG_ASSERT(fastTrackToRemove == 0);
6131 fastTrackToRemove = activeTrack;
6132 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006133 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006134 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006135 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006136 continue;
6137 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006138
6139 TrackBase::track_state activeTrackState = activeTrack->mState;
6140 switch (activeTrackState) {
6141
6142 case TrackBase::PAUSING:
6143 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006144 doBroadcast = true;
6145 size--;
6146 continue;
6147
6148 case TrackBase::STARTING_1:
6149 sleepUs = 10000;
6150 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006151 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006152 continue;
6153
6154 case TrackBase::STARTING_2:
6155 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006156 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006157 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006158 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006159 break;
6160
6161 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006162 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006163 break;
6164
6165 case TrackBase::IDLE:
6166 i++;
6167 continue;
6168
6169 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006170 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006171 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006172
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006173 activeTracks.add(activeTrack);
6174 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006175
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006176 if (activeTrack->isFastTrack()) {
6177 ALOG_ASSERT(!mFastTrackAvail);
6178 ALOG_ASSERT(fastTrack == 0);
6179 fastTrack = activeTrack;
6180 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006181 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006182
Andy Hungdae27702016-10-31 14:01:16 -07006183 mActiveTracks.updatePowerState(this);
6184
Eric Laurent5c25d562016-07-13 17:17:45 -07006185 if (allStopped) {
6186 standbyIfNotAlreadyInStandby();
6187 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006188 if (doBroadcast) {
6189 mStartStopCond.broadcast();
6190 }
6191
6192 // sleep if there are no active tracks to process
6193 if (activeTracks.size() == 0) {
6194 if (sleepUs == 0) {
6195 sleepUs = kRecordThreadSleepUs;
6196 }
6197 continue;
6198 }
6199 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006200
Eric Laurent81784c32012-11-19 14:55:58 -08006201 lockEffectChains_l(effectChains);
6202 }
6203
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006204 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006205
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006206 size_t size = effectChains.size();
6207 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006208 // thread mutex is not locked, but effect chain is locked
6209 effectChains[i]->process_l();
6210 }
6211
Glenn Kasten735f45f2014-08-18 15:51:59 -07006212 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006213 if (mFastCapture != 0) {
6214 FastCaptureStateQueue *sq = mFastCapture->sq();
6215 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006216 bool didModify = false;
6217 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006218 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6219 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6220 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6221 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6222 if (old == -1) {
6223 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6224 }
6225 }
6226 state->mCommand = FastCaptureState::READ_WRITE;
6227#if 0 // FIXME
6228 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006229 FastThreadDumpState::kSamplingNforLowRamDevice :
6230 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006231#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006232 didModify = true;
6233 }
6234 audio_track_cblk_t *cblkOld = state->mCblk;
6235 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6236 if (cblkNew != cblkOld) {
6237 state->mCblk = cblkNew;
6238 // block until acked if removing a fast track
6239 if (cblkOld != NULL) {
6240 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6241 }
6242 didModify = true;
6243 }
6244 sq->end(didModify);
6245 if (didModify) {
6246 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006247#if 0
6248 if (kUseFastCapture == FastCapture_Dynamic) {
6249 mNormalSource = mPipeSource;
6250 }
6251#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006252 }
6253 }
6254
Glenn Kasten735f45f2014-08-18 15:51:59 -07006255 // now run the fast track destructor with thread mutex unlocked
6256 fastTrackToRemove.clear();
6257
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006258 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6259 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6260 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6261 // If destination is non-contiguous, first read past the nominal end of buffer, then
6262 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006263
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006264 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006265 ssize_t framesRead;
6266
6267 // If an NBAIO source is present, use it to read the normal capture's data
6268 if (mPipeSource != 0) {
6269 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006270 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006271 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006272 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006273 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6274 // buffer size or at least for 20ms.
6275 size_t sleepFrames = max(
6276 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6277 if (framesRead <= (ssize_t) sleepFrames) {
6278 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6279 }
6280 if (framesRead < 0) {
6281 status_t status = (status_t) framesRead;
6282 switch (status) {
6283 case OVERRUN:
6284 ALOGW("overrun on read from pipe");
6285 framesRead = 0;
6286 break;
6287 case NEGOTIATE:
6288 ALOGE("re-negotiation is needed");
6289 framesRead = -1; // Will cause an attempt to recover.
6290 break;
6291 default:
6292 ALOGE("unknown error %d on read from pipe", status);
6293 break;
6294 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006295 }
6296 // otherwise use the HAL / AudioStreamIn directly
6297 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006298 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006299 size_t bytesRead;
6300 status_t result = mInput->stream->read(
6301 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006302 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006303 if (result < 0) {
6304 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006305 } else {
6306 framesRead = bytesRead / mFrameSize;
6307 }
6308 }
6309
Andy Hung3f0c9022016-01-15 17:49:46 -08006310 // Update server timestamp with server stats
6311 // systemTime() is optional if the hardware supports timestamps.
6312 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6313 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6314
6315 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006316 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006317 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006318 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006319 if (ret == NO_ERROR) {
6320 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6321 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6322 // Note: In general record buffers should tend to be empty in
6323 // a properly running pipeline.
6324 //
6325 // Also, it is not advantageous to call get_presentation_position during the read
6326 // as the read obtains a lock, preventing the timestamp call from executing.
6327 }
6328 }
6329 // Use this to track timestamp information
6330 // ALOGD("%s", mTimestamp.toString().c_str());
6331
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006332 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006333 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334 // Force input into standby so that it tries to recover at next read attempt
6335 inputStandBy();
6336 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006337 }
6338 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006339 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006340 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006341 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006342
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006343 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006344 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006345 }
6346 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006347 {
6348 size_t part1 = mRsmpInFramesP2 - rear;
6349 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006350 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006351 (framesRead - part1) * mFrameSize);
6352 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006353 }
6354 rear = mRsmpInRear += framesRead;
6355
6356 size = activeTracks.size();
6357 // loop over each active track
6358 for (size_t i = 0; i < size; i++) {
6359 activeTrack = activeTracks[i];
6360
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006361 // skip fast tracks, as those are handled directly by FastCapture
6362 if (activeTrack->isFastTrack()) {
6363 continue;
6364 }
6365
Andy Hung73c02e42015-03-29 01:13:58 -07006366 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006367 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6368
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006369 enum {
6370 OVERRUN_UNKNOWN,
6371 OVERRUN_TRUE,
6372 OVERRUN_FALSE
6373 } overrun = OVERRUN_UNKNOWN;
6374
6375 // loop over getNextBuffer to handle circular sink
6376 for (;;) {
6377
6378 activeTrack->mSink.frameCount = ~0;
6379 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6380 size_t framesOut = activeTrack->mSink.frameCount;
6381 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6382
Andy Hung73c02e42015-03-29 01:13:58 -07006383 // check available frames and handle overrun conditions
6384 // if the record track isn't draining fast enough.
6385 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006386 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006387 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6388 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006389 overrun = OVERRUN_TRUE;
6390 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006391 if (framesOut == 0 || framesIn == 0) {
6392 break;
6393 }
6394
Andy Hung6770c6f2015-04-07 13:43:36 -07006395 // Don't allow framesOut to be larger than what is possible with resampling
6396 // from framesIn.
6397 // This isn't strictly necessary but helps limit buffer resizing in
6398 // RecordBufferConverter. TODO: remove when no longer needed.
6399 framesOut = min(framesOut,
6400 destinationFramesPossible(
6401 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006402 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6403 framesOut = activeTrack->mRecordBufferConverter->convert(
6404 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006405
6406 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6407 overrun = OVERRUN_FALSE;
6408 }
6409
6410 if (activeTrack->mFramesToDrop == 0) {
6411 if (framesOut > 0) {
6412 activeTrack->mSink.frameCount = framesOut;
6413 activeTrack->releaseBuffer(&activeTrack->mSink);
6414 }
6415 } else {
6416 // FIXME could do a partial drop of framesOut
6417 if (activeTrack->mFramesToDrop > 0) {
6418 activeTrack->mFramesToDrop -= framesOut;
6419 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006420 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006421 }
6422 } else {
6423 activeTrack->mFramesToDrop += framesOut;
6424 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6425 activeTrack->mSyncStartEvent->isCancelled()) {
6426 ALOGW("Synced record %s, session %d, trigger session %d",
6427 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6428 activeTrack->sessionId(),
6429 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006430 activeTrack->mSyncStartEvent->triggerSession() :
6431 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006432 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006433 }
6434 }
6435 }
6436
6437 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006438 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006439 }
6440 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006441
6442 switch (overrun) {
6443 case OVERRUN_TRUE:
6444 // client isn't retrieving buffers fast enough
6445 if (!activeTrack->setOverflow()) {
6446 nsecs_t now = systemTime();
6447 // FIXME should lastWarning per track?
6448 if ((now - lastWarning) > kWarningThrottleNs) {
6449 ALOGW("RecordThread: buffer overflow");
6450 lastWarning = now;
6451 }
6452 }
6453 break;
6454 case OVERRUN_FALSE:
6455 activeTrack->clearOverflow();
6456 break;
6457 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006458 break;
6459 }
6460
Andy Hung3f0c9022016-01-15 17:49:46 -08006461 // update frame information and push timestamp out
6462 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006463 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006464 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6465 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006466 }
6467
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006468unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006469 // enable changes in effect chain
6470 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006471 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006472 }
6473
Glenn Kasten93e471f2013-08-19 08:40:07 -07006474 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006475
6476 {
6477 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006478 for (size_t i = 0; i < mTracks.size(); i++) {
6479 sp<RecordTrack> track = mTracks[i];
6480 track->invalidate();
6481 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006482 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006483 mStartStopCond.broadcast();
6484 }
6485
6486 releaseWakeLock();
6487
6488 ALOGV("RecordThread %p exiting", this);
6489 return false;
6490}
6491
Glenn Kasten93e471f2013-08-19 08:40:07 -07006492void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006493{
6494 if (!mStandby) {
6495 inputStandBy();
6496 mStandby = true;
6497 }
6498}
6499
6500void AudioFlinger::RecordThread::inputStandBy()
6501{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006502 // Idle the fast capture if it's currently running
6503 if (mFastCapture != 0) {
6504 FastCaptureStateQueue *sq = mFastCapture->sq();
6505 FastCaptureState *state = sq->begin();
6506 if (!(state->mCommand & FastCaptureState::IDLE)) {
6507 state->mCommand = FastCaptureState::COLD_IDLE;
6508 state->mColdFutexAddr = &mFastCaptureFutex;
6509 state->mColdGen++;
6510 mFastCaptureFutex = 0;
6511 sq->end();
6512 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6513 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6514#if 0
6515 if (kUseFastCapture == FastCapture_Dynamic) {
6516 // FIXME
6517 }
6518#endif
6519#ifdef AUDIO_WATCHDOG
6520 // FIXME
6521#endif
6522 } else {
6523 sq->end(false /*didModify*/);
6524 }
6525 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006526 status_t result = mInput->stream->standby();
6527 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006528
6529 // If going into standby, flush the pipe source.
6530 if (mPipeSource.get() != nullptr) {
6531 const ssize_t flushed = mPipeSource->flush();
6532 if (flushed > 0) {
6533 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6534 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6535 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6536 }
6537 }
Eric Laurent81784c32012-11-19 14:55:58 -08006538}
6539
Glenn Kasten05997e22014-03-13 15:08:33 -07006540// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006541sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006542 const sp<AudioFlinger::Client>& client,
6543 uint32_t sampleRate,
6544 audio_format_t format,
6545 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006546 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006547 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006548 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006549 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006550 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006551 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006552 status_t *status,
6553 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006554{
Glenn Kasten74935e42013-12-19 08:56:45 -08006555 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006556 sp<RecordTrack> track;
6557 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006558 audio_input_flags_t inputFlags = mInput->flags;
6559
6560 // special case for FAST flag considered OK if fast capture is present
6561 if (hasFastCapture()) {
6562 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6563 }
6564
6565 // Check if requested flags are compatible with output stream flags
6566 if ((*flags & inputFlags) != *flags) {
6567 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6568 " input flags (%08x)",
6569 *flags, inputFlags);
6570 *flags = (audio_input_flags_t)(*flags & inputFlags);
6571 }
Eric Laurent81784c32012-11-19 14:55:58 -08006572
Glenn Kasten90e58b12013-07-31 16:16:02 -07006573 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006574 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006575 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006576 // we formerly checked for a callback handler (non-0 tid),
6577 // but that is no longer required for TRANSFER_OBTAIN mode
6578 //
Glenn Kasten74105912014-07-03 12:28:53 -07006579 // frame count is not specified, or is exactly the pipe depth
6580 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006581 // PCM data
6582 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006583 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006584 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006585 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006586 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006587 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006588 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006589 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006590 hasFastCapture() &&
6591 // there are sufficient fast track slots available
6592 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006593 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006594 // check compatibility with audio effects.
6595 Mutex::Autolock _l(mLock);
6596 // Do not accept FAST flag if the session has software effects
6597 sp<EffectChain> chain = getEffectChain_l(sessionId);
6598 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006599 audio_input_flags_t old = *flags;
6600 chain->checkInputFlagCompatibility(flags);
6601 if (old != *flags) {
6602 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6603 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006604 }
6605 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006606 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006607 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6608 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006609 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006610 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006611 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006612 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006613 frameCount, mFrameCount, mPipeFramesP2,
6614 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6615 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006616 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006617 }
6618 }
6619
6620 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006621 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006622 // fast track: frame count is exactly the pipe depth
6623 frameCount = mPipeFramesP2;
6624 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6625 *notificationFrames = mFrameCount;
6626 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006627 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6628 // or 20 ms if there is a fast capture
6629 // TODO This could be a roundupRatio inline, and const
6630 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6631 * sampleRate + mSampleRate - 1) / mSampleRate;
6632 // minimum number of notification periods is at least kMinNotifications,
6633 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6634 static const size_t kMinNotifications = 3;
6635 static const uint32_t kMinMs = 30;
6636 // TODO This could be a roundupRatio inline
6637 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6638 // TODO This could be a roundupRatio inline
6639 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6640 maxNotificationFrames;
6641 const size_t minFrameCount = maxNotificationFrames *
6642 max(kMinNotifications, minNotificationsByMs);
6643 frameCount = max(frameCount, minFrameCount);
6644 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6645 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006646 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006647 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006648 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006649
Glenn Kasten15e57982013-09-24 11:52:37 -07006650 lStatus = initCheck();
6651 if (lStatus != NO_ERROR) {
6652 ALOGE("createRecordTrack_l() audio driver not initialized");
6653 goto Exit;
6654 }
Eric Laurent81784c32012-11-19 14:55:58 -08006655
6656 { // scope for mLock
6657 Mutex::Autolock _l(mLock);
6658
6659 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006660 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006661 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006662
Glenn Kasten03003332013-08-06 15:40:54 -07006663 lStatus = track->initCheck();
6664 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006665 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006666 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006667 goto Exit;
6668 }
6669 mTracks.add(track);
6670
6671 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6672 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6673 mAudioFlinger->btNrecIsOff();
6674 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6675 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006676
Eric Laurent05067782016-06-01 18:27:28 -07006677 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006678 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6679 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6680 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08006681 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006682 }
Eric Laurent81784c32012-11-19 14:55:58 -08006683 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006684
Eric Laurent81784c32012-11-19 14:55:58 -08006685 lStatus = NO_ERROR;
6686
6687Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006688 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006689 return track;
6690}
6691
6692status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6693 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006694 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006695{
6696 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6697 sp<ThreadBase> strongMe = this;
6698 status_t status = NO_ERROR;
6699
6700 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006701 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006702 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006703 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006704 triggerSession,
6705 recordTrack->sessionId(),
6706 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006707 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006708 // Sync event can be cancelled by the trigger session if the track is not in a
6709 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006710 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006711 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006712 } else {
6713 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006714 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006715 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006716 }
6717 }
6718
6719 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006720 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006721 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006722 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6723 if (recordTrack->mState == TrackBase::PAUSING) {
6724 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006725 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006726 } else {
6727 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006728 }
6729 return status;
6730 }
6731
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006732 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6733 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6734 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006735 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006736 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006737 status_t status = NO_ERROR;
6738 if (recordTrack->isExternalTrack()) {
6739 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006740 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006741 mLock.lock();
6742 // FIXME should verify that recordTrack is still in mActiveTracks
6743 if (status != NO_ERROR) {
6744 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006745 recordTrack->clearSyncStartEvent();
6746 ALOGV("RecordThread::start error %d", status);
6747 return status;
6748 }
Eric Laurent81784c32012-11-19 14:55:58 -08006749 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006750 // Catch up with current buffer indices if thread is already running.
6751 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6752 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6753 // see previously buffered data before it called start(), but with greater risk of overrun.
6754
Andy Hung73c02e42015-03-29 01:13:58 -07006755 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006756 // clear any converter state as new data will be discontinuous
6757 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006758 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006759 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006760 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006761 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006762 ALOGV("Record failed to start");
6763 status = BAD_VALUE;
6764 goto startError;
6765 }
Eric Laurent81784c32012-11-19 14:55:58 -08006766 return status;
6767 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006768
Eric Laurent81784c32012-11-19 14:55:58 -08006769startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006770 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006771 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006772 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006773 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006774 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006775 return status;
6776}
6777
Eric Laurent81784c32012-11-19 14:55:58 -08006778void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6779{
6780 sp<SyncEvent> strongEvent = event.promote();
6781
6782 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006783 sp<RefBase> ptr = strongEvent->cookie().promote();
6784 if (ptr != 0) {
6785 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6786 recordTrack->handleSyncStartEvent(strongEvent);
6787 }
Eric Laurent81784c32012-11-19 14:55:58 -08006788 }
6789}
6790
Glenn Kastena8356f62013-07-25 14:37:52 -07006791bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006792 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006793 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006794 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006795 return false;
6796 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006797 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006798 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006799 // signal thread to stop
6800 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006801 // do not wait for mStartStopCond if exiting
6802 if (exitPending()) {
6803 return true;
6804 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006805 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006806 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006807 // if we have been restarted, recordTrack is in mActiveTracks here
6808 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006809 ALOGV("Record stopped OK");
6810 return true;
6811 }
6812 return false;
6813}
6814
Glenn Kasten0f11b512014-01-31 16:18:54 -08006815bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006816{
6817 return false;
6818}
6819
Glenn Kasten0f11b512014-01-31 16:18:54 -08006820status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006821{
6822#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6823 if (!isValidSyncEvent(event)) {
6824 return BAD_VALUE;
6825 }
6826
Glenn Kastend848eb42016-03-08 13:42:11 -08006827 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006828 status_t ret = NAME_NOT_FOUND;
6829
6830 Mutex::Autolock _l(mLock);
6831
6832 for (size_t i = 0; i < mTracks.size(); i++) {
6833 sp<RecordTrack> track = mTracks[i];
6834 if (eventSession == track->sessionId()) {
6835 (void) track->setSyncEvent(event);
6836 ret = NO_ERROR;
6837 }
6838 }
6839 return ret;
6840#else
6841 return BAD_VALUE;
6842#endif
6843}
6844
6845// destroyTrack_l() must be called with ThreadBase::mLock held
6846void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6847{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006848 track->terminate();
6849 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006850 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006851 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006852 removeTrack_l(track);
6853 }
6854}
6855
6856void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6857{
6858 mTracks.remove(track);
6859 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006860 if (track->isFastTrack()) {
6861 ALOG_ASSERT(!mFastTrackAvail);
6862 mFastTrackAvail = true;
6863 }
Eric Laurent81784c32012-11-19 14:55:58 -08006864}
6865
6866void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6867{
6868 dumpInternals(fd, args);
6869 dumpTracks(fd, args);
6870 dumpEffectChains(fd, args);
6871}
6872
6873void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6874{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006875 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006876
Glenn Kasten44182c22015-03-05 17:12:23 -08006877 dumpBase(fd, args);
6878
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006879 AudioStreamIn *input = mInput;
6880 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6881 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6882 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006883 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006884 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006885 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006886 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006887 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006888
Glenn Kasten2f90c512015-12-02 11:40:09 -08006889 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6890 // while we are dumping it. It may be inconsistent, but it won't mutate!
6891 // This is a large object so we place it on the heap.
6892 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6893 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6894 copy->dump(fd);
6895 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006896}
6897
Glenn Kasten0f11b512014-01-31 16:18:54 -08006898void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006899{
6900 const size_t SIZE = 256;
6901 char buffer[SIZE];
6902 String8 result;
6903
Marco Nelissenb2208842014-02-07 14:00:50 -08006904 size_t numtracks = mTracks.size();
6905 size_t numactive = mActiveTracks.size();
6906 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006907 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006908 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006909 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006910 RecordTrack::appendDumpHeader(result);
6911 for (size_t i = 0; i < numtracks ; ++i) {
6912 sp<RecordTrack> track = mTracks[i];
6913 if (track != 0) {
6914 bool active = mActiveTracks.indexOf(track) >= 0;
6915 if (active) {
6916 numactiveseen++;
6917 }
6918 track->dump(buffer, SIZE, active);
6919 result.append(buffer);
6920 }
Eric Laurent81784c32012-11-19 14:55:58 -08006921 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006922 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006923 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006924 }
6925
Marco Nelissenb2208842014-02-07 14:00:50 -08006926 if (numactiveseen != numactive) {
6927 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6928 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006929 result.append(buffer);
6930 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006931 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006932 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006933 if (mTracks.indexOf(track) < 0) {
6934 track->dump(buffer, SIZE, true);
6935 result.append(buffer);
6936 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006937 }
Eric Laurent81784c32012-11-19 14:55:58 -08006938
6939 }
6940 write(fd, result.string(), result.size());
6941}
6942
Andy Hung73c02e42015-03-29 01:13:58 -07006943
6944void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6945{
6946 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6947 RecordThread *recordThread = (RecordThread *) threadBase.get();
6948 mRsmpInFront = recordThread->mRsmpInRear;
6949 mRsmpInUnrel = 0;
6950}
6951
6952void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6953 size_t *framesAvailable, bool *hasOverrun)
6954{
6955 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6956 RecordThread *recordThread = (RecordThread *) threadBase.get();
6957 const int32_t rear = recordThread->mRsmpInRear;
6958 const int32_t front = mRsmpInFront;
6959 const ssize_t filled = rear - front;
6960
6961 size_t framesIn;
6962 bool overrun = false;
6963 if (filled < 0) {
6964 // should not happen, but treat like a massive overrun and re-sync
6965 framesIn = 0;
6966 mRsmpInFront = rear;
6967 overrun = true;
6968 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6969 framesIn = (size_t) filled;
6970 } else {
6971 // client is not keeping up with server, but give it latest data
6972 framesIn = recordThread->mRsmpInFrames;
6973 mRsmpInFront = /* front = */ rear - framesIn;
6974 overrun = true;
6975 }
6976 if (framesAvailable != NULL) {
6977 *framesAvailable = framesIn;
6978 }
6979 if (hasOverrun != NULL) {
6980 *hasOverrun = overrun;
6981 }
6982}
6983
Eric Laurent81784c32012-11-19 14:55:58 -08006984// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006985status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006986 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006987{
Andy Hung73c02e42015-03-29 01:13:58 -07006988 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006989 if (threadBase == 0) {
6990 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006991 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006992 return NOT_ENOUGH_DATA;
6993 }
6994 RecordThread *recordThread = (RecordThread *) threadBase.get();
6995 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006996 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006997 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006998 // FIXME should not be P2 (don't want to increase latency)
6999 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007000 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007001 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007002 front &= recordThread->mRsmpInFramesP2 - 1;
7003 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007004 if (part1 > (size_t) filled) {
7005 part1 = filled;
7006 }
7007 size_t ask = buffer->frameCount;
7008 ALOG_ASSERT(ask > 0);
7009 if (part1 > ask) {
7010 part1 = ask;
7011 }
7012 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007013 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007014 buffer->raw = NULL;
7015 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007016 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007017 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007018 }
7019
Andy Hung57446612015-04-19 23:56:46 -07007020 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007021 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007022 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007023 return NO_ERROR;
7024}
7025
7026// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007027void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7028 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007029{
Glenn Kasten85948432013-08-19 12:09:05 -07007030 size_t stepCount = buffer->frameCount;
7031 if (stepCount == 0) {
7032 return;
7033 }
Andy Hung73c02e42015-03-29 01:13:58 -07007034 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7035 mRsmpInUnrel -= stepCount;
7036 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007037 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007038 buffer->frameCount = 0;
7039}
7040
Andy Hung97a893e2015-03-29 01:03:07 -07007041
Eric Laurent10351942014-05-08 18:49:52 -07007042bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7043 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007044{
7045 bool reconfig = false;
7046
Eric Laurent10351942014-05-08 18:49:52 -07007047 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007048
Eric Laurent10351942014-05-08 18:49:52 -07007049 audio_format_t reqFormat = mFormat;
7050 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007051 // 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 -07007052 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7053
7054 AudioParameter param = AudioParameter(keyValuePair);
7055 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007056
7057 // scope for AutoPark extends to end of method
7058 AutoPark<FastCapture> park(mFastCapture);
7059
Eric Laurent10351942014-05-08 18:49:52 -07007060 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7061 // channel count change can be requested. Do we mandate the first client defines the
7062 // HAL sampling rate and channel count or do we allow changes on the fly?
7063 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7064 samplingRate = value;
7065 reconfig = true;
7066 }
7067 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007068 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007069 status = BAD_VALUE;
7070 } else {
7071 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007072 reconfig = true;
7073 }
Eric Laurent10351942014-05-08 18:49:52 -07007074 }
7075 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7076 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007077 if (!audio_is_input_channel(mask) ||
7078 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007079 status = BAD_VALUE;
7080 } else {
7081 channelMask = mask;
7082 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007083 }
Eric Laurent10351942014-05-08 18:49:52 -07007084 }
7085 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7086 // do not accept frame count changes if tracks are open as the track buffer
7087 // size depends on frame count and correct behavior would not be guaranteed
7088 // if frame count is changed after track creation
7089 if (mActiveTracks.size() > 0) {
7090 status = INVALID_OPERATION;
7091 } else {
7092 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007093 }
Eric Laurent10351942014-05-08 18:49:52 -07007094 }
7095 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7096 // forward device change to effects that have requested to be
7097 // aware of attached audio device.
7098 for (size_t i = 0; i < mEffectChains.size(); i++) {
7099 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007100 }
Eric Laurent81784c32012-11-19 14:55:58 -08007101
Eric Laurent10351942014-05-08 18:49:52 -07007102 // store input device and output device but do not forward output device to audio HAL.
7103 // Note that status is ignored by the caller for output device
7104 // (see AudioFlinger::setParameters()
7105 if (audio_is_output_devices(value)) {
7106 mOutDevice = value;
7107 status = BAD_VALUE;
7108 } else {
7109 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007110 if (value != AUDIO_DEVICE_NONE) {
7111 mPrevInDevice = value;
7112 }
Eric Laurent10351942014-05-08 18:49:52 -07007113 // disable AEC and NS if the device is a BT SCO headset supporting those
7114 // pre processings
7115 if (mTracks.size() > 0) {
7116 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7117 mAudioFlinger->btNrecIsOff();
7118 for (size_t i = 0; i < mTracks.size(); i++) {
7119 sp<RecordTrack> track = mTracks[i];
7120 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7121 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007122 }
7123 }
7124 }
Eric Laurent10351942014-05-08 18:49:52 -07007125 }
7126 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7127 mAudioSource != (audio_source_t)value) {
7128 // forward device change to effects that have requested to be
7129 // aware of attached audio device.
7130 for (size_t i = 0; i < mEffectChains.size(); i++) {
7131 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007132 }
Eric Laurent10351942014-05-08 18:49:52 -07007133 mAudioSource = (audio_source_t)value;
7134 }
Glenn Kastene198c362013-08-13 09:13:36 -07007135
Eric Laurent10351942014-05-08 18:49:52 -07007136 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007137 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007138 if (status == INVALID_OPERATION) {
7139 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007140 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007141 }
7142 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007143 if (status == BAD_VALUE) {
7144 uint32_t sRate;
7145 audio_channel_mask_t channelMask;
7146 audio_format_t format;
7147 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7148 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7149 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7150 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7151 status = NO_ERROR;
7152 }
Eric Laurent81784c32012-11-19 14:55:58 -08007153 }
Eric Laurent10351942014-05-08 18:49:52 -07007154 if (status == NO_ERROR) {
7155 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007156 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007157 }
7158 }
Eric Laurent81784c32012-11-19 14:55:58 -08007159 }
Eric Laurent10351942014-05-08 18:49:52 -07007160
Eric Laurent81784c32012-11-19 14:55:58 -08007161 return reconfig;
7162}
7163
7164String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7165{
Eric Laurent81784c32012-11-19 14:55:58 -08007166 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007167 if (initCheck() == NO_ERROR) {
7168 String8 out_s8;
7169 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7170 return out_s8;
7171 }
Eric Laurent81784c32012-11-19 14:55:58 -08007172 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007173 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007174}
7175
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007176void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007177 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7178
7179 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007180
7181 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007182 case AUDIO_INPUT_OPENED:
7183 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007184 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007185 desc->mChannelMask = mChannelMask;
7186 desc->mSamplingRate = mSampleRate;
7187 desc->mFormat = mFormat;
7188 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007189 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007190 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007191 break;
7192
Eric Laurent73e26b62015-04-27 16:55:58 -07007193 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007194 default:
7195 break;
7196 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007197 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007198}
7199
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007200void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007201{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007202 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7203 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007204 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007205 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007206 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007207 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7208 result = mInput->stream->getFrameSize(&mFrameSize);
7209 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7210 result = mInput->stream->getBufferSize(&mBufferSize);
7211 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007212 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007213 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007214 // 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 -07007215 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007216 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007217 // A larger value should allow more old data to be read after a track calls start(),
7218 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007219 //
7220 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007221 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007222 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007223 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007224 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007225
7226 // TODO optimize audio capture buffer sizes ...
7227 // Here we calculate the size of the sliding buffer used as a source
7228 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7229 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7230 // be better to have it derived from the pipe depth in the long term.
7231 // The current value is higher than necessary. However it should not add to latency.
7232
Glenn Kasten85948432013-08-19 12:09:05 -07007233 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007234 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7235 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007236 // if posix_memalign fails, will segv here.
7237 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007238
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007239 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7240 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007241}
7242
Glenn Kasten5f972c02014-01-13 09:59:31 -08007243uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007244{
7245 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007246 uint32_t result;
7247 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7248 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007249 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007250 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007251}
7252
Eric Laurent4c415062016-06-17 16:14:16 -07007253// hasAudioSession_l() must be called with ThreadBase::mLock held
7254uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007255{
Eric Laurent81784c32012-11-19 14:55:58 -08007256 uint32_t result = 0;
7257 if (getEffectChain_l(sessionId) != 0) {
7258 result = EFFECT_SESSION;
7259 }
7260
7261 for (size_t i = 0; i < mTracks.size(); ++i) {
7262 if (sessionId == mTracks[i]->sessionId()) {
7263 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007264 if (mTracks[i]->isFastTrack()) {
7265 result |= FAST_SESSION;
7266 }
Eric Laurent81784c32012-11-19 14:55:58 -08007267 break;
7268 }
7269 }
7270
7271 return result;
7272}
7273
Glenn Kastend848eb42016-03-08 13:42:11 -08007274KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007275{
Glenn Kastend848eb42016-03-08 13:42:11 -08007276 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007277 Mutex::Autolock _l(mLock);
7278 for (size_t j = 0; j < mTracks.size(); ++j) {
7279 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007280 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007281 if (ids.indexOfKey(sessionId) < 0) {
7282 ids.add(sessionId, true);
7283 }
7284 }
7285 return ids;
7286}
7287
7288AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7289{
7290 Mutex::Autolock _l(mLock);
7291 AudioStreamIn *input = mInput;
7292 mInput = NULL;
7293 return input;
7294}
7295
7296// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007297sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007298{
7299 if (mInput == NULL) {
7300 return NULL;
7301 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007302 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007303}
7304
7305status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7306{
7307 // only one chain per input thread
7308 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007309 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007310 return INVALID_OPERATION;
7311 }
7312 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007313 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007314 chain->setInBuffer(NULL);
7315 chain->setOutBuffer(NULL);
7316
7317 checkSuspendOnAddEffectChain_l(chain);
7318
Eric Laurent1b928682014-10-02 19:41:47 -07007319 // make sure enabled pre processing effects state is communicated to the HAL as we
7320 // just moved them to a new input stream.
7321 chain->syncHalEffectsState();
7322
Eric Laurent81784c32012-11-19 14:55:58 -08007323 mEffectChains.add(chain);
7324
7325 return NO_ERROR;
7326}
7327
7328size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7329{
7330 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7331 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007332 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007333 chain.get(), mEffectChains.size(), this);
7334 if (mEffectChains.size() == 1) {
7335 mEffectChains.removeAt(0);
7336 }
7337 return 0;
7338}
7339
Eric Laurent1c333e22014-05-20 10:48:17 -07007340status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7341 audio_patch_handle_t *handle)
7342{
7343 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007344
7345 // store new device and send to effects
7346 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007347 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007348 for (size_t i = 0; i < mEffectChains.size(); i++) {
7349 mEffectChains[i]->setDevice_l(mInDevice);
7350 }
7351
7352 // disable AEC and NS if the device is a BT SCO headset supporting those
7353 // pre processings
7354 if (mTracks.size() > 0) {
7355 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7356 mAudioFlinger->btNrecIsOff();
7357 for (size_t i = 0; i < mTracks.size(); i++) {
7358 sp<RecordTrack> track = mTracks[i];
7359 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7360 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7361 }
7362 }
7363
7364 // store new source and send to effects
7365 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7366 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007367 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007368 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007369 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007370 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007371
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007372 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007373 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7374 status = hwDevice->createAudioPatch(patch->num_sources,
7375 patch->sources,
7376 patch->num_sinks,
7377 patch->sinks,
7378 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007379 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007380 char *address;
7381 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7382 address = audio_device_address_to_parameter(
7383 patch->sources[0].ext.device.type,
7384 patch->sources[0].ext.device.address);
7385 } else {
7386 address = (char *)calloc(1, 1);
7387 }
7388 AudioParameter param = AudioParameter(String8(address));
7389 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007390 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007391 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007392 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007393 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007394 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007395 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007396 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007397
Eric Laurente8726fe2015-06-26 09:39:24 -07007398 if (mInDevice != mPrevInDevice) {
7399 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7400 mPrevInDevice = mInDevice;
7401 }
Eric Laurent296fb132015-05-01 11:38:42 -07007402
Eric Laurent1c333e22014-05-20 10:48:17 -07007403 return status;
7404}
7405
7406status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7407{
7408 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007409
7410 mInDevice = AUDIO_DEVICE_NONE;
7411
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007412 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007413 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7414 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007415 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007416 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007417 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007418 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007419 }
7420 return status;
7421}
7422
Eric Laurent83b88082014-06-20 18:31:16 -07007423void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7424{
7425 Mutex::Autolock _l(mLock);
7426 mTracks.add(record);
7427}
7428
7429void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7430{
7431 Mutex::Autolock _l(mLock);
7432 destroyTrack_l(record);
7433}
7434
7435void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7436{
7437 ThreadBase::getAudioPortConfig(config);
7438 config->role = AUDIO_PORT_ROLE_SINK;
7439 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7440 config->ext.mix.usecase.source = mAudioSource;
7441}
Eric Laurent1c333e22014-05-20 10:48:17 -07007442
Eric Laurent6acd1d42017-01-04 14:23:29 -08007443// ----------------------------------------------------------------------------
7444// Mmap
7445// ----------------------------------------------------------------------------
7446
7447AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7448 : mThread(thread)
7449{
7450}
7451
7452AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7453{
7454 MmapThread *thread = mThread.get();
7455 // clear our strong reference before disconnecting the thread: the last strong reference
Eric Laurent18b57012017-02-13 16:23:52 -08007456 // will be removed when closeInput/closeOutput is executed upon call from audio policy manager
Eric Laurent6acd1d42017-01-04 14:23:29 -08007457 // and the thread removed from mMMapThreads list causing the thread destruction.
7458 mThread.clear();
7459 if (thread != nullptr) {
7460 thread->disconnect();
7461 }
7462}
7463
7464status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7465 struct audio_mmap_buffer_info *info)
7466{
7467 if (mThread == 0) {
7468 return NO_INIT;
7469 }
7470 return mThread->createMmapBuffer(minSizeFrames, info);
7471}
7472
7473status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7474{
7475 if (mThread == 0) {
7476 return NO_INIT;
7477 }
7478 return mThread->getMmapPosition(position);
7479}
7480
Glenn Kastend3bb6452016-12-05 18:14:37 -08007481status_t AudioFlinger::MmapThreadHandle::start(const MmapStreamInterface::Client& client,
7482 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007483
7484{
7485 if (mThread == 0) {
7486 return NO_INIT;
7487 }
7488 return mThread->start(client, handle);
7489}
7490
7491status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7492{
7493 if (mThread == 0) {
7494 return NO_INIT;
7495 }
7496 return mThread->stop(handle);
7497}
7498
Eric Laurent18b57012017-02-13 16:23:52 -08007499status_t AudioFlinger::MmapThreadHandle::standby()
7500{
7501 if (mThread == 0) {
7502 return NO_INIT;
7503 }
7504 return mThread->standby();
7505}
7506
Eric Laurent6acd1d42017-01-04 14:23:29 -08007507
7508AudioFlinger::MmapThread::MmapThread(
7509 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7510 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7511 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7512 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
7513 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev)
7514{
Eric Laurent18b57012017-02-13 16:23:52 -08007515 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007516 readHalParameters_l();
7517}
7518
7519AudioFlinger::MmapThread::~MmapThread()
7520{
Eric Laurent18b57012017-02-13 16:23:52 -08007521 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007522}
7523
7524void AudioFlinger::MmapThread::onFirstRef()
7525{
7526 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7527}
7528
7529void AudioFlinger::MmapThread::disconnect()
7530{
7531 for (const sp<MmapTrack> &t : mActiveTracks) {
7532 stop(t->portId());
7533 }
7534 // this will cause the destruction of this thread.
7535 if (isOutput()) {
7536 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7537 } else {
7538 AudioSystem::releaseInput(mId, mSessionId);
7539 }
7540}
7541
7542
7543void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7544 audio_stream_type_t streamType __unused,
7545 audio_session_t sessionId,
7546 const sp<MmapStreamCallback>& callback,
7547 audio_port_handle_t portId)
7548{
7549 mAttr = *attr;
7550 mSessionId = sessionId;
7551 mCallback = callback;
7552 mPortId = portId;
7553}
7554
7555status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7556 struct audio_mmap_buffer_info *info)
7557{
7558 if (mHalStream == 0) {
7559 return NO_INIT;
7560 }
Eric Laurent18b57012017-02-13 16:23:52 -08007561 mStandby = true;
7562 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007563 return mHalStream->createMmapBuffer(minSizeFrames, info);
7564}
7565
7566status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7567{
7568 if (mHalStream == 0) {
7569 return NO_INIT;
7570 }
7571 return mHalStream->getMmapPosition(position);
7572}
7573
7574status_t AudioFlinger::MmapThread::start(const MmapStreamInterface::Client& client,
7575 audio_port_handle_t *handle)
7576{
Eric Laurent18b57012017-02-13 16:23:52 -08007577 ALOGV("%s clientUid %d mStandby %d", __FUNCTION__, client.clientUid, mStandby);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007578 if (mHalStream == 0) {
7579 return NO_INIT;
7580 }
7581
7582 status_t ret;
7583 audio_session_t sessionId;
7584 audio_port_handle_t portId;
7585
7586 if (mActiveTracks.size() == 0) {
7587 // for the first track, reuse portId and session allocated when the stream was opened
7588 mHalStream->start();
7589 portId = mPortId;
7590 sessionId = mSessionId;
Eric Laurent18b57012017-02-13 16:23:52 -08007591 mStandby = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007592 } else {
7593 // for other tracks than first one, get a new port ID from APM.
7594 sessionId = (audio_session_t)mAudioFlinger->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
7595 audio_io_handle_t io;
7596 if (isOutput()) {
7597 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7598 config.sample_rate = mSampleRate;
7599 config.channel_mask = mChannelMask;
7600 config.format = mFormat;
7601 audio_stream_type_t stream = streamType();
7602 audio_output_flags_t flags =
7603 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
7604 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7605 sessionId,
7606 &stream,
7607 client.clientUid,
7608 &config,
7609 flags,
7610 AUDIO_PORT_HANDLE_NONE,
7611 &portId);
7612 } else {
7613 audio_config_base_t config;
7614 config.sample_rate = mSampleRate;
7615 config.channel_mask = mChannelMask;
7616 config.format = mFormat;
7617 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7618 sessionId,
7619 client.clientPid,
7620 client.clientUid,
7621 &config,
7622 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7623 AUDIO_PORT_HANDLE_NONE,
7624 &portId);
7625 }
7626 // APM should not chose a different input or output stream for the same set of attributes
7627 // and audo configuration
7628 if (ret != NO_ERROR || io != mId) {
7629 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7630 __FUNCTION__, ret, io, mId);
7631 return BAD_VALUE;
7632 }
7633 }
7634
7635 if (isOutput()) {
7636 ret = AudioSystem::startOutput(mId, streamType(), sessionId);
7637 } else {
7638 ret = AudioSystem::startInput(mId, sessionId);
7639 }
7640
7641 // abort if start is rejected by audio policy manager
7642 if (ret != NO_ERROR) {
7643 if (mActiveTracks.size() != 0) {
7644 if (isOutput()) {
7645 AudioSystem::releaseOutput(mId, streamType(), sessionId);
7646 } else {
7647 AudioSystem::releaseInput(mId, sessionId);
7648 }
Eric Laurent18b57012017-02-13 16:23:52 -08007649 } else {
7650 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007651 }
7652 return PERMISSION_DENIED;
7653 }
7654
7655 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, sessionId,
7656 client.clientUid, portId);
7657
7658 mActiveTracks.add(track);
7659 sp<EffectChain> chain = getEffectChain_l(sessionId);
7660 if (chain != 0) {
7661 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7662 chain->incTrackCnt();
7663 chain->incActiveTrackCnt();
7664 }
7665
7666 *handle = portId;
7667
7668 broadcast_l();
7669
Eric Laurent18b57012017-02-13 16:23:52 -08007670 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, portId, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007671
7672 return NO_ERROR;
7673}
7674
7675status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7676{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007677 ALOGV("%s handle %d", __FUNCTION__, handle);
7678
7679 if (mHalStream == 0) {
7680 return NO_INIT;
7681 }
7682
7683 sp<MmapTrack> track;
7684 for (const sp<MmapTrack> &t : mActiveTracks) {
7685 if (handle == t->portId()) {
7686 track = t;
7687 break;
7688 }
7689 }
7690 if (track == 0) {
7691 return BAD_VALUE;
7692 }
7693
7694 mActiveTracks.remove(track);
7695
7696 if (isOutput()) {
7697 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
7698 if (mActiveTracks.size() != 0) {
7699 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
7700 }
7701 } else {
7702 AudioSystem::stopInput(mId, track->sessionId());
7703 if (mActiveTracks.size() != 0) {
7704 AudioSystem::releaseInput(mId, track->sessionId());
7705 }
7706 }
7707
7708 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7709 if (chain != 0) {
7710 chain->decActiveTrackCnt();
7711 chain->decTrackCnt();
7712 }
7713
7714 broadcast_l();
7715
7716 if (mActiveTracks.size() == 0) {
7717 mHalStream->stop();
7718 }
7719 return NO_ERROR;
7720}
7721
Eric Laurent18b57012017-02-13 16:23:52 -08007722status_t AudioFlinger::MmapThread::standby()
7723{
7724 ALOGV("%s", __FUNCTION__);
7725
7726 if (mHalStream == 0) {
7727 return NO_INIT;
7728 }
7729 if (mActiveTracks.size() != 0) {
7730 return INVALID_OPERATION;
7731 }
7732 mHalStream->standby();
7733 mStandby = true;
7734 releaseWakeLock();
7735 return NO_ERROR;
7736}
7737
Eric Laurent6acd1d42017-01-04 14:23:29 -08007738
7739void AudioFlinger::MmapThread::readHalParameters_l()
7740{
7741 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7742 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7743 mFormat = mHALFormat;
7744 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7745 result = mHalStream->getFrameSize(&mFrameSize);
7746 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7747 result = mHalStream->getBufferSize(&mBufferSize);
7748 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7749 mFrameCount = mBufferSize / mFrameSize;
7750}
7751
7752bool AudioFlinger::MmapThread::threadLoop()
7753{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007754 checkSilentMode_l();
7755
7756 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7757
7758 while (!exitPending())
7759 {
7760 Mutex::Autolock _l(mLock);
7761 Vector< sp<EffectChain> > effectChains;
7762
7763 if (mSignalPending) {
7764 // A signal was raised while we were unlocked
7765 mSignalPending = false;
7766 } else {
7767 if (mConfigEvents.isEmpty()) {
7768 // we're about to wait, flush the binder command buffer
7769 IPCThreadState::self()->flushCommands();
7770
7771 if (exitPending()) {
7772 break;
7773 }
7774
Eric Laurent6acd1d42017-01-04 14:23:29 -08007775 // wait until we have something to do...
7776 ALOGV("%s going to sleep", myName.string());
7777 mWaitWorkCV.wait(mLock);
7778 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007779
7780 checkSilentMode_l();
7781
7782 continue;
7783 }
7784 }
7785
7786 processConfigEvents_l();
7787
7788 processVolume_l();
7789
7790 checkInvalidTracks_l();
7791
7792 mActiveTracks.updatePowerState(this);
7793
7794 lockEffectChains_l(effectChains);
7795 for (size_t i = 0; i < effectChains.size(); i ++) {
7796 effectChains[i]->process_l();
7797 }
7798 // enable changes in effect chain
7799 unlockEffectChains(effectChains);
7800 // Effect chains will be actually deleted here if they were removed from
7801 // mEffectChains list during mixing or effects processing
7802 }
7803
7804 threadLoop_exit();
7805
7806 if (!mStandby) {
7807 threadLoop_standby();
7808 mStandby = true;
7809 }
7810
Eric Laurent6acd1d42017-01-04 14:23:29 -08007811 ALOGV("Thread %p type %d exiting", this, mType);
7812 return false;
7813}
7814
7815// checkForNewParameter_l() must be called with ThreadBase::mLock held
7816bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7817 status_t& status)
7818{
7819 AudioParameter param = AudioParameter(keyValuePair);
7820 int value;
7821 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7822 // forward device change to effects that have requested to be
7823 // aware of attached audio device.
7824 if (value != AUDIO_DEVICE_NONE) {
7825 mOutDevice = value;
7826 for (size_t i = 0; i < mEffectChains.size(); i++) {
7827 mEffectChains[i]->setDevice_l(mOutDevice);
7828 }
7829 }
7830 }
7831 status = mHalStream->setParameters(keyValuePair);
7832
7833 return false;
7834}
7835
7836String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7837{
7838 Mutex::Autolock _l(mLock);
7839 String8 out_s8;
7840 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7841 return out_s8;
7842 }
7843 return String8();
7844}
7845
7846void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7847 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7848
7849 desc->mIoHandle = mId;
7850
7851 switch (event) {
7852 case AUDIO_INPUT_OPENED:
7853 case AUDIO_INPUT_CONFIG_CHANGED:
7854 case AUDIO_OUTPUT_OPENED:
7855 case AUDIO_OUTPUT_CONFIG_CHANGED:
7856 desc->mPatch = mPatch;
7857 desc->mChannelMask = mChannelMask;
7858 desc->mSamplingRate = mSampleRate;
7859 desc->mFormat = mFormat;
7860 desc->mFrameCount = mFrameCount;
7861 desc->mFrameCountHAL = mFrameCount;
7862 desc->mLatency = 0;
7863 break;
7864
7865 case AUDIO_INPUT_CLOSED:
7866 case AUDIO_OUTPUT_CLOSED:
7867 default:
7868 break;
7869 }
7870 mAudioFlinger->ioConfigChanged(event, desc, pid);
7871}
7872
7873status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7874 audio_patch_handle_t *handle)
7875{
7876 status_t status = NO_ERROR;
7877
7878 // store new device and send to effects
7879 audio_devices_t type = AUDIO_DEVICE_NONE;
7880 audio_port_handle_t deviceId;
7881 if (isOutput()) {
7882 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7883 type |= patch->sinks[i].ext.device.type;
7884 }
7885 deviceId = patch->sinks[0].id;
7886 } else {
7887 type = patch->sources[0].ext.device.type;
7888 deviceId = patch->sources[0].id;
7889 }
7890
7891 for (size_t i = 0; i < mEffectChains.size(); i++) {
7892 mEffectChains[i]->setDevice_l(type);
7893 }
7894
7895 if (isOutput()) {
7896 mOutDevice = type;
7897 } else {
7898 mInDevice = type;
7899 // store new source and send to effects
7900 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7901 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7902 for (size_t i = 0; i < mEffectChains.size(); i++) {
7903 mEffectChains[i]->setAudioSource_l(mAudioSource);
7904 }
7905 }
7906 }
7907
7908 if (mAudioHwDev->supportsAudioPatches()) {
7909 status = mHalDevice->createAudioPatch(patch->num_sources,
7910 patch->sources,
7911 patch->num_sinks,
7912 patch->sinks,
7913 handle);
7914 } else {
7915 char *address;
7916 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7917 //FIXME: we only support address on first sink with HAL version < 3.0
7918 address = audio_device_address_to_parameter(
7919 patch->sinks[0].ext.device.type,
7920 patch->sinks[0].ext.device.address);
7921 } else {
7922 address = (char *)calloc(1, 1);
7923 }
7924 AudioParameter param = AudioParameter(String8(address));
7925 free(address);
7926 param.addInt(String8(AudioParameter::keyRouting), (int)type);
7927 if (!isOutput()) {
7928 param.addInt(String8(AudioParameter::keyInputSource),
7929 (int)patch->sinks[0].ext.mix.usecase.source);
7930 }
7931 status = mHalStream->setParameters(param.toString());
7932 *handle = AUDIO_PATCH_HANDLE_NONE;
7933 }
7934
7935 if (isOutput() && mPrevOutDevice != mOutDevice) {
7936 mPrevOutDevice = type;
7937 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
7938 if (mCallback != 0) {
7939 mCallback->onRoutingChanged(deviceId);
7940 }
7941 }
7942 if (!isOutput() && mPrevInDevice != mInDevice) {
7943 mPrevInDevice = type;
7944 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7945 if (mCallback != 0) {
7946 mCallback->onRoutingChanged(deviceId);
7947 }
7948 }
7949 return status;
7950}
7951
7952status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7953{
7954 status_t status = NO_ERROR;
7955
7956 mInDevice = AUDIO_DEVICE_NONE;
7957
7958 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
7959 supportsAudioPatches : false;
7960
7961 if (supportsAudioPatches) {
7962 status = mHalDevice->releaseAudioPatch(handle);
7963 } else {
7964 AudioParameter param;
7965 param.addInt(String8(AudioParameter::keyRouting), 0);
7966 status = mHalStream->setParameters(param.toString());
7967 }
7968 return status;
7969}
7970
7971void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
7972{
7973 ThreadBase::getAudioPortConfig(config);
7974 if (isOutput()) {
7975 config->role = AUDIO_PORT_ROLE_SOURCE;
7976 config->ext.mix.hw_module = mAudioHwDev->handle();
7977 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
7978 } else {
7979 config->role = AUDIO_PORT_ROLE_SINK;
7980 config->ext.mix.hw_module = mAudioHwDev->handle();
7981 config->ext.mix.usecase.source = mAudioSource;
7982 }
7983}
7984
7985status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
7986{
7987 audio_session_t session = chain->sessionId();
7988
7989 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
7990 // Attach all tracks with same session ID to this chain.
7991 // indicate all active tracks in the chain
7992 for (const sp<MmapTrack> &track : mActiveTracks) {
7993 if (session == track->sessionId()) {
7994 chain->incTrackCnt();
7995 chain->incActiveTrackCnt();
7996 }
7997 }
7998
7999 chain->setThread(this);
8000 chain->setInBuffer(nullptr);
8001 chain->setOutBuffer(nullptr);
8002 chain->syncHalEffectsState();
8003
8004 mEffectChains.add(chain);
8005 checkSuspendOnAddEffectChain_l(chain);
8006 return NO_ERROR;
8007}
8008
8009size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8010{
8011 audio_session_t session = chain->sessionId();
8012
8013 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8014
8015 for (size_t i = 0; i < mEffectChains.size(); i++) {
8016 if (chain == mEffectChains[i]) {
8017 mEffectChains.removeAt(i);
8018 // detach all active tracks from the chain
8019 // detach all tracks with same session ID from this chain
8020 for (const sp<MmapTrack> &track : mActiveTracks) {
8021 if (session == track->sessionId()) {
8022 chain->decActiveTrackCnt();
8023 chain->decTrackCnt();
8024 }
8025 }
8026 break;
8027 }
8028 }
8029 return mEffectChains.size();
8030}
8031
8032// hasAudioSession_l() must be called with ThreadBase::mLock held
8033uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8034{
8035 uint32_t result = 0;
8036 if (getEffectChain_l(sessionId) != 0) {
8037 result = EFFECT_SESSION;
8038 }
8039
8040 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8041 sp<MmapTrack> track = mActiveTracks[i];
8042 if (sessionId == track->sessionId()) {
8043 result |= TRACK_SESSION;
8044 if (track->isFastTrack()) {
8045 result |= FAST_SESSION;
8046 }
8047 break;
8048 }
8049 }
8050
8051 return result;
8052}
8053
8054void AudioFlinger::MmapThread::threadLoop_standby()
8055{
8056 mHalStream->standby();
8057}
8058
8059void AudioFlinger::MmapThread::threadLoop_exit()
8060{
8061 if (mCallback != 0) {
8062 mCallback->onTearDown();
8063 }
8064}
8065
8066status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8067{
8068 return BAD_VALUE;
8069}
8070
8071bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8072{
8073 return false;
8074}
8075
8076status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8077 const effect_descriptor_t *desc, audio_session_t sessionId)
8078{
8079 // No global effect sessions on mmap threads
8080 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8081 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8082 desc->name, mThreadName);
8083 return BAD_VALUE;
8084 }
8085
8086 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8087 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8088 desc->name);
8089 return BAD_VALUE;
8090 }
8091 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008092 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8093 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008094 return BAD_VALUE;
8095 }
8096
8097 // Only allow effects without processing load or latency
8098 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8099 return BAD_VALUE;
8100 }
8101
8102 return NO_ERROR;
8103
8104}
8105
8106void AudioFlinger::MmapThread::checkInvalidTracks_l()
8107{
8108 for (const sp<MmapTrack> &track : mActiveTracks) {
8109 if (track->isInvalid()) {
8110 if (mCallback != 0) {
8111 mCallback->onTearDown();
8112 }
8113 break;
8114 }
8115 }
8116}
8117
8118void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8119{
8120 dumpInternals(fd, args);
8121 dumpTracks(fd, args);
8122 dumpEffectChains(fd, args);
8123}
8124
8125void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8126{
8127 dprintf(fd, "\nMmap thread %p:\n", this);
8128
8129 dumpBase(fd, args);
8130
8131 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8132 mAttr.content_type, mAttr.usage, mAttr.source);
8133 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8134 if (mActiveTracks.size() == 0) {
8135 dprintf(fd, " No active clients\n");
8136 }
8137}
8138
8139void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8140{
8141 const size_t SIZE = 256;
8142 char buffer[SIZE];
8143 String8 result;
8144
8145 size_t numtracks = mActiveTracks.size();
8146 dprintf(fd, " %zu Tracks", numtracks);
8147 if (numtracks) {
8148 MmapTrack::appendDumpHeader(result);
8149 for (size_t i = 0; i < numtracks ; ++i) {
8150 sp<MmapTrack> track = mActiveTracks[i];
8151 track->dump(buffer, SIZE);
8152 result.append(buffer);
8153 }
8154 } else {
8155 dprintf(fd, "\n");
8156 }
8157 write(fd, result.string(), result.size());
8158}
8159
8160AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8161 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8162 AudioHwDevice *hwDev, AudioStreamOut *output,
8163 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8164 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8165 mStreamType(AUDIO_STREAM_MUSIC),
8166 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8167{
8168 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8169 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8170 mMasterVolume = audioFlinger->masterVolume_l();
8171 mMasterMute = audioFlinger->masterMute_l();
8172 if (mAudioHwDev) {
8173 if (mAudioHwDev->canSetMasterVolume()) {
8174 mMasterVolume = 1.0;
8175 }
8176
8177 if (mAudioHwDev->canSetMasterMute()) {
8178 mMasterMute = false;
8179 }
8180 }
8181}
8182
8183void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8184 audio_stream_type_t streamType,
8185 audio_session_t sessionId,
8186 const sp<MmapStreamCallback>& callback,
8187 audio_port_handle_t portId)
8188{
8189 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8190 mStreamType = streamType;
8191}
8192
8193AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8194{
8195 Mutex::Autolock _l(mLock);
8196 AudioStreamOut *output = mOutput;
8197 mOutput = NULL;
8198 return output;
8199}
8200
8201void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8202{
8203 Mutex::Autolock _l(mLock);
8204 // Don't apply master volume in SW if our HAL can do it for us.
8205 if (mAudioHwDev &&
8206 mAudioHwDev->canSetMasterVolume()) {
8207 mMasterVolume = 1.0;
8208 } else {
8209 mMasterVolume = value;
8210 }
8211}
8212
8213void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8214{
8215 Mutex::Autolock _l(mLock);
8216 // Don't apply master mute in SW if our HAL can do it for us.
8217 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8218 mMasterMute = false;
8219 } else {
8220 mMasterMute = muted;
8221 }
8222}
8223
8224void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8225{
8226 Mutex::Autolock _l(mLock);
8227 if (stream == mStreamType) {
8228 mStreamVolume = value;
8229 broadcast_l();
8230 }
8231}
8232
8233float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8234{
8235 Mutex::Autolock _l(mLock);
8236 if (stream == mStreamType) {
8237 return mStreamVolume;
8238 }
8239 return 0.0f;
8240}
8241
8242void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8243{
8244 Mutex::Autolock _l(mLock);
8245 if (stream == mStreamType) {
8246 mStreamMute= muted;
8247 broadcast_l();
8248 }
8249}
8250
8251void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8252{
8253 Mutex::Autolock _l(mLock);
8254 if (streamType == mStreamType) {
8255 for (const sp<MmapTrack> &track : mActiveTracks) {
8256 track->invalidate();
8257 }
8258 broadcast_l();
8259 }
8260}
8261
8262void AudioFlinger::MmapPlaybackThread::processVolume_l()
8263{
8264 float volume;
8265
8266 if (mMasterMute || mStreamMute) {
8267 volume = 0;
8268 } else {
8269 volume = mMasterVolume * mStreamVolume;
8270 }
8271
8272 if (volume != mHalVolFloat) {
8273 mHalVolFloat = volume;
8274
8275 // Convert volumes from float to 8.24
8276 uint32_t vol = (uint32_t)(volume * (1 << 24));
8277
8278 // Delegate volume control to effect in track effect chain if needed
8279 // only one effect chain can be present on DirectOutputThread, so if
8280 // there is one, the track is connected to it
8281 if (!mEffectChains.isEmpty()) {
8282 mEffectChains[0]->setVolume_l(&vol, &vol);
8283 volume = (float)vol / (1 << 24);
8284 }
8285
8286 mOutput->stream->setVolume(volume, volume);
8287
8288 if (mCallback != 0) {
8289 int channelCount;
8290 if (isOutput()) {
8291 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8292 } else {
8293 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8294 }
8295 Vector<float> values;
8296 for (int i = 0; i < channelCount; i++) {
8297 values.add(volume);
8298 }
8299 mCallback->onVolumeChanged(mChannelMask, values);
8300 }
8301 }
8302}
8303
8304void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8305{
8306 if (!mMasterMute) {
8307 char value[PROPERTY_VALUE_MAX];
8308 if (property_get("ro.audio.silent", value, "0") > 0) {
8309 char *endptr;
8310 unsigned long ul = strtoul(value, &endptr, 0);
8311 if (*endptr == '\0' && ul != 0) {
8312 ALOGD("Silence is golden");
8313 // The setprop command will not allow a property to be changed after
8314 // the first time it is set, so we don't have to worry about un-muting.
8315 setMasterMute_l(true);
8316 }
8317 }
8318 }
8319}
8320
8321void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8322{
8323 MmapThread::dumpInternals(fd, args);
8324
Glenn Kastend3bb6452016-12-05 18:14:37 -08008325 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8326 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008327 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8328}
8329
8330AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8331 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8332 AudioHwDevice *hwDev, AudioStreamIn *input,
8333 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8334 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8335 mInput(input)
8336{
8337 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8338 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8339}
8340
8341AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8342{
8343 Mutex::Autolock _l(mLock);
8344 AudioStreamIn *input = mInput;
8345 mInput = NULL;
8346 return input;
8347}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008348} // namespace android