blob: 5cdabbc255593ddf998e650a04e0bd106b2a8c84 [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";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800450 case MMAP:
451 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700452 default:
453 return "unknown";
454 }
455}
456
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700461 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800462 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700463 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800464 }
465 return result;
466}
467
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700468std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800469{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700470 std::string result;
471 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800472 return result;
473}
474
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700475std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700476{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700477 std::string result;
478 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700479 return result;
480}
481
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800482const char *sourceToString(audio_source_t source)
483{
484 switch (source) {
485 case AUDIO_SOURCE_DEFAULT: return "default";
486 case AUDIO_SOURCE_MIC: return "mic";
487 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
488 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
489 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
490 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
491 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
492 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
493 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800494 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800495 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
496 case AUDIO_SOURCE_HOTWORD: return "hotword";
497 default: return "unknown";
498 }
499}
500
Eric Laurent81784c32012-11-19 14:55:58 -0800501AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700502 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800503 : Thread(false /*canCallJava*/),
504 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700505 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700506 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800507 // are set by PlaybackThread::readOutputParameters_l() or
508 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700509 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800510 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700511 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
512 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800513 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700514 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800515 mSystemReady(systemReady),
516 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800517{
Eric Laurent296fb132015-05-01 11:38:42 -0700518 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800519}
520
521AudioFlinger::ThreadBase::~ThreadBase()
522{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700523 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700524 mConfigEvents.clear();
525
Eric Laurent81784c32012-11-19 14:55:58 -0800526 // do not lock the mutex in destructor
527 releaseWakeLock_l();
528 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800529 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800530 binder->unlinkToDeath(mDeathRecipient);
531 }
532}
533
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700534status_t AudioFlinger::ThreadBase::readyToRun()
535{
536 status_t status = initCheck();
537 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800538 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700539 } else {
540 ALOGE("No working audio driver found.");
541 }
542 return status;
543}
544
Eric Laurent81784c32012-11-19 14:55:58 -0800545void AudioFlinger::ThreadBase::exit()
546{
547 ALOGV("ThreadBase::exit");
548 // do any cleanup required for exit to succeed
549 preExit();
550 {
551 // This lock prevents the following race in thread (uniprocessor for illustration):
552 // if (!exitPending()) {
553 // // context switch from here to exit()
554 // // exit() calls requestExit(), what exitPending() observes
555 // // exit() calls signal(), which is dropped since no waiters
556 // // context switch back from exit() to here
557 // mWaitWorkCV.wait(...);
558 // // now thread is hung
559 // }
560 AutoMutex lock(mLock);
561 requestExit();
562 mWaitWorkCV.broadcast();
563 }
564 // When Thread::requestExitAndWait is made virtual and this method is renamed to
565 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
566 requestExitAndWait();
567}
568
569status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
570{
Eric Laurent81784c32012-11-19 14:55:58 -0800571 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
572 Mutex::Autolock _l(mLock);
573
Eric Laurent10351942014-05-08 18:49:52 -0700574 return sendSetParameterConfigEvent_l(keyValuePairs);
575}
576
577// sendConfigEvent_l() must be called with ThreadBase::mLock held
578// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
579status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
580{
581 status_t status = NO_ERROR;
582
Eric Laurent72e3f392015-05-20 14:43:50 -0700583 if (event->mRequiresSystemReady && !mSystemReady) {
584 event->mWaitStatus = false;
585 mPendingConfigEvents.add(event);
586 return status;
587 }
Eric Laurent10351942014-05-08 18:49:52 -0700588 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700589 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800590 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700591 mLock.unlock();
592 {
593 Mutex::Autolock _l(event->mLock);
594 while (event->mWaitStatus) {
595 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
596 event->mStatus = TIMED_OUT;
597 event->mWaitStatus = false;
598 }
599 }
600 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800601 }
Eric Laurent10351942014-05-08 18:49:52 -0700602 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800603 return status;
604}
605
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700606void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800607{
608 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800610}
611
612// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700613void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800614{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700615 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700616 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800617}
618
Mikhail Naganov83f04272017-02-07 10:45:09 -0800619void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700620{
621 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800622 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700623}
624
Eric Laurent81784c32012-11-19 14:55:58 -0800625// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800626void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
627 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800628{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800629 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700630 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800631}
632
Eric Laurent10351942014-05-08 18:49:52 -0700633// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
634status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800635{
Andy Hung2ddee192015-12-18 17:34:44 -0800636 sp<ConfigEvent> configEvent;
637 AudioParameter param(keyValuePair);
638 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700639 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800640 setMasterMono_l(value != 0);
641 if (param.size() == 1) {
642 return NO_ERROR; // should be a solo parameter - we don't pass down
643 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700644 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800645 configEvent = new SetParameterConfigEvent(param.toString());
646 } else {
647 configEvent = new SetParameterConfigEvent(keyValuePair);
648 }
Eric Laurent10351942014-05-08 18:49:52 -0700649 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700650}
651
Eric Laurent1c333e22014-05-20 10:48:17 -0700652status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
653 const struct audio_patch *patch,
654 audio_patch_handle_t *handle)
655{
656 Mutex::Autolock _l(mLock);
657 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
658 status_t status = sendConfigEvent_l(configEvent);
659 if (status == NO_ERROR) {
660 CreateAudioPatchConfigEventData *data =
661 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
662 *handle = data->mHandle;
663 }
664 return status;
665}
666
667status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
668 const audio_patch_handle_t handle)
669{
670 Mutex::Autolock _l(mLock);
671 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
672 return sendConfigEvent_l(configEvent);
673}
674
675
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700676// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700677void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700678{
Eric Laurent10351942014-05-08 18:49:52 -0700679 bool configChanged = false;
680
Eric Laurent81784c32012-11-19 14:55:58 -0800681 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700682 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700683 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800684 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700685 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700686 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700687 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
688 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800689 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700690 true /*asynchronous*/);
691 if (err != 0) {
692 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700693 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700694 }
695 } break;
696 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700697 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700698 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700699 } break;
700 case CFG_EVENT_SET_PARAMETER: {
701 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
702 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
703 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700704 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
705 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700706 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700707 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700708 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700709 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700710 CreateAudioPatchConfigEventData *data =
711 (CreateAudioPatchConfigEventData *)event->mData.get();
712 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700713 const audio_devices_t newDevice = getDevice();
714 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
715 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
716 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700717 } break;
718 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700719 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700720 ReleaseAudioPatchConfigEventData *data =
721 (ReleaseAudioPatchConfigEventData *)event->mData.get();
722 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700723 const audio_devices_t newDevice = getDevice();
724 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
725 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
726 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700727 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700728 default:
Eric Laurent10351942014-05-08 18:49:52 -0700729 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700730 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800731 }
Eric Laurent10351942014-05-08 18:49:52 -0700732 {
733 Mutex::Autolock _l(event->mLock);
734 if (event->mWaitStatus) {
735 event->mWaitStatus = false;
736 event->mCond.signal();
737 }
738 }
739 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
740 }
741
742 if (configChanged) {
743 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800744 }
Eric Laurent81784c32012-11-19 14:55:58 -0800745}
746
Marco Nelissenb2208842014-02-07 14:00:50 -0800747String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
748 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700749 const audio_channel_representation_t representation =
750 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700751
752 switch (representation) {
753 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
754 if (output) {
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
756 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
758 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
760 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
761 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
763 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
764 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
765 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
770 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
771 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
772 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
773 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
774 } else {
775 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
776 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
777 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
778 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
779 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
781 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
782 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
783 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
784 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
785 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
786 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
787 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
788 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
789 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
790 }
791 const int len = s.length();
792 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700793 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794 s.unlockBuffer(len - 2); // remove trailing ", "
795 }
796 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800797 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700798 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
799 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
800 return s;
801 default:
802 s.appendFormat("unknown mask, representation:%d bits:%#x",
803 representation, audio_channel_mask_get_bits(mask));
804 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800805 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800806}
807
Glenn Kasten0f11b512014-01-31 16:18:54 -0800808void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800809{
810 const size_t SIZE = 256;
811 char buffer[SIZE];
812 String8 result;
813
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800814 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
815 this, mThreadName, getTid(), type(), threadTypeToString(type()));
816
Eric Laurent81784c32012-11-19 14:55:58 -0800817 bool locked = AudioFlinger::dumpTryLock(mLock);
818 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800819 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800820 }
821
Elliott Hughes87cebad2014-05-22 10:14:43 -0700822 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700825 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700826 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700827 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700828 dprintf(fd, " Channel count: %u\n", mChannelCount);
829 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800830 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700831 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700832 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700833 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800834 size_t numConfig = mConfigEvents.size();
835 if (numConfig) {
836 for (size_t i = 0; i < numConfig; i++) {
837 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800839 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700840 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800841 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700842 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800843 }
Andy Hung293558a2017-03-21 12:19:20 -0700844 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700845 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
846 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800847 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800848
849 if (locked) {
850 mLock.unlock();
851 }
852}
853
854void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
855{
856 const size_t SIZE = 256;
857 char buffer[SIZE];
858 String8 result;
859
Marco Nelissenb2208842014-02-07 14:00:50 -0800860 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000861 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800862 write(fd, buffer, strlen(buffer));
863
Marco Nelissenb2208842014-02-07 14:00:50 -0800864 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800865 sp<EffectChain> chain = mEffectChains[i];
866 if (chain != 0) {
867 chain->dump(fd, args);
868 }
869 }
870}
871
Andy Hungdae27702016-10-31 14:01:16 -0700872void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800873{
874 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700875 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800876}
877
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100878String16 AudioFlinger::ThreadBase::getWakeLockTag()
879{
880 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800881 case MIXER:
882 return String16("AudioMix");
883 case DIRECT:
884 return String16("AudioDirectOut");
885 case DUPLICATING:
886 return String16("AudioDup");
887 case RECORD:
888 return String16("AudioIn");
889 case OFFLOAD:
890 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800891 case MMAP:
892 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800893 default:
894 ALOG_ASSERT(false);
895 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100896 }
897}
898
Andy Hungdae27702016-10-31 14:01:16 -0700899void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800900{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800901 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800902 if (mPowerManager != 0) {
903 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700904 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
905 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700906 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100907 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700908 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700909 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 if (status == NO_ERROR) {
911 mWakeLockToken = binder;
912 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800913 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800914 }
Wei Jia3f273d12015-11-24 09:06:49 -0800915
Andy Hung3f0c9022016-01-15 17:49:46 -0800916 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800917 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
918 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800919}
920
921void AudioFlinger::ThreadBase::releaseWakeLock()
922{
923 Mutex::Autolock _l(mLock);
924 releaseWakeLock_l();
925}
926
927void AudioFlinger::ThreadBase::releaseWakeLock_l()
928{
Andy Hung3f0c9022016-01-15 17:49:46 -0800929 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800930 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800931 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700933 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
934 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800935 }
936 mWakeLockToken.clear();
937 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800938}
939
940void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700941 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800942 // use checkService() to avoid blocking if power service is not up yet
943 sp<IBinder> binder =
944 defaultServiceManager()->checkService(String16("power"));
945 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800946 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800947 } else {
948 mPowerManager = interface_cast<IPowerManager>(binder);
949 binder->linkToDeath(mDeathRecipient);
950 }
951 }
952}
953
Andy Hungd01b0f12016-11-07 16:10:30 -0800954void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800955 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700956
957#if !LOG_NDEBUG
958 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800959 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700960 s << uid << " ";
961 }
962 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
963#endif
964
Andy Hung438e7572015-12-14 15:51:17 -0800965 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
966 if (mSystemReady) {
967 ALOGE("no wake lock to update, but system ready!");
968 } else {
969 ALOGW("no wake lock to update, system not ready yet");
970 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800971 return;
972 }
973 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800974 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
975 status_t status = mPowerManager->updateWakeLockUids(
976 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
977 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800978 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800979 }
980}
981
Eric Laurent81784c32012-11-19 14:55:58 -0800982void AudioFlinger::ThreadBase::clearPowerManager()
983{
984 Mutex::Autolock _l(mLock);
985 releaseWakeLock_l();
986 mPowerManager.clear();
987}
988
Glenn Kasten0f11b512014-01-31 16:18:54 -0800989void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800990{
991 sp<ThreadBase> thread = mThread.promote();
992 if (thread != 0) {
993 thread->clearPowerManager();
994 }
995 ALOGW("power manager service died !!!");
996}
997
998void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800999 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001000{
1001 Mutex::Autolock _l(mLock);
1002 setEffectSuspended_l(type, suspend, sessionId);
1003}
1004
1005void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001006 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001007{
1008 sp<EffectChain> chain = getEffectChain_l(sessionId);
1009 if (chain != 0) {
1010 if (type != NULL) {
1011 chain->setEffectSuspended_l(type, suspend);
1012 } else {
1013 chain->setEffectSuspendedAll_l(suspend);
1014 }
1015 }
1016
1017 updateSuspendedSessions_l(type, suspend, sessionId);
1018}
1019
1020void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1021{
1022 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1023 if (index < 0) {
1024 return;
1025 }
1026
1027 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1028 mSuspendedSessions.valueAt(index);
1029
1030 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001031 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001032 for (int j = 0; j < desc->mRefCount; j++) {
1033 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1034 chain->setEffectSuspendedAll_l(true);
1035 } else {
1036 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1037 desc->mType.timeLow);
1038 chain->setEffectSuspended_l(&desc->mType, true);
1039 }
1040 }
1041 }
1042}
1043
1044void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1045 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001046 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001047{
1048 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1049
1050 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1051
1052 if (suspend) {
1053 if (index >= 0) {
1054 sessionEffects = mSuspendedSessions.valueAt(index);
1055 } else {
1056 mSuspendedSessions.add(sessionId, sessionEffects);
1057 }
1058 } else {
1059 if (index < 0) {
1060 return;
1061 }
1062 sessionEffects = mSuspendedSessions.valueAt(index);
1063 }
1064
1065
1066 int key = EffectChain::kKeyForSuspendAll;
1067 if (type != NULL) {
1068 key = type->timeLow;
1069 }
1070 index = sessionEffects.indexOfKey(key);
1071
1072 sp<SuspendedSessionDesc> desc;
1073 if (suspend) {
1074 if (index >= 0) {
1075 desc = sessionEffects.valueAt(index);
1076 } else {
1077 desc = new SuspendedSessionDesc();
1078 if (type != NULL) {
1079 desc->mType = *type;
1080 }
1081 sessionEffects.add(key, desc);
1082 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1083 }
1084 desc->mRefCount++;
1085 } else {
1086 if (index < 0) {
1087 return;
1088 }
1089 desc = sessionEffects.valueAt(index);
1090 if (--desc->mRefCount == 0) {
1091 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1092 sessionEffects.removeItemsAt(index);
1093 if (sessionEffects.isEmpty()) {
1094 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1095 sessionId);
1096 mSuspendedSessions.removeItem(sessionId);
1097 }
1098 }
1099 }
1100 if (!sessionEffects.isEmpty()) {
1101 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1102 }
1103}
1104
1105void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1106 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001107 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001108{
1109 Mutex::Autolock _l(mLock);
1110 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1111}
1112
1113void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1114 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001115 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001116{
1117 if (mType != RECORD) {
1118 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1119 // another session. This gives the priority to well behaved effect control panels
1120 // and applications not using global effects.
1121 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1122 // global effects
1123 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1124 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1125 }
1126 }
1127
1128 sp<EffectChain> chain = getEffectChain_l(sessionId);
1129 if (chain != 0) {
1130 chain->checkSuspendOnEffectEnabled(effect, enabled);
1131 }
1132}
1133
Eric Laurent4c415062016-06-17 16:14:16 -07001134// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1135status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1136 const effect_descriptor_t *desc, audio_session_t sessionId)
1137{
1138 // No global effect sessions on record threads
1139 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1140 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1141 desc->name, mThreadName);
1142 return BAD_VALUE;
1143 }
1144 // only pre processing effects on record thread
1145 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1146 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1147 desc->name, mThreadName);
1148 return BAD_VALUE;
1149 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001150
1151 // always allow effects without processing load or latency
1152 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1153 return NO_ERROR;
1154 }
1155
Eric Laurent4c415062016-06-17 16:14:16 -07001156 audio_input_flags_t flags = mInput->flags;
1157 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1158 if (flags & AUDIO_INPUT_FLAG_RAW) {
1159 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1160 desc->name, mThreadName);
1161 return BAD_VALUE;
1162 }
1163 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1164 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1165 desc->name, mThreadName);
1166 return BAD_VALUE;
1167 }
1168 }
1169 return NO_ERROR;
1170}
1171
1172// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1173status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1174 const effect_descriptor_t *desc, audio_session_t sessionId)
1175{
1176 // no preprocessing on playback threads
1177 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1178 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1179 " thread %s", desc->name, mThreadName);
1180 return BAD_VALUE;
1181 }
1182
1183 switch (mType) {
1184 case MIXER: {
1185 // Reject any effect on mixer multichannel sinks.
1186 // TODO: fix both format and multichannel issues with effects.
1187 if (mChannelCount != FCC_2) {
1188 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1189 " thread %s", desc->name, mChannelCount, mThreadName);
1190 return BAD_VALUE;
1191 }
1192 audio_output_flags_t flags = mOutput->flags;
1193 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1194 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1195 // global effects are applied only to non fast tracks if they are SW
1196 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1197 break;
1198 }
1199 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1200 // only post processing on output stage session
1201 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1202 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1203 " on output stage session", desc->name);
1204 return BAD_VALUE;
1205 }
1206 } else {
1207 // no restriction on effects applied on non fast tracks
1208 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1209 break;
1210 }
1211 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001212
1213 // always allow effects without processing load or latency
1214 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1215 break;
1216 }
Eric Laurent4c415062016-06-17 16:14:16 -07001217 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1218 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1219 desc->name);
1220 return BAD_VALUE;
1221 }
1222 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1223 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1224 " in fast mode", desc->name);
1225 return BAD_VALUE;
1226 }
1227 }
1228 } break;
1229 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001230 // nothing actionable on offload threads, if the effect:
1231 // - is offloadable: the effect can be created
1232 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1233 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001234 break;
1235 case DIRECT:
1236 // Reject any effect on Direct output threads for now, since the format of
1237 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1238 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1239 desc->name, mThreadName);
1240 return BAD_VALUE;
1241 case DUPLICATING:
1242 // Reject any effect on mixer multichannel sinks.
1243 // TODO: fix both format and multichannel issues with effects.
1244 if (mChannelCount != FCC_2) {
1245 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1246 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1250 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1251 " thread %s", desc->name, mThreadName);
1252 return BAD_VALUE;
1253 }
1254 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1255 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1256 " DUPLICATING thread %s", desc->name, mThreadName);
1257 return BAD_VALUE;
1258 }
1259 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1260 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1261 " DUPLICATING thread %s", desc->name, mThreadName);
1262 return BAD_VALUE;
1263 }
1264 break;
1265 default:
1266 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1267 }
1268
1269 return NO_ERROR;
1270}
1271
Eric Laurent81784c32012-11-19 14:55:58 -08001272// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1273sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1274 const sp<AudioFlinger::Client>& client,
1275 const sp<IEffectClient>& effectClient,
1276 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001277 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001278 effect_descriptor_t *desc,
1279 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001280 status_t *status,
1281 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001282{
1283 sp<EffectModule> effect;
1284 sp<EffectHandle> handle;
1285 status_t lStatus;
1286 sp<EffectChain> chain;
1287 bool chainCreated = false;
1288 bool effectCreated = false;
1289 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001290 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001291
1292 lStatus = initCheck();
1293 if (lStatus != NO_ERROR) {
1294 ALOGW("createEffect_l() Audio driver not initialized.");
1295 goto Exit;
1296 }
1297
Eric Laurent81784c32012-11-19 14:55:58 -08001298 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1299
1300 { // scope for mLock
1301 Mutex::Autolock _l(mLock);
1302
Eric Laurent4c415062016-06-17 16:14:16 -07001303 lStatus = checkEffectCompatibility_l(desc, sessionId);
1304 if (lStatus != NO_ERROR) {
1305 goto Exit;
1306 }
1307
Eric Laurent81784c32012-11-19 14:55:58 -08001308 // check for existing effect chain with the requested audio session
1309 chain = getEffectChain_l(sessionId);
1310 if (chain == 0) {
1311 // create a new chain for this session
1312 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1313 chain = new EffectChain(this, sessionId);
1314 addEffectChain_l(chain);
1315 chain->setStrategy(getStrategyForSession_l(sessionId));
1316 chainCreated = true;
1317 } else {
1318 effect = chain->getEffectFromDesc_l(desc);
1319 }
1320
1321 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1322
1323 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001324 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001325 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001326 lStatus = AudioSystem::registerEffect(
1327 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001328 if (lStatus != NO_ERROR) {
1329 goto Exit;
1330 }
1331 effectRegistered = true;
1332 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001333 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001334 if (lStatus != NO_ERROR) {
1335 goto Exit;
1336 }
1337 effectCreated = true;
1338
1339 effect->setDevice(mOutDevice);
1340 effect->setDevice(mInDevice);
1341 effect->setMode(mAudioFlinger->getMode());
1342 effect->setAudioSource(mAudioSource);
1343 }
1344 // create effect handle and connect it to effect module
1345 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001346 lStatus = handle->initCheck();
1347 if (lStatus == OK) {
1348 lStatus = effect->addHandle(handle.get());
1349 }
Eric Laurent81784c32012-11-19 14:55:58 -08001350 if (enabled != NULL) {
1351 *enabled = (int)effect->isEnabled();
1352 }
1353 }
1354
1355Exit:
1356 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1357 Mutex::Autolock _l(mLock);
1358 if (effectCreated) {
1359 chain->removeEffect_l(effect);
1360 }
1361 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001362 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001363 }
1364 if (chainCreated) {
1365 removeEffectChain_l(chain);
1366 }
1367 handle.clear();
1368 }
1369
Glenn Kasten9156ef32013-08-06 15:39:08 -07001370 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001371 return handle;
1372}
1373
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001374void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1375 bool unpinIfLast)
1376{
1377 bool remove = false;
1378 sp<EffectModule> effect;
1379 {
1380 Mutex::Autolock _l(mLock);
1381
1382 effect = handle->effect().promote();
1383 if (effect == 0) {
1384 return;
1385 }
1386 // restore suspended effects if the disconnected handle was enabled and the last one.
1387 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1388 if (remove) {
1389 removeEffect_l(effect, true);
1390 }
1391 }
1392 if (remove) {
1393 mAudioFlinger->updateOrphanEffectChains(effect);
1394 AudioSystem::unregisterEffect(effect->id());
1395 if (handle->enabled()) {
1396 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1397 }
1398 }
1399}
1400
Glenn Kastend848eb42016-03-08 13:42:11 -08001401sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1402 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001403{
1404 Mutex::Autolock _l(mLock);
1405 return getEffect_l(sessionId, effectId);
1406}
1407
Glenn Kastend848eb42016-03-08 13:42:11 -08001408sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1409 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001410{
1411 sp<EffectChain> chain = getEffectChain_l(sessionId);
1412 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1413}
1414
1415// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1416// PlaybackThread::mLock held
1417status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1418{
1419 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001420 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001421 sp<EffectChain> chain = getEffectChain_l(sessionId);
1422 bool chainCreated = false;
1423
Eric Laurent5baf2af2013-09-12 17:37:00 -07001424 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1425 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1426 this, effect->desc().name, effect->desc().flags);
1427
Eric Laurent81784c32012-11-19 14:55:58 -08001428 if (chain == 0) {
1429 // create a new chain for this session
1430 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1431 chain = new EffectChain(this, sessionId);
1432 addEffectChain_l(chain);
1433 chain->setStrategy(getStrategyForSession_l(sessionId));
1434 chainCreated = true;
1435 }
1436 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1437
1438 if (chain->getEffectFromId_l(effect->id()) != 0) {
1439 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1440 this, effect->desc().name, chain.get());
1441 return BAD_VALUE;
1442 }
1443
Eric Laurent5baf2af2013-09-12 17:37:00 -07001444 effect->setOffloaded(mType == OFFLOAD, mId);
1445
Eric Laurent81784c32012-11-19 14:55:58 -08001446 status_t status = chain->addEffect_l(effect);
1447 if (status != NO_ERROR) {
1448 if (chainCreated) {
1449 removeEffectChain_l(chain);
1450 }
1451 return status;
1452 }
1453
1454 effect->setDevice(mOutDevice);
1455 effect->setDevice(mInDevice);
1456 effect->setMode(mAudioFlinger->getMode());
1457 effect->setAudioSource(mAudioSource);
1458 return NO_ERROR;
1459}
1460
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001461void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001462
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001463 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001464 effect_descriptor_t desc = effect->desc();
1465 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1466 detachAuxEffect_l(effect->id());
1467 }
1468
1469 sp<EffectChain> chain = effect->chain().promote();
1470 if (chain != 0) {
1471 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001472 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001473 removeEffectChain_l(chain);
1474 }
1475 } else {
1476 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1477 }
1478}
1479
1480void AudioFlinger::ThreadBase::lockEffectChains_l(
1481 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1482{
1483 effectChains = mEffectChains;
1484 for (size_t i = 0; i < mEffectChains.size(); i++) {
1485 mEffectChains[i]->lock();
1486 }
1487}
1488
1489void AudioFlinger::ThreadBase::unlockEffectChains(
1490 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1491{
1492 for (size_t i = 0; i < effectChains.size(); i++) {
1493 effectChains[i]->unlock();
1494 }
1495}
1496
Glenn Kastend848eb42016-03-08 13:42:11 -08001497sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001498{
1499 Mutex::Autolock _l(mLock);
1500 return getEffectChain_l(sessionId);
1501}
1502
Glenn Kastend848eb42016-03-08 13:42:11 -08001503sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1504 const
Eric Laurent81784c32012-11-19 14:55:58 -08001505{
1506 size_t size = mEffectChains.size();
1507 for (size_t i = 0; i < size; i++) {
1508 if (mEffectChains[i]->sessionId() == sessionId) {
1509 return mEffectChains[i];
1510 }
1511 }
1512 return 0;
1513}
1514
1515void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1516{
1517 Mutex::Autolock _l(mLock);
1518 size_t size = mEffectChains.size();
1519 for (size_t i = 0; i < size; i++) {
1520 mEffectChains[i]->setMode_l(mode);
1521 }
1522}
1523
Eric Laurent83b88082014-06-20 18:31:16 -07001524void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1525{
1526 config->type = AUDIO_PORT_TYPE_MIX;
1527 config->ext.mix.handle = mId;
1528 config->sample_rate = mSampleRate;
1529 config->format = mFormat;
1530 config->channel_mask = mChannelMask;
1531 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1532 AUDIO_PORT_CONFIG_FORMAT;
1533}
1534
Eric Laurent72e3f392015-05-20 14:43:50 -07001535void AudioFlinger::ThreadBase::systemReady()
1536{
1537 Mutex::Autolock _l(mLock);
1538 if (mSystemReady) {
1539 return;
1540 }
1541 mSystemReady = true;
1542
1543 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1544 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1545 }
1546 mPendingConfigEvents.clear();
1547}
1548
Andy Hungdae27702016-10-31 14:01:16 -07001549template <typename T>
1550ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1551 ssize_t index = mActiveTracks.indexOf(track);
1552 if (index >= 0) {
1553 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1554 return index;
1555 }
1556 mActiveTracksGeneration++;
1557 mLatestActiveTrack = track;
1558 ++mBatteryCounter[track->uid()].second;
1559 return mActiveTracks.add(track);
1560}
1561
1562template <typename T>
1563ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1564 ssize_t index = mActiveTracks.remove(track);
1565 if (index < 0) {
1566 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1567 return index;
1568 }
1569 mActiveTracksGeneration++;
1570 --mBatteryCounter[track->uid()].second;
1571 // mLatestActiveTrack is not cleared even if is the same as track.
1572 return index;
1573}
1574
1575template <typename T>
1576void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1577 for (const sp<T> &track : mActiveTracks) {
1578 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1579 }
1580 mLastActiveTracksGeneration = mActiveTracksGeneration;
1581 mActiveTracks.clear();
1582 mLatestActiveTrack.clear();
1583 mBatteryCounter.clear();
1584}
1585
1586template <typename T>
1587void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1588 sp<ThreadBase> thread, bool force) {
1589 // Updates ActiveTracks client uids to the thread wakelock.
1590 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1591 thread->updateWakeLockUids_l(getWakeLockUids());
1592 mLastActiveTracksGeneration = mActiveTracksGeneration;
1593 }
1594
1595 // Updates BatteryNotifier uids
1596 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1597 const uid_t uid = it->first;
1598 ssize_t &previous = it->second.first;
1599 ssize_t &current = it->second.second;
1600 if (current > 0) {
1601 if (previous == 0) {
1602 BatteryNotifier::getInstance().noteStartAudio(uid);
1603 }
1604 previous = current;
1605 ++it;
1606 } else if (current == 0) {
1607 if (previous > 0) {
1608 BatteryNotifier::getInstance().noteStopAudio(uid);
1609 }
1610 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1611 } else /* (current < 0) */ {
1612 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1613 }
1614 }
1615}
Eric Laurent83b88082014-06-20 18:31:16 -07001616
Eric Laurent6acd1d42017-01-04 14:23:29 -08001617void AudioFlinger::ThreadBase::broadcast_l()
1618{
1619 // Thread could be blocked waiting for async
1620 // so signal it to handle state changes immediately
1621 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1622 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1623 mSignalPending = true;
1624 mWaitWorkCV.broadcast();
1625}
1626
Eric Laurent81784c32012-11-19 14:55:58 -08001627// ----------------------------------------------------------------------------
1628// Playback
1629// ----------------------------------------------------------------------------
1630
1631AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1632 AudioStreamOut* output,
1633 audio_io_handle_t id,
1634 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001635 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001636 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001637 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001638 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001639 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001640 mMixerBuffer(NULL),
1641 mMixerBufferSize(0),
1642 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1643 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001644 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001645 mEffectBuffer(NULL),
1646 mEffectBufferSize(0),
1647 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1648 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001649 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001650 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001651 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001652 // mStreamTypes[] initialized in constructor body
1653 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001654 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001655 mMixerStatus(MIXER_IDLE),
1656 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001657 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001658 mBytesRemaining(0),
1659 mCurrentWriteLength(0),
1660 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001661 mWriteAckSequence(0),
1662 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001663 mScreenState(AudioFlinger::mScreenState),
1664 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001665 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001666 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001667{
Glenn Kastend7dca052015-03-05 16:05:54 -08001668 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1669 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001670
1671 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1672 // it would be safer to explicitly pass initial masterVolume/masterMute as
1673 // parameter.
1674 //
1675 // If the HAL we are using has support for master volume or master mute,
1676 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1677 // and the mute set to false).
1678 mMasterVolume = audioFlinger->masterVolume_l();
1679 mMasterMute = audioFlinger->masterMute_l();
1680 if (mOutput && mOutput->audioHwDev) {
1681 if (mOutput->audioHwDev->canSetMasterVolume()) {
1682 mMasterVolume = 1.0;
1683 }
1684
1685 if (mOutput->audioHwDev->canSetMasterMute()) {
1686 mMasterMute = false;
1687 }
1688 }
1689
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001690 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001691
Eric Laurent223fd5c2014-11-11 13:43:36 -08001692 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001693 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001694 stream = (audio_stream_type_t) (stream + 1)) {
1695 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1696 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1697 }
Eric Laurent81784c32012-11-19 14:55:58 -08001698}
1699
1700AudioFlinger::PlaybackThread::~PlaybackThread()
1701{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001702 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001703 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001704 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001705 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001706}
1707
1708void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1709{
1710 dumpInternals(fd, args);
1711 dumpTracks(fd, args);
1712 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001713 dprintf(fd, " Local log:\n");
1714 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001715}
1716
Glenn Kasten0f11b512014-01-31 16:18:54 -08001717void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001718{
1719 const size_t SIZE = 256;
1720 char buffer[SIZE];
1721 String8 result;
1722
Marco Nelissenb2208842014-02-07 14:00:50 -08001723 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001724 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1725 const stream_type_t *st = &mStreamTypes[i];
1726 if (i > 0) {
1727 result.appendFormat(", ");
1728 }
1729 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1730 if (st->mute) {
1731 result.append("M");
1732 }
1733 }
1734 result.append("\n");
1735 write(fd, result.string(), result.length());
1736 result.clear();
1737
Eric Laurent81784c32012-11-19 14:55:58 -08001738 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1739 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001740 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001741 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001742
1743 size_t numtracks = mTracks.size();
1744 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001745 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001746 size_t numactiveseen = 0;
1747 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001748 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001749 Track::appendDumpHeader(result);
1750 for (size_t i = 0; i < numtracks; ++i) {
1751 sp<Track> track = mTracks[i];
1752 if (track != 0) {
1753 bool active = mActiveTracks.indexOf(track) >= 0;
1754 if (active) {
1755 numactiveseen++;
1756 }
1757 track->dump(buffer, SIZE, active);
1758 result.append(buffer);
1759 }
1760 }
1761 } else {
1762 result.append("\n");
1763 }
1764 if (numactiveseen != numactive) {
1765 // some tracks in the active list were not in the tracks list
1766 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1767 " not in the track list\n");
1768 result.append(buffer);
1769 Track::appendDumpHeader(result);
1770 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001771 sp<Track> track = mActiveTracks[i];
1772 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001773 track->dump(buffer, SIZE, true);
1774 result.append(buffer);
1775 }
1776 }
1777 }
1778
1779 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001780}
1781
1782void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1783{
Glenn Kasten44182c22015-03-05 17:12:23 -08001784 dumpBase(fd, args);
1785
Elliott Hughes87cebad2014-05-22 10:14:43 -07001786 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001787 dprintf(fd, " Last write occurred (msecs): %llu\n",
1788 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001789 dprintf(fd, " Total writes: %d\n", mNumWrites);
1790 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1791 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1792 dprintf(fd, " Suspend count: %d\n", mSuspended);
1793 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1794 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1795 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1796 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001797 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001798 AudioStreamOut *output = mOutput;
1799 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001800 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1801 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001802 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1803 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1804 if (mPipeSink.get() != nullptr) {
1805 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1806 }
1807 if (output != nullptr) {
1808 dprintf(fd, " Hal stream dump:\n");
1809 (void)output->stream->dump(fd);
1810 }
Eric Laurent81784c32012-11-19 14:55:58 -08001811}
1812
1813// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001814
1815void AudioFlinger::PlaybackThread::onFirstRef()
1816{
Glenn Kastend7dca052015-03-05 16:05:54 -08001817 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001818}
1819
1820// ThreadBase virtuals
1821void AudioFlinger::PlaybackThread::preExit()
1822{
1823 ALOGV(" preExit()");
1824 // FIXME this is using hard-coded strings but in the future, this functionality will be
1825 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001826 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1827 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001828}
1829
1830// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1831sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1832 const sp<AudioFlinger::Client>& client,
1833 audio_stream_type_t streamType,
1834 uint32_t sampleRate,
1835 audio_format_t format,
1836 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001837 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001838 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001839 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001840 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001841 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001842 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001843 status_t *status,
1844 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001845{
Glenn Kasten74935e42013-12-19 08:56:45 -08001846 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001847 sp<Track> track;
1848 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001849 audio_output_flags_t outputFlags = mOutput->flags;
1850
1851 // special case for FAST flag considered OK if fast mixer is present
1852 if (hasFastMixer()) {
1853 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1854 }
1855
1856 // Check if requested flags are compatible with output stream flags
1857 if ((*flags & outputFlags) != *flags) {
1858 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1859 *flags, outputFlags);
1860 *flags = (audio_output_flags_t)(*flags & outputFlags);
1861 }
Eric Laurent81784c32012-11-19 14:55:58 -08001862
Eric Laurent81784c32012-11-19 14:55:58 -08001863 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001864 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001865 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001866 // PCM data
1867 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001868 // TODO: extract as a data library function that checks that a computationally
1869 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001870 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001871 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1872 (channelMask == AUDIO_CHANNEL_OUT_MONO
1873 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001874 // hardware sample rate
1875 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001876 // normal mixer has an associated fast mixer
1877 hasFastMixer() &&
1878 // there are sufficient fast track slots available
1879 (mFastTrackAvailMask != 0)
1880 // FIXME test that MixerThread for this fast track has a capable output HAL
1881 // FIXME add a permission test also?
1882 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001883 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1884 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001885 // read the fast track multiplier property the first time it is needed
1886 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1887 if (ok != 0) {
1888 ALOGE("%s pthread_once failed: %d", __func__, ok);
1889 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001890 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001891 }
Eric Laurent4c415062016-06-17 16:14:16 -07001892
1893 // check compatibility with audio effects.
1894 { // scope for mLock
1895 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001896 for (audio_session_t session : {
1897 AUDIO_SESSION_OUTPUT_STAGE,
1898 AUDIO_SESSION_OUTPUT_MIX,
1899 sessionId,
1900 }) {
1901 sp<EffectChain> chain = getEffectChain_l(session);
1902 if (chain.get() != nullptr) {
1903 audio_output_flags_t old = *flags;
1904 chain->checkOutputFlagCompatibility(flags);
1905 if (old != *flags) {
1906 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1907 (int)session, (int)old, (int)*flags);
1908 }
Eric Laurent4c415062016-06-17 16:14:16 -07001909 }
1910 }
1911 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001912 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001913 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1914 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001915 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001916 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1917 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001918 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001919 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001920 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001921 audio_is_linear_pcm(format),
1922 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001923 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001924 }
1925 }
1926 // For normal PCM streaming tracks, update minimum frame count.
1927 // For compatibility with AudioTrack calculation, buffer depth is forced
1928 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1929 // This is probably too conservative, but legacy application code may depend on it.
1930 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001931 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001932 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001933 // this must match AudioTrack.cpp calculateMinFrameCount().
1934 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001935 uint32_t latencyMs = 0;
1936 lStatus = mOutput->stream->getLatency(&latencyMs);
1937 if (lStatus != OK) {
1938 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1939 goto Exit;
1940 }
Eric Laurent81784c32012-11-19 14:55:58 -08001941 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1942 if (minBufCount < 2) {
1943 minBufCount = 2;
1944 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001945 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1946 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001947 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001948 minBufCount * sourceFramesNeededWithTimestretch(
1949 sampleRate, mNormalFrameCount,
1950 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001951 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001952 frameCount = minFrameCount;
1953 }
Eric Laurent81784c32012-11-19 14:55:58 -08001954 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001955 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001956
Glenn Kastenc3df8382014-03-13 15:05:25 -07001957 switch (mType) {
1958
1959 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001960 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001961 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001962 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1963 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001964 sampleRate, format, channelMask, mOutput, mFormat);
1965 lStatus = BAD_VALUE;
1966 goto Exit;
1967 }
1968 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001969 break;
1970
1971 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001972 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001973 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1974 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975 sampleRate, format, channelMask, mOutput, mFormat);
1976 lStatus = BAD_VALUE;
1977 goto Exit;
1978 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001979 break;
1980
1981 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001982 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001983 ALOGE("createTrack_l() Bad parameter: format %#x \""
1984 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001985 format, mOutput, mFormat);
1986 lStatus = BAD_VALUE;
1987 goto Exit;
1988 }
Andy Hungcd044842014-08-07 11:04:34 -07001989 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001990 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1991 lStatus = BAD_VALUE;
1992 goto Exit;
1993 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001994 break;
1995
Eric Laurent81784c32012-11-19 14:55:58 -08001996 }
1997
1998 lStatus = initCheck();
1999 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002000 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002001 goto Exit;
2002 }
2003
2004 { // scope for mLock
2005 Mutex::Autolock _l(mLock);
2006
2007 // all tracks in same audio session must share the same routing strategy otherwise
2008 // conflicts will happen when tracks are moved from one output to another by audio policy
2009 // manager
2010 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2011 for (size_t i = 0; i < mTracks.size(); ++i) {
2012 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002013 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002014 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2015 if (sessionId == t->sessionId() && strategy != actual) {
2016 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2017 strategy, actual);
2018 lStatus = BAD_VALUE;
2019 goto Exit;
2020 }
2021 }
2022 }
2023
Glenn Kastend79072e2016-01-06 08:41:20 -08002024 track = new Track(this, client, streamType, sampleRate, format,
2025 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002026 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002027
Glenn Kasten03003332013-08-06 15:40:54 -07002028 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2029 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002030 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002031 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002032 goto Exit;
2033 }
2034 mTracks.add(track);
2035
2036 sp<EffectChain> chain = getEffectChain_l(sessionId);
2037 if (chain != 0) {
2038 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2039 track->setMainBuffer(chain->inBuffer());
2040 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2041 chain->incTrackCnt();
2042 }
2043
Eric Laurent05067782016-06-01 18:27:28 -07002044 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002045 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2046 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2047 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08002048 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*isForApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002049 }
2050 }
2051
2052 lStatus = NO_ERROR;
2053
2054Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002055 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002056 return track;
2057}
2058
2059uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2060{
2061 return latency;
2062}
2063
2064uint32_t AudioFlinger::PlaybackThread::latency() const
2065{
2066 Mutex::Autolock _l(mLock);
2067 return latency_l();
2068}
2069uint32_t AudioFlinger::PlaybackThread::latency_l() const
2070{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002071 uint32_t latency;
2072 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2073 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002074 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002075 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002076}
2077
2078void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2079{
2080 Mutex::Autolock _l(mLock);
2081 // Don't apply master volume in SW if our HAL can do it for us.
2082 if (mOutput && mOutput->audioHwDev &&
2083 mOutput->audioHwDev->canSetMasterVolume()) {
2084 mMasterVolume = 1.0;
2085 } else {
2086 mMasterVolume = value;
2087 }
2088}
2089
2090void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2091{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002092 if (isDuplicating()) {
2093 return;
2094 }
Eric Laurent81784c32012-11-19 14:55:58 -08002095 Mutex::Autolock _l(mLock);
2096 // Don't apply master mute in SW if our HAL can do it for us.
2097 if (mOutput && mOutput->audioHwDev &&
2098 mOutput->audioHwDev->canSetMasterMute()) {
2099 mMasterMute = false;
2100 } else {
2101 mMasterMute = muted;
2102 }
2103}
2104
2105void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2106{
2107 Mutex::Autolock _l(mLock);
2108 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002109 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002110}
2111
2112void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2113{
2114 Mutex::Autolock _l(mLock);
2115 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002116 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002117}
2118
2119float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2120{
2121 Mutex::Autolock _l(mLock);
2122 return mStreamTypes[stream].volume;
2123}
2124
2125// addTrack_l() must be called with ThreadBase::mLock held
2126status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2127{
2128 status_t status = ALREADY_EXISTS;
2129
Eric Laurent81784c32012-11-19 14:55:58 -08002130 if (mActiveTracks.indexOf(track) < 0) {
2131 // the track is newly added, make sure it fills up all its
2132 // buffers before playing. This is to ensure the client will
2133 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002134 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002135 TrackBase::track_state state = track->mState;
2136 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002137 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002138 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002139 mLock.lock();
2140 // abort track was stopped/paused while we released the lock
2141 if (state != track->mState) {
2142 if (status == NO_ERROR) {
2143 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002144 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002145 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002146 mLock.lock();
2147 }
2148 return INVALID_OPERATION;
2149 }
2150 // abort if start is rejected by audio policy manager
2151 if (status != NO_ERROR) {
2152 return PERMISSION_DENIED;
2153 }
2154#ifdef ADD_BATTERY_DATA
2155 // to track the speaker usage
2156 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2157#endif
2158 }
2159
Eric Laurent51716182016-02-29 18:00:56 -08002160 // set retry count for buffer fill
2161 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002162 if (track->isStopping_1()) {
2163 track->mRetryCount = kMaxTrackStopRetriesOffload;
2164 } else {
2165 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2166 }
2167 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002168 } else {
2169 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002170 track->mFillingUpStatus =
2171 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002172 }
2173
Eric Laurent81784c32012-11-19 14:55:58 -08002174 track->mResetDone = false;
2175 track->mPresentationCompleteFrames = 0;
2176 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002177 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2178 if (chain != 0) {
2179 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2180 track->sessionId());
2181 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002182 }
2183
Andy Hung2148bf02016-11-28 19:01:02 -08002184 char buffer[256];
2185 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2186 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2187
Eric Laurent81784c32012-11-19 14:55:58 -08002188 status = NO_ERROR;
2189 }
2190
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002191 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002192 return status;
2193}
2194
Eric Laurentbfb1b832013-01-07 09:53:42 -08002195bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002196{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002197 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002198 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002199 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2200 track->mState = TrackBase::STOPPED;
2201 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002202 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002203 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002205 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206
2207 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002208}
2209
2210void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2211{
2212 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002213
2214 char buffer[256];
2215 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2216 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2217
Eric Laurent81784c32012-11-19 14:55:58 -08002218 mTracks.remove(track);
2219 deleteTrackName_l(track->name());
2220 // redundant as track is about to be destroyed, for dumpsys only
2221 track->mName = -1;
2222 if (track->isFastTrack()) {
2223 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002224 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002225 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2226 mFastTrackAvailMask |= 1 << index;
2227 // redundant as track is about to be destroyed, for dumpsys only
2228 track->mFastIndex = -1;
2229 }
2230 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2231 if (chain != 0) {
2232 chain->decTrackCnt();
2233 }
2234}
2235
2236String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2237{
Eric Laurent81784c32012-11-19 14:55:58 -08002238 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002239 String8 out_s8;
2240 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2241 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002242 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002243 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002244}
2245
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002246void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002247 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2248 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002249
Eric Laurent73e26b62015-04-27 16:55:58 -07002250 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002251
2252 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002253 case AUDIO_OUTPUT_OPENED:
2254 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002255 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002256 desc->mChannelMask = mChannelMask;
2257 desc->mSamplingRate = mSampleRate;
2258 desc->mFormat = mFormat;
2259 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002260 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002261 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002262 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002263 break;
2264
Eric Laurent73e26b62015-04-27 16:55:58 -07002265 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002266 default:
2267 break;
2268 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002269 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002270}
2271
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002272void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002274 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002275}
2276
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002277void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002279 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002280}
2281
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002282void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002283{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002284 mCallbackThread->setAsyncError();
2285}
2286
Eric Laurent3b4529e2013-09-05 18:09:19 -07002287void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288{
2289 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002290 // reject out of sequence requests
2291 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2292 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002293 mWaitWorkCV.signal();
2294 }
2295}
2296
Eric Laurent3b4529e2013-09-05 18:09:19 -07002297void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002298{
2299 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002300 // reject out of sequence requests
2301 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2302 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002303 mWaitWorkCV.signal();
2304 }
2305}
2306
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002307void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002308{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002309 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002310 mSampleRate = mOutput->getSampleRate();
2311 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002312 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002313 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002314 }
Andy Hung9a592762014-07-21 21:56:01 -07002315 if ((mType == MIXER || mType == DUPLICATING)
2316 && !isValidPcmSinkChannelMask(mChannelMask)) {
2317 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2318 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002319 }
Andy Hunge5412692014-05-16 11:25:07 -07002320 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002321
2322 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002323 status_t result = mOutput->stream->getFormat(&mHALFormat);
2324 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002325 // Get format from the shim, which will be different than the HAL format
2326 // if playing compressed audio over HDMI passthrough.
2327 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002328 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002329 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002330 }
Andy Hung6146c082014-03-18 11:56:15 -07002331 if ((mType == MIXER || mType == DUPLICATING)
2332 && !isValidPcmSinkFormat(mFormat)) {
2333 LOG_FATAL("HAL format %#x not supported for mixed output",
2334 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002335 }
Phil Burk062e67a2015-02-11 13:40:50 -08002336 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002337 result = mOutput->stream->getBufferSize(&mBufferSize);
2338 LOG_ALWAYS_FATAL_IF(result != OK,
2339 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002340 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002341 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002342 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002343 mFrameCount);
2344 }
2345
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002346 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2347 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002348 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002349 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002350 }
2351 }
2352
Eric Laurentd1f69b02014-12-15 14:33:13 -08002353 mHwSupportsPause = false;
2354 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002355 bool supportsPause = false, supportsResume = false;
2356 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2357 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002358 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002359 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002360 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002361 } else if (supportsResume) {
2362 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002363 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002364 }
2365 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002366 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2367 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2368 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002369
Andy Hungfbfc3952015-01-15 13:33:51 -08002370 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2371 // For best precision, we use float instead of the associated output
2372 // device format (typically PCM 16 bit).
2373
2374 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2375 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2376 mBufferSize = mFrameSize * mFrameCount;
2377
2378 // TODO: We currently use the associated output device channel mask and sample rate.
2379 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2380 // (if a valid mask) to avoid premature downmix.
2381 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2382 // instead of the output device sample rate to avoid loss of high frequency information.
2383 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2384 }
2385
Andy Hung09a50072014-02-27 14:30:47 -08002386 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002387 double multiplier = 1.0;
2388 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2389 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002390 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2391 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002392
Eric Laurent81784c32012-11-19 14:55:58 -08002393 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2394 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2395 maxNormalFrameCount = maxNormalFrameCount & ~15;
2396 if (maxNormalFrameCount < minNormalFrameCount) {
2397 maxNormalFrameCount = minNormalFrameCount;
2398 }
2399 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2400 if (multiplier <= 1.0) {
2401 multiplier = 1.0;
2402 } else if (multiplier <= 2.0) {
2403 if (2 * mFrameCount <= maxNormalFrameCount) {
2404 multiplier = 2.0;
2405 } else {
2406 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2407 }
2408 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002409 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002410 }
2411 }
2412 mNormalFrameCount = multiplier * mFrameCount;
2413 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002414 if (mType == MIXER || mType == DUPLICATING) {
2415 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2416 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002417 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002418 mNormalFrameCount);
2419
Andy Hung08fb1742015-05-31 23:22:10 -07002420 // Check if we want to throttle the processing to no more than 2x normal rate
2421 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002422 mThreadThrottleTimeMs = 0;
2423 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002424 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2425
Andy Hung010a1a12014-03-13 13:57:33 -07002426 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2427 // Originally this was int16_t[] array, need to remove legacy implications.
2428 free(mSinkBuffer);
2429 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002430 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2431 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2432 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002433 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002434
Andy Hung69aed5f2014-02-25 17:24:40 -08002435 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2436 // drives the output.
2437 free(mMixerBuffer);
2438 mMixerBuffer = NULL;
2439 if (mMixerBufferEnabled) {
2440 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2441 mMixerBufferSize = mNormalFrameCount * mChannelCount
2442 * audio_bytes_per_sample(mMixerBufferFormat);
2443 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2444 }
Andy Hung98ef9782014-03-04 14:46:50 -08002445 free(mEffectBuffer);
2446 mEffectBuffer = NULL;
2447 if (mEffectBufferEnabled) {
2448 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2449 mEffectBufferSize = mNormalFrameCount * mChannelCount
2450 * audio_bytes_per_sample(mEffectBufferFormat);
2451 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2452 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002453
Eric Laurent81784c32012-11-19 14:55:58 -08002454 // force reconfiguration of effect chains and engines to take new buffer size and audio
2455 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002456 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002457 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2458 // matter.
2459 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2460 Vector< sp<EffectChain> > effectChains = mEffectChains;
2461 for (size_t i = 0; i < effectChains.size(); i ++) {
2462 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2463 }
2464}
2465
2466
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002467status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002468{
2469 if (halFrames == NULL || dspFrames == NULL) {
2470 return BAD_VALUE;
2471 }
2472 Mutex::Autolock _l(mLock);
2473 if (initCheck() != NO_ERROR) {
2474 return INVALID_OPERATION;
2475 }
Andy Hung818e7a32016-02-16 18:08:07 -08002476 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002477 *halFrames = framesWritten;
2478
2479 if (isSuspended()) {
2480 // return an estimation of rendered frames when the output is suspended
2481 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002482 *dspFrames = (uint32_t)
2483 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002484 return NO_ERROR;
2485 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002486 status_t status;
2487 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002488 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002489 *dspFrames = (size_t)frames;
2490 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002491 }
2492}
2493
Eric Laurent4c415062016-06-17 16:14:16 -07002494// hasAudioSession_l() must be called with ThreadBase::mLock held
2495uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002496{
Eric Laurent81784c32012-11-19 14:55:58 -08002497 uint32_t result = 0;
2498 if (getEffectChain_l(sessionId) != 0) {
2499 result = EFFECT_SESSION;
2500 }
2501
2502 for (size_t i = 0; i < mTracks.size(); ++i) {
2503 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002504 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002505 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002506 if (track->isFastTrack()) {
2507 result |= FAST_SESSION;
2508 }
Eric Laurent81784c32012-11-19 14:55:58 -08002509 break;
2510 }
2511 }
2512
2513 return result;
2514}
2515
Glenn Kastend848eb42016-03-08 13:42:11 -08002516uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002517{
2518 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2519 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2520 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2521 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2522 }
2523 for (size_t i = 0; i < mTracks.size(); i++) {
2524 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002525 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002526 return AudioSystem::getStrategyForStream(track->streamType());
2527 }
2528 }
2529 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2530}
2531
2532
Phil Burk062e67a2015-02-11 13:40:50 -08002533AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002534{
2535 Mutex::Autolock _l(mLock);
2536 return mOutput;
2537}
2538
Phil Burk062e67a2015-02-11 13:40:50 -08002539AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002540{
2541 Mutex::Autolock _l(mLock);
2542 AudioStreamOut *output = mOutput;
2543 mOutput = NULL;
2544 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2545 // must push a NULL and wait for ack
2546 mOutputSink.clear();
2547 mPipeSink.clear();
2548 mNormalSink.clear();
2549 return output;
2550}
2551
2552// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002553sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002554{
2555 if (mOutput == NULL) {
2556 return NULL;
2557 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002558 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002559}
2560
2561uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2562{
2563 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2564}
2565
2566status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2567{
2568 if (!isValidSyncEvent(event)) {
2569 return BAD_VALUE;
2570 }
2571
2572 Mutex::Autolock _l(mLock);
2573
2574 for (size_t i = 0; i < mTracks.size(); ++i) {
2575 sp<Track> track = mTracks[i];
2576 if (event->triggerSession() == track->sessionId()) {
2577 (void) track->setSyncEvent(event);
2578 return NO_ERROR;
2579 }
2580 }
2581
2582 return NAME_NOT_FOUND;
2583}
2584
2585bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2586{
2587 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2588}
2589
2590void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2591 const Vector< sp<Track> >& tracksToRemove)
2592{
2593 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002594 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002595 for (size_t i = 0 ; i < count ; i++) {
2596 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002597 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002598 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002599 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002600#ifdef ADD_BATTERY_DATA
2601 // to track the speaker usage
2602 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2603#endif
2604 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002605 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002606 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002607 }
Eric Laurent81784c32012-11-19 14:55:58 -08002608 }
2609 }
2610 }
Eric Laurent81784c32012-11-19 14:55:58 -08002611}
2612
2613void AudioFlinger::PlaybackThread::checkSilentMode_l()
2614{
2615 if (!mMasterMute) {
2616 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002617 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2618 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2619 return;
2620 }
Eric Laurent81784c32012-11-19 14:55:58 -08002621 if (property_get("ro.audio.silent", value, "0") > 0) {
2622 char *endptr;
2623 unsigned long ul = strtoul(value, &endptr, 0);
2624 if (*endptr == '\0' && ul != 0) {
2625 ALOGD("Silence is golden");
2626 // The setprop command will not allow a property to be changed after
2627 // the first time it is set, so we don't have to worry about un-muting.
2628 setMasterMute_l(true);
2629 }
2630 }
2631 }
2632}
2633
2634// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002635ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002636{
Eric Laurent81784c32012-11-19 14:55:58 -08002637 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002638 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002639 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002640
2641 // If an NBAIO sink is present, use it to write the normal mixer's submix
2642 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002643
Andy Hung010a1a12014-03-13 13:57:33 -07002644 const size_t count = mBytesRemaining / mFrameSize;
2645
Simon Wilson2d590962012-11-29 15:18:50 -08002646 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002647 // update the setpoint when AudioFlinger::mScreenState changes
2648 uint32_t screenState = AudioFlinger::mScreenState;
2649 if (screenState != mScreenState) {
2650 mScreenState = screenState;
2651 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2652 if (pipe != NULL) {
2653 pipe->setAvgFrames((mScreenState & 1) ?
2654 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2655 }
2656 }
Andy Hung010a1a12014-03-13 13:57:33 -07002657 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002658 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002659 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002660 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002661 } else {
2662 bytesWritten = framesWritten;
2663 }
2664 // otherwise use the HAL / AudioStreamOut directly
2665 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002667
Eric Laurentbfb1b832013-01-07 09:53:42 -08002668 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002669 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2670 mWriteAckSequence += 2;
2671 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002672 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002673 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002675 // FIXME We should have an implementation of timestamps for direct output threads.
2676 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002677 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002678
Eric Laurentbfb1b832013-01-07 09:53:42 -08002679 if (mUseAsyncWrite &&
2680 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2681 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002682 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002683 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002684 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002685 }
Eric Laurent81784c32012-11-19 14:55:58 -08002686 }
2687
Eric Laurent81784c32012-11-19 14:55:58 -08002688 mNumWrites++;
2689 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002690 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002691 return bytesWritten;
2692}
2693
2694void AudioFlinger::PlaybackThread::threadLoop_drain()
2695{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002696 bool supportsDrain = false;
2697 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002698 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2699 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002700 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2701 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002702 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002703 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002704 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002705 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002706 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002707 }
2708}
2709
2710void AudioFlinger::PlaybackThread::threadLoop_exit()
2711{
Eric Laurent275e8e92014-11-30 15:14:47 -08002712 {
2713 Mutex::Autolock _l(mLock);
2714 for (size_t i = 0; i < mTracks.size(); i++) {
2715 sp<Track> track = mTracks[i];
2716 track->invalidate();
2717 }
Andy Hungdae27702016-10-31 14:01:16 -07002718 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2719 // After we exit there are no more track changes sent to BatteryNotifier
2720 // because that requires an active threadLoop.
2721 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2722 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002723 }
Eric Laurent81784c32012-11-19 14:55:58 -08002724}
2725
2726/*
2727The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002728 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002729 - mActiveSleepTimeUs from activeSleepTimeUs()
2730 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002731 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2732 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002733 - maxPeriod from frame count and sample rate (MIXER only)
2734
2735The parameters that affect these derived values are:
2736 - frame count
2737 - frame size
2738 - sample rate
2739 - device type: A2DP or not
2740 - device latency
2741 - format: PCM or not
2742 - active sleep time
2743 - idle sleep time
2744*/
2745
2746void AudioFlinger::PlaybackThread::cacheParameters_l()
2747{
Andy Hung25c2dac2014-02-27 14:56:00 -08002748 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002749 mActiveSleepTimeUs = activeSleepTimeUs();
2750 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002751
2752 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2753 // truncating audio when going to standby.
2754 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2755 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2756 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2757 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2758 }
2759 }
Eric Laurent81784c32012-11-19 14:55:58 -08002760}
2761
Eric Laurent13084622016-05-17 10:51:49 -07002762bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002763{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002764 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002765 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002766 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002767 size_t size = mTracks.size();
2768 for (size_t i = 0; i < size; i++) {
2769 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002770 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002771 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002772 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002773 }
2774 }
Eric Laurent13084622016-05-17 10:51:49 -07002775 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002776}
2777
Haynes Mathew George05317d22016-05-03 16:34:26 -07002778void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2779{
2780 Mutex::Autolock _l(mLock);
2781 invalidateTracks_l(streamType);
2782}
2783
Eric Laurent81784c32012-11-19 14:55:58 -08002784status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2785{
Glenn Kastend848eb42016-03-08 13:42:11 -08002786 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002787 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2788 status_t result = EffectBufferHalInterface::mirror(
2789 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2790 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2791 &halInBuffer);
2792 if (result != OK) return result;
2793 halOutBuffer = halInBuffer;
2794 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002795
2796 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002797 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002798 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002799 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002800 if (mType != DIRECT) {
2801 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002802 status_t result = EffectBufferHalInterface::allocate(
2803 numSamples * sizeof(int16_t),
2804 &halInBuffer);
2805 if (result != OK) return result;
2806 buffer = halInBuffer->audioBuffer()->s16;
2807 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2808 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002809 }
2810
2811 // Attach all tracks with same session ID to this chain.
2812 for (size_t i = 0; i < mTracks.size(); ++i) {
2813 sp<Track> track = mTracks[i];
2814 if (session == track->sessionId()) {
2815 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2816 buffer);
2817 track->setMainBuffer(buffer);
2818 chain->incTrackCnt();
2819 }
2820 }
2821
2822 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002823 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002824 if (session == track->sessionId()) {
2825 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2826 chain->incActiveTrackCnt();
2827 }
2828 }
2829 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002830 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002831 chain->setInBuffer(halInBuffer);
2832 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002833 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002834 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002835 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2836 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002837 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002838 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002839 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002840 // Effect chain for other sessions are inserted at beginning of effect
2841 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002842 // sessions is not important.
2843 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2844 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2845 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002846 size_t size = mEffectChains.size();
2847 size_t i = 0;
2848 for (i = 0; i < size; i++) {
2849 if (mEffectChains[i]->sessionId() < session) {
2850 break;
2851 }
2852 }
2853 mEffectChains.insertAt(chain, i);
2854 checkSuspendOnAddEffectChain_l(chain);
2855
2856 return NO_ERROR;
2857}
2858
2859size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2860{
Glenn Kastend848eb42016-03-08 13:42:11 -08002861 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002862
2863 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2864
2865 for (size_t i = 0; i < mEffectChains.size(); i++) {
2866 if (chain == mEffectChains[i]) {
2867 mEffectChains.removeAt(i);
2868 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002869 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002870 if (session == track->sessionId()) {
2871 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2872 chain.get(), session);
2873 chain->decActiveTrackCnt();
2874 }
2875 }
2876
2877 // detach all tracks with same session ID from this chain
2878 for (size_t i = 0; i < mTracks.size(); ++i) {
2879 sp<Track> track = mTracks[i];
2880 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002881 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002882 chain->decTrackCnt();
2883 }
2884 }
2885 break;
2886 }
2887 }
2888 return mEffectChains.size();
2889}
2890
2891status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002892 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002893{
2894 Mutex::Autolock _l(mLock);
2895 return attachAuxEffect_l(track, EffectId);
2896}
2897
2898status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002899 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002900{
2901 status_t status = NO_ERROR;
2902
2903 if (EffectId == 0) {
2904 track->setAuxBuffer(0, NULL);
2905 } else {
2906 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2907 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2908 if (effect != 0) {
2909 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2910 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2911 } else {
2912 status = INVALID_OPERATION;
2913 }
2914 } else {
2915 status = BAD_VALUE;
2916 }
2917 }
2918 return status;
2919}
2920
2921void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2922{
2923 for (size_t i = 0; i < mTracks.size(); ++i) {
2924 sp<Track> track = mTracks[i];
2925 if (track->auxEffectId() == effectId) {
2926 attachAuxEffect_l(track, 0);
2927 }
2928 }
2929}
2930
2931bool AudioFlinger::PlaybackThread::threadLoop()
2932{
Glenn Kasten388d5712017-04-07 14:38:41 -07002933 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002934
Eric Laurent81784c32012-11-19 14:55:58 -08002935 Vector< sp<Track> > tracksToRemove;
2936
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002937 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002938 nsecs_t lastWriteFinished = -1; // time last server write completed
2939 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002940
2941 // MIXER
2942 nsecs_t lastWarning = 0;
2943
2944 // DUPLICATING
2945 // FIXME could this be made local to while loop?
2946 writeFrames = 0;
2947
2948 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002949 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002950
2951 if (mType == MIXER) {
2952 sleepTimeShift = 0;
2953 }
2954
2955 CpuStats cpuStats;
2956 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2957
2958 acquireWakeLock();
2959
Glenn Kasteneef598c2017-04-03 14:41:13 -07002960 // mNBLogWriter logging APIs can only be called by a single thread, typically the
2961 // thread associated with this PlaybackThread.
2962 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
2963 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002964 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2965 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07002966 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002967 const char *logString = NULL;
2968
Eric Laurent664539d2013-09-23 18:24:31 -07002969 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07002970
Eric Laurent81784c32012-11-19 14:55:58 -08002971 while (!exitPending())
2972 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002973 // Log merge requests are performed during AudioFlinger binder transactions, but
2974 // that does not cover audio playback. It's requested here for that reason.
2975 mAudioFlinger->requestLogMerge();
2976
Eric Laurent81784c32012-11-19 14:55:58 -08002977 cpuStats.sample(myName);
2978
2979 Vector< sp<EffectChain> > effectChains;
2980
Eric Laurent81784c32012-11-19 14:55:58 -08002981 { // scope for mLock
2982
2983 Mutex::Autolock _l(mLock);
2984
Eric Laurent021cf962014-05-13 10:18:14 -07002985 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002986
Glenn Kasteneef598c2017-04-03 14:41:13 -07002987 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08002988 if (logString != NULL) {
2989 mNBLogWriter->logTimestamp();
2990 mNBLogWriter->log(logString);
2991 logString = NULL;
2992 }
2993
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002994 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002995 // and associate with the sink frames written out. We need
2996 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002997 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002998 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002999 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003000 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003001 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003002 ExtendedTimestamp timestamp; // use private copy to fetch
3003 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003004
3005 // We keep track of the last valid kernel position in case we are in underrun
3006 // and the normal mixer period is the same as the fast mixer period, or there
3007 // is some error from the HAL.
3008 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3009 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3010 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3011 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3012 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3013
3014 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3015 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3016 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3017 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003018 }
3019
3020 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3021 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003022 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003023 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003024 }
3025
Andy Hung818e7a32016-02-16 18:08:07 -08003026 // copy over kernel info
3027 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003028 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3029 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003030 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3031 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003032 }
3033 // mFramesWritten for non-offloaded tracks are contiguous
3034 // even after standby() is called. This is useful for the track frame
3035 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003036 bool serverLocationUpdate = false;
3037 if (mFramesWritten != lastFramesWritten) {
3038 serverLocationUpdate = true;
3039 lastFramesWritten = mFramesWritten;
3040 }
3041 // Only update timestamps if there is a meaningful change.
3042 // Either the kernel timestamp must be valid or we have written something.
3043 if (kernelLocationUpdate || serverLocationUpdate) {
3044 if (serverLocationUpdate) {
3045 // use the time before we called the HAL write - it is a bit more accurate
3046 // to when the server last read data than the current time here.
3047 //
3048 // If we haven't written anything, mLastWriteTime will be -1
3049 // and we use systemTime().
3050 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3051 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3052 ? systemTime() : mLastWriteTime;
3053 }
Andy Hungdae27702016-10-31 14:01:16 -07003054
3055 for (const sp<Track> &t : mActiveTracks) {
3056 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003057 t->updateTrackFrameInfo(
3058 t->mAudioTrackServerProxy->framesReleased(),
3059 mFramesWritten,
3060 mTimestamp);
3061 }
Andy Hunge10393e2015-06-12 13:59:33 -07003062 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003063 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003064#if 0
3065 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003066 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003067 timespec ts;
3068 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003069 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003070 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003071 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003072 }
3073 ++z;
3074#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003075 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003076 if (mSignalPending) {
3077 // A signal was raised while we were unlocked
3078 mSignalPending = false;
3079 } else if (waitingAsyncCallback_l()) {
3080 if (exitPending()) {
3081 break;
3082 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003083 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003084 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003085 releaseWakeLock_l();
3086 released = true;
3087 }
Andy Hung10cbff12017-02-21 17:30:14 -08003088
3089 const int64_t waitNs = computeWaitTimeNs_l();
3090 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3091 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3092 if (status == TIMED_OUT) {
3093 mSignalPending = true; // if timeout recheck everything
3094 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003095 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003096 if (released) {
3097 acquireWakeLock_l();
3098 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003099 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3100 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003101
3102 continue;
3103 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003104 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105 isSuspended()) {
3106 // put audio hardware into standby after short delay
3107 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003108
3109 threadLoop_standby();
3110
3111 mStandby = true;
3112 }
3113
3114 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3115 // we're about to wait, flush the binder command buffer
3116 IPCThreadState::self()->flushCommands();
3117
3118 clearOutputTracks();
3119
3120 if (exitPending()) {
3121 break;
3122 }
3123
3124 releaseWakeLock_l();
3125 // wait until we have something to do...
3126 ALOGV("%s going to sleep", myName.string());
3127 mWaitWorkCV.wait(mLock);
3128 ALOGV("%s waking up", myName.string());
3129 acquireWakeLock_l();
3130
3131 mMixerStatus = MIXER_IDLE;
3132 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3133 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003135 checkSilentMode_l();
3136
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003137 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3138 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003139 if (mType == MIXER) {
3140 sleepTimeShift = 0;
3141 }
3142
3143 continue;
3144 }
3145 }
Eric Laurent81784c32012-11-19 14:55:58 -08003146 // mMixerStatusIgnoringFastTracks is also updated internally
3147 mMixerStatus = prepareTracks_l(&tracksToRemove);
3148
Andy Hungdae27702016-10-31 14:01:16 -07003149 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003150
Eric Laurent81784c32012-11-19 14:55:58 -08003151 // prevent any changes in effect chain list and in each effect chain
3152 // during mixing and effect process as the audio buffers could be deleted
3153 // or modified if an effect is created or deleted
3154 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003155 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003156
Eric Laurentbfb1b832013-01-07 09:53:42 -08003157 if (mBytesRemaining == 0) {
3158 mCurrentWriteLength = 0;
3159 if (mMixerStatus == MIXER_TRACKS_READY) {
3160 // threadLoop_mix() sets mCurrentWriteLength
3161 threadLoop_mix();
3162 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3163 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003164 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003165 // must be written to HAL
3166 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003167 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003168 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169 }
3170 }
Andy Hung98ef9782014-03-04 14:46:50 -08003171 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003172 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003173 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3174 // or mSinkBuffer (if there are no effects).
3175 //
3176 // This is done pre-effects computation; if effects change to
3177 // support higher precision, this needs to move.
3178 //
3179 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003180 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003181 if (mMixerBufferValid) {
3182 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3183 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3184
Andy Hung2ddee192015-12-18 17:34:44 -08003185 // mono blend occurs for mixer threads only (not direct or offloaded)
3186 // and is handled here if we're going directly to the sink.
3187 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003188 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3189 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003190 }
3191
Andy Hung98ef9782014-03-04 14:46:50 -08003192 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3193 mNormalFrameCount * mChannelCount);
3194 }
3195
Eric Laurentbfb1b832013-01-07 09:53:42 -08003196 mBytesRemaining = mCurrentWriteLength;
3197 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003198 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3199 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3200 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3201 mBytesWritten += mBytesRemaining;
3202 mFramesWritten += framesRemaining;
3203 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003204 mBytesRemaining = 0;
3205 }
Eric Laurent81784c32012-11-19 14:55:58 -08003206
Eric Laurentbfb1b832013-01-07 09:53:42 -08003207 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003208 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003209 for (size_t i = 0; i < effectChains.size(); i ++) {
3210 effectChains[i]->process_l();
3211 }
Eric Laurent81784c32012-11-19 14:55:58 -08003212 }
3213 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003214 // Process effect chains for offloaded thread even if no audio
3215 // was read from audio track: process only updates effect state
3216 // and thus does have to be synchronized with audio writes but may have
3217 // to be called while waiting for async write callback
3218 if (mType == OFFLOAD) {
3219 for (size_t i = 0; i < effectChains.size(); i ++) {
3220 effectChains[i]->process_l();
3221 }
3222 }
Eric Laurent81784c32012-11-19 14:55:58 -08003223
Andy Hung98ef9782014-03-04 14:46:50 -08003224 // Only if the Effects buffer is enabled and there is data in the
3225 // Effects buffer (buffer valid), we need to
3226 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003227 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003228 if (mEffectBufferValid) {
3229 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003230
3231 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003232 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3233 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003234 }
3235
Andy Hung98ef9782014-03-04 14:46:50 -08003236 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3237 mNormalFrameCount * mChannelCount);
3238 }
3239
Eric Laurent81784c32012-11-19 14:55:58 -08003240 // enable changes in effect chain
3241 unlockEffectChains(effectChains);
3242
Eric Laurentbfb1b832013-01-07 09:53:42 -08003243 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003244 // mSleepTimeUs == 0 means we must write to audio hardware
3245 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003246 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003247 // We save lastWriteFinished here, as previousLastWriteFinished,
3248 // for throttling. On thread start, previousLastWriteFinished will be
3249 // set to -1, which properly results in no throttling after the first write.
3250 nsecs_t previousLastWriteFinished = lastWriteFinished;
3251 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003252 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003253 // FIXME rewrite to reduce number of system calls
3254 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003255 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003256 lastWriteFinished = systemTime();
3257 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003258 if (ret < 0) {
3259 mBytesRemaining = 0;
3260 } else {
3261 mBytesWritten += ret;
3262 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003263 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003264 }
3265 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3266 (mMixerStatus == MIXER_DRAIN_ALL)) {
3267 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003268 }
Andy Hung08fb1742015-05-31 23:22:10 -07003269 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003270 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003271 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003272 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003273 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003274 ATRACE_NAME("underrun");
3275 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003276 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003277 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003278 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003279 }
Andy Hung08fb1742015-05-31 23:22:10 -07003280
3281 if (mThreadThrottle
3282 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3283 && ret > 0) { // we wrote something
3284 // Limit MixerThread data processing to no more than twice the
3285 // expected processing rate.
3286 //
3287 // This helps prevent underruns with NuPlayer and other applications
3288 // which may set up buffers that are close to the minimum size, or use
3289 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3290 //
3291 // The throttle smooths out sudden large data drains from the device,
3292 // e.g. when it comes out of standby, which often causes problems with
3293 // (1) mixer threads without a fast mixer (which has its own warm-up)
3294 // (2) minimum buffer sized tracks (even if the track is full,
3295 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003296 //
3297 // Total time spent in last processing cycle equals time spent in
3298 // 1. threadLoop_write, as well as time spent in
3299 // 2. threadLoop_mix (significant for heavy mixing, especially
3300 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003301
Andy Hung69488c42016-05-16 18:43:33 -07003302 // it's OK if deltaMs is an overestimate.
3303 const int32_t deltaMs =
3304 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003305 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3306 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3307 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003308 // notify of throttle start on verbose log
3309 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3310 "mixer(%p) throttle begin:"
3311 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003312 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003313 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003314 // Throttle must be attributed to the previous mixer loop's write time
3315 // to allow back-to-back throttling.
3316 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003317 } else {
3318 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3319 if (diff > 0) {
3320 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003321 // but prevent spamming for bluetooth
3322 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3323 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003324 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3325 }
Andy Hung08fb1742015-05-31 23:22:10 -07003326 }
3327 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003328 }
Eric Laurent81784c32012-11-19 14:55:58 -08003329
Eric Laurentbfb1b832013-01-07 09:53:42 -08003330 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003331 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003332 Mutex::Autolock _l(mLock);
3333 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3334 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003335 }
Glenn Kastene7754022014-10-31 12:11:26 -07003336 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003337 }
Eric Laurent81784c32012-11-19 14:55:58 -08003338 }
3339
3340 // Finally let go of removed track(s), without the lock held
3341 // since we can't guarantee the destructors won't acquire that
3342 // same lock. This will also mutate and push a new fast mixer state.
3343 threadLoop_removeTracks(tracksToRemove);
3344 tracksToRemove.clear();
3345
3346 // FIXME I don't understand the need for this here;
3347 // it was in the original code but maybe the
3348 // assignment in saveOutputTracks() makes this unnecessary?
3349 clearOutputTracks();
3350
3351 // Effect chains will be actually deleted here if they were removed from
3352 // mEffectChains list during mixing or effects processing
3353 effectChains.clear();
3354
3355 // FIXME Note that the above .clear() is no longer necessary since effectChains
3356 // is now local to this block, but will keep it for now (at least until merge done).
3357 }
3358
Eric Laurentbfb1b832013-01-07 09:53:42 -08003359 threadLoop_exit();
3360
Eric Laurentcf817a22014-08-04 20:36:31 -07003361 if (!mStandby) {
3362 threadLoop_standby();
3363 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003364 }
3365
3366 releaseWakeLock();
3367
3368 ALOGV("Thread %p type %d exiting", this, mType);
3369 return false;
3370}
3371
Eric Laurentbfb1b832013-01-07 09:53:42 -08003372// removeTracks_l() must be called with ThreadBase::mLock held
3373void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3374{
3375 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003376 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003377 for (size_t i=0 ; i<count ; i++) {
3378 const sp<Track>& track = tracksToRemove.itemAt(i);
3379 mActiveTracks.remove(track);
3380 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3381 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3382 if (chain != 0) {
3383 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3384 track->sessionId());
3385 chain->decActiveTrackCnt();
3386 }
3387 if (track->isTerminated()) {
3388 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003389 } else { // inactive but not terminated
3390 char buffer[256];
3391 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3392 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003393 }
3394 }
3395 }
3396
3397}
Eric Laurent81784c32012-11-19 14:55:58 -08003398
Eric Laurentaccc1472013-09-20 09:36:34 -07003399status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3400{
3401 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003402 ExtendedTimestamp ets;
3403 status_t status = mNormalSink->getTimestamp(ets);
3404 if (status == NO_ERROR) {
3405 status = ets.getBestTimestamp(&timestamp);
3406 }
3407 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003408 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003409 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003410 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003411 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003412 timestamp.mPosition = (uint32_t)position64;
3413 return NO_ERROR;
3414 }
3415 }
3416 return INVALID_OPERATION;
3417}
Eric Laurent1c333e22014-05-20 10:48:17 -07003418
Eric Laurent054d9d32015-04-24 08:48:48 -07003419status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3420 audio_patch_handle_t *handle)
3421{
Andy Hungf60abce2016-08-26 11:37:54 -07003422 status_t status;
3423 if (property_get_bool("af.patch_park", false /* default_value */)) {
3424 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3425 // or if HAL does not properly lock against access.
3426 AutoPark<FastMixer> park(mFastMixer);
3427 status = PlaybackThread::createAudioPatch_l(patch, handle);
3428 } else {
3429 status = PlaybackThread::createAudioPatch_l(patch, handle);
3430 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003431 return status;
3432}
3433
Eric Laurent1c333e22014-05-20 10:48:17 -07003434status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3435 audio_patch_handle_t *handle)
3436{
3437 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003438
3439 // store new device and send to effects
3440 audio_devices_t type = AUDIO_DEVICE_NONE;
3441 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3442 type |= patch->sinks[i].ext.device.type;
3443 }
3444
3445#ifdef ADD_BATTERY_DATA
3446 // when changing the audio output device, call addBatteryData to notify
3447 // the change
3448 if (mOutDevice != type) {
3449 uint32_t params = 0;
3450 // check whether speaker is on
3451 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3452 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003453 }
3454
Eric Laurent054d9d32015-04-24 08:48:48 -07003455 audio_devices_t deviceWithoutSpeaker
3456 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3457 // check if any other device (except speaker) is on
3458 if (type & deviceWithoutSpeaker) {
3459 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3460 }
3461
3462 if (params != 0) {
3463 addBatteryData(params);
3464 }
3465 }
3466#endif
3467
3468 for (size_t i = 0; i < mEffectChains.size(); i++) {
3469 mEffectChains[i]->setDevice_l(type);
3470 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003471
3472 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3473 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3474 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003475 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003476 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003477
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003478 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003479 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3480 status = hwDevice->createAudioPatch(patch->num_sources,
3481 patch->sources,
3482 patch->num_sinks,
3483 patch->sinks,
3484 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003485 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003486 char *address;
3487 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3488 //FIXME: we only support address on first sink with HAL version < 3.0
3489 address = audio_device_address_to_parameter(
3490 patch->sinks[0].ext.device.type,
3491 patch->sinks[0].ext.device.address);
3492 } else {
3493 address = (char *)calloc(1, 1);
3494 }
3495 AudioParameter param = AudioParameter(String8(address));
3496 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003497 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003498 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003499 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003500 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003501 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003502 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003503 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3504 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003505 return status;
3506}
3507
Eric Laurent054d9d32015-04-24 08:48:48 -07003508status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3509{
Andy Hungf60abce2016-08-26 11:37:54 -07003510 status_t status;
3511 if (property_get_bool("af.patch_park", false /* default_value */)) {
3512 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3513 // or if HAL does not properly lock against access.
3514 AutoPark<FastMixer> park(mFastMixer);
3515 status = PlaybackThread::releaseAudioPatch_l(handle);
3516 } else {
3517 status = PlaybackThread::releaseAudioPatch_l(handle);
3518 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003519 return status;
3520}
3521
Eric Laurent1c333e22014-05-20 10:48:17 -07003522status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3523{
3524 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003525
3526 mOutDevice = AUDIO_DEVICE_NONE;
3527
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003528 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003529 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3530 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003531 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003532 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003533 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003534 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003535 }
3536 return status;
3537}
3538
Eric Laurent83b88082014-06-20 18:31:16 -07003539void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3540{
3541 Mutex::Autolock _l(mLock);
3542 mTracks.add(track);
3543}
3544
3545void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3546{
3547 Mutex::Autolock _l(mLock);
3548 destroyTrack_l(track);
3549}
3550
3551void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3552{
3553 ThreadBase::getAudioPortConfig(config);
3554 config->role = AUDIO_PORT_ROLE_SOURCE;
3555 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3556 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3557}
3558
Eric Laurent81784c32012-11-19 14:55:58 -08003559// ----------------------------------------------------------------------------
3560
3561AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003562 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3563 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003564 // mAudioMixer below
3565 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003566 mFastMixerFutex(0),
3567 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003568 // mOutputSink below
3569 // mPipeSink below
3570 // mNormalSink below
3571{
3572 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003573 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3574 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003575 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3576 mNormalFrameCount);
3577 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3578
Andy Hungfbfc3952015-01-15 13:33:51 -08003579 if (type == DUPLICATING) {
3580 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3581 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3582 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3583 return;
3584 }
Eric Laurent81784c32012-11-19 14:55:58 -08003585 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003586 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003587 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003588 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003589#if !LOG_NDEBUG
3590 ssize_t index =
3591#else
3592 (void)
3593#endif
3594 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003595 ALOG_ASSERT(index == 0);
3596
3597 // initialize fast mixer depending on configuration
3598 bool initFastMixer;
3599 switch (kUseFastMixer) {
3600 case FastMixer_Never:
3601 initFastMixer = false;
3602 break;
3603 case FastMixer_Always:
3604 initFastMixer = true;
3605 break;
3606 case FastMixer_Static:
3607 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003608 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3609 // where the period is less than an experimentally determined threshold that can be
3610 // scheduled reliably with CFS. However, the BT A2DP HAL is
3611 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3612 initFastMixer = mFrameCount < mNormalFrameCount
3613 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003614 break;
3615 }
Andy Hungfda69402017-02-15 14:33:12 -08003616 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3617 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3618 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003619 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003620 audio_format_t fastMixerFormat;
3621 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3622 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3623 } else {
3624 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3625 }
3626 if (mFormat != fastMixerFormat) {
3627 // change our Sink format to accept our intermediate precision
3628 mFormat = fastMixerFormat;
3629 free(mSinkBuffer);
3630 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3631 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3632 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3633 }
Eric Laurent81784c32012-11-19 14:55:58 -08003634
3635 // create a MonoPipe to connect our submix to FastMixer
3636 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003637#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003638 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003639#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003640 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003641 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003642 format.mFormat = fastMixerFormat;
3643 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3644
Eric Laurent81784c32012-11-19 14:55:58 -08003645 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3646 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3647 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3648 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3649 const NBAIO_Format offers[1] = {format};
3650 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003651#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003652 ssize_t index =
3653#else
3654 (void)
3655#endif
3656 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003657 ALOG_ASSERT(index == 0);
3658 monoPipe->setAvgFrames((mScreenState & 1) ?
3659 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3660 mPipeSink = monoPipe;
3661
Glenn Kasten46909e72013-02-26 09:20:22 -08003662#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003663 if (mTeeSinkOutputEnabled) {
3664 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003665 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3666 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003667 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003668 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003669 ALOG_ASSERT(index == 0);
3670 mTeeSink = teeSink;
3671 PipeReader *teeSource = new PipeReader(*teeSink);
3672 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003673 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003674 ALOG_ASSERT(index == 0);
3675 mTeeSource = teeSource;
3676 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003677#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003678
3679 // create fast mixer and configure it initially with just one fast track for our submix
3680 mFastMixer = new FastMixer();
3681 FastMixerStateQueue *sq = mFastMixer->sq();
3682#ifdef STATE_QUEUE_DUMP
3683 sq->setObserverDump(&mStateQueueObserverDump);
3684 sq->setMutatorDump(&mStateQueueMutatorDump);
3685#endif
3686 FastMixerState *state = sq->begin();
3687 FastTrack *fastTrack = &state->mFastTracks[0];
3688 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3689 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3690 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003691 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3692 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003693 fastTrack->mGeneration++;
3694 state->mFastTracksGen++;
3695 state->mTrackMask = 1;
3696 // fast mixer will use the HAL output sink
3697 state->mOutputSink = mOutputSink.get();
3698 state->mOutputSinkGen++;
3699 state->mFrameCount = mFrameCount;
3700 state->mCommand = FastMixerState::COLD_IDLE;
3701 // already done in constructor initialization list
3702 //mFastMixerFutex = 0;
3703 state->mColdFutexAddr = &mFastMixerFutex;
3704 state->mColdGen++;
3705 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003706#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003707 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003708#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003709 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3710 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003711 sq->end();
3712 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3713
3714 // start the fast mixer
3715 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3716 pid_t tid = mFastMixer->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08003717 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003718 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003719
3720#ifdef AUDIO_WATCHDOG
3721 // create and start the watchdog
3722 mAudioWatchdog = new AudioWatchdog();
3723 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3724 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3725 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003726 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003727#endif
3728
Eric Laurent81784c32012-11-19 14:55:58 -08003729 }
3730
3731 switch (kUseFastMixer) {
3732 case FastMixer_Never:
3733 case FastMixer_Dynamic:
3734 mNormalSink = mOutputSink;
3735 break;
3736 case FastMixer_Always:
3737 mNormalSink = mPipeSink;
3738 break;
3739 case FastMixer_Static:
3740 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3741 break;
3742 }
3743}
3744
3745AudioFlinger::MixerThread::~MixerThread()
3746{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003747 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003748 FastMixerStateQueue *sq = mFastMixer->sq();
3749 FastMixerState *state = sq->begin();
3750 if (state->mCommand == FastMixerState::COLD_IDLE) {
3751 int32_t old = android_atomic_inc(&mFastMixerFutex);
3752 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003753 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003754 }
3755 }
3756 state->mCommand = FastMixerState::EXIT;
3757 sq->end();
3758 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3759 mFastMixer->join();
3760 // Though the fast mixer thread has exited, it's state queue is still valid.
3761 // We'll use that extract the final state which contains one remaining fast track
3762 // corresponding to our sub-mix.
3763 state = sq->begin();
3764 ALOG_ASSERT(state->mTrackMask == 1);
3765 FastTrack *fastTrack = &state->mFastTracks[0];
3766 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3767 delete fastTrack->mBufferProvider;
3768 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003769 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003770#ifdef AUDIO_WATCHDOG
3771 if (mAudioWatchdog != 0) {
3772 mAudioWatchdog->requestExit();
3773 mAudioWatchdog->requestExitAndWait();
3774 mAudioWatchdog.clear();
3775 }
3776#endif
3777 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003778 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003779 delete mAudioMixer;
3780}
3781
3782
3783uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3784{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003785 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003786 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3787 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3788 }
3789 return latency;
3790}
3791
3792
3793void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3794{
3795 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3796}
3797
Eric Laurentbfb1b832013-01-07 09:53:42 -08003798ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003799{
3800 // FIXME we should only do one push per cycle; confirm this is true
3801 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003802 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003803 FastMixerStateQueue *sq = mFastMixer->sq();
3804 FastMixerState *state = sq->begin();
3805 if (state->mCommand != FastMixerState::MIX_WRITE &&
3806 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3807 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003808
3809 // FIXME workaround for first HAL write being CPU bound on some devices
3810 ATRACE_BEGIN("write");
3811 mOutput->write((char *)mSinkBuffer, 0);
3812 ATRACE_END();
3813
Eric Laurent81784c32012-11-19 14:55:58 -08003814 int32_t old = android_atomic_inc(&mFastMixerFutex);
3815 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003816 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003817 }
3818#ifdef AUDIO_WATCHDOG
3819 if (mAudioWatchdog != 0) {
3820 mAudioWatchdog->resume();
3821 }
3822#endif
3823 }
3824 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003825#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003826 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003827 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003828#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003829 sq->end();
3830 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3831 if (kUseFastMixer == FastMixer_Dynamic) {
3832 mNormalSink = mPipeSink;
3833 }
3834 } else {
3835 sq->end(false /*didModify*/);
3836 }
3837 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003838 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003839}
3840
3841void AudioFlinger::MixerThread::threadLoop_standby()
3842{
3843 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003844 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003845 FastMixerStateQueue *sq = mFastMixer->sq();
3846 FastMixerState *state = sq->begin();
3847 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003848 // Report any frames trapped in the Monopipe
3849 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3850 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3851 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3852 "monoPipeWritten:%lld monoPipeLeft:%lld",
3853 (long long)mFramesWritten, (long long)mSuspendedFrames,
3854 (long long)mPipeSink->framesWritten(), pipeFrames);
3855 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3856
Eric Laurent81784c32012-11-19 14:55:58 -08003857 state->mCommand = FastMixerState::COLD_IDLE;
3858 state->mColdFutexAddr = &mFastMixerFutex;
3859 state->mColdGen++;
3860 mFastMixerFutex = 0;
3861 sq->end();
3862 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3863 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3864 if (kUseFastMixer == FastMixer_Dynamic) {
3865 mNormalSink = mOutputSink;
3866 }
3867#ifdef AUDIO_WATCHDOG
3868 if (mAudioWatchdog != 0) {
3869 mAudioWatchdog->pause();
3870 }
3871#endif
3872 } else {
3873 sq->end(false /*didModify*/);
3874 }
3875 }
3876 PlaybackThread::threadLoop_standby();
3877}
3878
Eric Laurentbfb1b832013-01-07 09:53:42 -08003879bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3880{
3881 return false;
3882}
3883
3884bool AudioFlinger::PlaybackThread::shouldStandby_l()
3885{
3886 return !mStandby;
3887}
3888
3889bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3890{
3891 Mutex::Autolock _l(mLock);
3892 return waitingAsyncCallback_l();
3893}
3894
Eric Laurent81784c32012-11-19 14:55:58 -08003895// shared by MIXER and DIRECT, overridden by DUPLICATING
3896void AudioFlinger::PlaybackThread::threadLoop_standby()
3897{
3898 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003899 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003900 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003901 // discard any pending drain or write ack by incrementing sequence
3902 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3903 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003904 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003905 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3906 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003907 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003908 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003909}
3910
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003911void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3912{
3913 ALOGV("signal playback thread");
3914 broadcast_l();
3915}
3916
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003917void AudioFlinger::PlaybackThread::onAsyncError()
3918{
3919 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3920 invalidateTracks((audio_stream_type_t)i);
3921 }
3922}
3923
Eric Laurent81784c32012-11-19 14:55:58 -08003924void AudioFlinger::MixerThread::threadLoop_mix()
3925{
Eric Laurent81784c32012-11-19 14:55:58 -08003926 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003927 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003928 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003929 // increase sleep time progressively when application underrun condition clears.
3930 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3931 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3932 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003933 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003934 sleepTimeShift--;
3935 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003936 mSleepTimeUs = 0;
3937 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003938 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003939
Eric Laurent81784c32012-11-19 14:55:58 -08003940}
3941
3942void AudioFlinger::MixerThread::threadLoop_sleepTime()
3943{
3944 // If no tracks are ready, sleep once for the duration of an output
3945 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003946 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003947 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003948 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3949 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3950 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003951 }
3952 // reduce sleep time in case of consecutive application underruns to avoid
3953 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3954 // duration we would end up writing less data than needed by the audio HAL if
3955 // the condition persists.
3956 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3957 sleepTimeShift++;
3958 }
3959 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003960 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003961 }
3962 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003963 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3964 // before effects processing or output.
3965 if (mMixerBufferValid) {
3966 memset(mMixerBuffer, 0, mMixerBufferSize);
3967 } else {
3968 memset(mSinkBuffer, 0, mSinkBufferSize);
3969 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003970 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003971 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3972 "anticipated start");
3973 }
3974 // TODO add standby time extension fct of effect tail
3975}
3976
3977// prepareTracks_l() must be called with ThreadBase::mLock held
3978AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3979 Vector< sp<Track> > *tracksToRemove)
3980{
3981
3982 mixer_state mixerStatus = MIXER_IDLE;
3983 // find out which tracks need to be processed
3984 size_t count = mActiveTracks.size();
3985 size_t mixedTracks = 0;
3986 size_t tracksWithEffect = 0;
3987 // counts only _active_ fast tracks
3988 size_t fastTracks = 0;
3989 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3990
3991 float masterVolume = mMasterVolume;
3992 bool masterMute = mMasterMute;
3993
3994 if (masterMute) {
3995 masterVolume = 0;
3996 }
3997 // Delegate master volume control to effect in output mix effect chain if needed
3998 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3999 if (chain != 0) {
4000 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4001 chain->setVolume_l(&v, &v);
4002 masterVolume = (float)((v + (1 << 23)) >> 24);
4003 chain.clear();
4004 }
4005
4006 // prepare a new state to push
4007 FastMixerStateQueue *sq = NULL;
4008 FastMixerState *state = NULL;
4009 bool didModify = false;
4010 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004011 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004012 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004013 sq = mFastMixer->sq();
4014 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004015 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004016 }
4017
Andy Hung69aed5f2014-02-25 17:24:40 -08004018 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004019 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004020
Eric Laurent81784c32012-11-19 14:55:58 -08004021 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004022 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004023
4024 // this const just means the local variable doesn't change
4025 Track* const track = t.get();
4026
4027 // process fast tracks
4028 if (track->isFastTrack()) {
4029
4030 // It's theoretically possible (though unlikely) for a fast track to be created
4031 // and then removed within the same normal mix cycle. This is not a problem, as
4032 // the track never becomes active so it's fast mixer slot is never touched.
4033 // The converse, of removing an (active) track and then creating a new track
4034 // at the identical fast mixer slot within the same normal mix cycle,
4035 // is impossible because the slot isn't marked available until the end of each cycle.
4036 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004037 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004038 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4039 FastTrack *fastTrack = &state->mFastTracks[j];
4040
4041 // Determine whether the track is currently in underrun condition,
4042 // and whether it had a recent underrun.
4043 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4044 FastTrackUnderruns underruns = ftDump->mUnderruns;
4045 uint32_t recentFull = (underruns.mBitFields.mFull -
4046 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4047 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4048 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4049 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4050 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4051 uint32_t recentUnderruns = recentPartial + recentEmpty;
4052 track->mObservedUnderruns = underruns;
4053 // don't count underruns that occur while stopping or pausing
4054 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004055 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4056 recentUnderruns > 0) {
4057 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4058 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004059 } else {
4060 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004061 }
4062
4063 // This is similar to the state machine for normal tracks,
4064 // with a few modifications for fast tracks.
4065 bool isActive = true;
4066 switch (track->mState) {
4067 case TrackBase::STOPPING_1:
4068 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004069 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004070 track->mState = TrackBase::STOPPING_2;
4071 }
4072 break;
4073 case TrackBase::PAUSING:
4074 // ramp down is not yet implemented
4075 track->setPaused();
4076 break;
4077 case TrackBase::RESUMING:
4078 // ramp up is not yet implemented
4079 track->mState = TrackBase::ACTIVE;
4080 break;
4081 case TrackBase::ACTIVE:
4082 if (recentFull > 0 || recentPartial > 0) {
4083 // track has provided at least some frames recently: reset retry count
4084 track->mRetryCount = kMaxTrackRetries;
4085 }
4086 if (recentUnderruns == 0) {
4087 // no recent underruns: stay active
4088 break;
4089 }
4090 // there has recently been an underrun of some kind
4091 if (track->sharedBuffer() == 0) {
4092 // were any of the recent underruns "empty" (no frames available)?
4093 if (recentEmpty == 0) {
4094 // no, then ignore the partial underruns as they are allowed indefinitely
4095 break;
4096 }
4097 // there has recently been an "empty" underrun: decrement the retry counter
4098 if (--(track->mRetryCount) > 0) {
4099 break;
4100 }
4101 // indicate to client process that the track was disabled because of underrun;
4102 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004103 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004104 // remove from active list, but state remains ACTIVE [confusing but true]
4105 isActive = false;
4106 break;
4107 }
4108 // fall through
4109 case TrackBase::STOPPING_2:
4110 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004111 case TrackBase::STOPPED:
4112 case TrackBase::FLUSHED: // flush() while active
4113 // Check for presentation complete if track is inactive
4114 // We have consumed all the buffers of this track.
4115 // This would be incomplete if we auto-paused on underrun
4116 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004117 uint32_t latency = 0;
4118 status_t result = mOutput->stream->getLatency(&latency);
4119 ALOGE_IF(result != OK,
4120 "Error when retrieving output stream latency: %d", result);
4121 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004122 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004123 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4124 // track stays in active list until presentation is complete
4125 break;
4126 }
4127 }
4128 if (track->isStopping_2()) {
4129 track->mState = TrackBase::STOPPED;
4130 }
4131 if (track->isStopped()) {
4132 // Can't reset directly, as fast mixer is still polling this track
4133 // track->reset();
4134 // So instead mark this track as needing to be reset after push with ack
4135 resetMask |= 1 << i;
4136 }
4137 isActive = false;
4138 break;
4139 case TrackBase::IDLE:
4140 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004141 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004142 }
4143
4144 if (isActive) {
4145 // was it previously inactive?
4146 if (!(state->mTrackMask & (1 << j))) {
4147 ExtendedAudioBufferProvider *eabp = track;
4148 VolumeProvider *vp = track;
4149 fastTrack->mBufferProvider = eabp;
4150 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004151 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004152 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004153 fastTrack->mGeneration++;
4154 state->mTrackMask |= 1 << j;
4155 didModify = true;
4156 // no acknowledgement required for newly active tracks
4157 }
4158 // cache the combined master volume and stream type volume for fast mixer; this
4159 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004160 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004161 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004162 track->mCachedVolume = masterVolume
4163 * mStreamTypes[track->streamType()].volume
4164 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004165 ++fastTracks;
4166 } else {
4167 // was it previously active?
4168 if (state->mTrackMask & (1 << j)) {
4169 fastTrack->mBufferProvider = NULL;
4170 fastTrack->mGeneration++;
4171 state->mTrackMask &= ~(1 << j);
4172 didModify = true;
4173 // If any fast tracks were removed, we must wait for acknowledgement
4174 // because we're about to decrement the last sp<> on those tracks.
4175 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4176 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004177 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4178 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4179 j, track->mState, state->mTrackMask, recentUnderruns,
4180 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004181 }
4182 tracksToRemove->add(track);
4183 // Avoids a misleading display in dumpsys
4184 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4185 }
4186 continue;
4187 }
4188
4189 { // local variable scope to avoid goto warning
4190
4191 audio_track_cblk_t* cblk = track->cblk();
4192
4193 // The first time a track is added we wait
4194 // for all its buffers to be filled before processing it
4195 int name = track->name();
4196 // make sure that we have enough frames to mix one full buffer.
4197 // enforce this condition only once to enable draining the buffer in case the client
4198 // app does not call stop() and relies on underrun to stop:
4199 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4200 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004201 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004202 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004203 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004204
4205 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004206 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004207 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4208 // add frames already consumed but not yet released by the resampler
4209 // because mAudioTrackServerProxy->framesReady() will include these frames
4210 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4211
Eric Laurent81784c32012-11-19 14:55:58 -08004212 uint32_t minFrames = 1;
4213 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4214 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004215 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004216 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004217
4218 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004219 if (ATRACE_ENABLED()) {
4220 // I wish we had formatted trace names
4221 char traceName[16];
4222 strcpy(traceName, "nRdy");
4223 int name = track->name();
4224 if (AudioMixer::TRACK0 <= name &&
4225 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4226 name -= AudioMixer::TRACK0;
4227 traceName[4] = (name / 10) + '0';
4228 traceName[5] = (name % 10) + '0';
4229 } else {
4230 traceName[4] = '?';
4231 traceName[5] = '?';
4232 }
4233 traceName[6] = '\0';
4234 ATRACE_INT(traceName, framesReady);
4235 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004236 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004237 !track->isPaused() && !track->isTerminated())
4238 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004239 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004240
4241 mixedTracks++;
4242
Andy Hung69aed5f2014-02-25 17:24:40 -08004243 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4244 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004245 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004246 if (track->mainBuffer() != mSinkBuffer &&
4247 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004248 if (mEffectBufferEnabled) {
4249 mEffectBufferValid = true; // Later can set directly.
4250 }
Eric Laurent81784c32012-11-19 14:55:58 -08004251 chain = getEffectChain_l(track->sessionId());
4252 // Delegate volume control to effect in track effect chain if needed
4253 if (chain != 0) {
4254 tracksWithEffect++;
4255 } else {
4256 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4257 "session %d",
4258 name, track->sessionId());
4259 }
4260 }
4261
4262
4263 int param = AudioMixer::VOLUME;
4264 if (track->mFillingUpStatus == Track::FS_FILLED) {
4265 // no ramp for the first volume setting
4266 track->mFillingUpStatus = Track::FS_ACTIVE;
4267 if (track->mState == TrackBase::RESUMING) {
4268 track->mState = TrackBase::ACTIVE;
4269 param = AudioMixer::RAMP_VOLUME;
4270 }
4271 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004272 // FIXME should not make a decision based on mServer
4273 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004274 // If the track is stopped before the first frame was mixed,
4275 // do not apply ramp
4276 param = AudioMixer::RAMP_VOLUME;
4277 }
4278
4279 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004280 uint32_t vl, vr; // in U8.24 integer format
4281 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004282 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004283 vl = vr = 0;
4284 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004285 if (track->isPausing()) {
4286 track->setPaused();
4287 }
4288 } else {
4289
4290 // read original volumes with volume control
4291 float typeVolume = mStreamTypes[track->streamType()].volume;
4292 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004293 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004294 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004295 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4296 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004297 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004298 if (vlf > GAIN_FLOAT_UNITY) {
4299 ALOGV("Track left volume out of range: %.3g", vlf);
4300 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004301 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004302 if (vrf > GAIN_FLOAT_UNITY) {
4303 ALOGV("Track right volume out of range: %.3g", vrf);
4304 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004305 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004306 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004307 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004308 // now apply the master volume and stream type volume and shaper volume
4309 vlf *= v * vh;
4310 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004311 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004312 // then derive vl and vr as U8.24 versions for the effect chain
4313 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4314 vl = (uint32_t) (scaleto8_24 * vlf);
4315 vr = (uint32_t) (scaleto8_24 * vrf);
4316 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004317 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004318 // send level comes from shared memory and so may be corrupt
4319 if (sendLevel > MAX_GAIN_INT) {
4320 ALOGV("Track send level out of range: %04X", sendLevel);
4321 sendLevel = MAX_GAIN_INT;
4322 }
Andy Hung6be49402014-05-30 10:42:03 -07004323 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4324 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004325 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004326
Eric Laurent81784c32012-11-19 14:55:58 -08004327 // Delegate volume control to effect in track effect chain if needed
4328 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4329 // Do not ramp volume if volume is controlled by effect
4330 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004331 // Update remaining floating point volume levels
4332 vlf = (float)vl / (1 << 24);
4333 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004334 track->mHasVolumeController = true;
4335 } else {
4336 // force no volume ramp when volume controller was just disabled or removed
4337 // from effect chain to avoid volume spike
4338 if (track->mHasVolumeController) {
4339 param = AudioMixer::VOLUME;
4340 }
4341 track->mHasVolumeController = false;
4342 }
4343
Eric Laurent81784c32012-11-19 14:55:58 -08004344 // XXX: these things DON'T need to be done each time
4345 mAudioMixer->setBufferProvider(name, track);
4346 mAudioMixer->enable(name);
4347
Andy Hung6be49402014-05-30 10:42:03 -07004348 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4349 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4350 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004351 mAudioMixer->setParameter(
4352 name,
4353 AudioMixer::TRACK,
4354 AudioMixer::FORMAT, (void *)track->format());
4355 mAudioMixer->setParameter(
4356 name,
4357 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004358 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004359 mAudioMixer->setParameter(
4360 name,
4361 AudioMixer::TRACK,
4362 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004363 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004364 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004365 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004366 if (reqSampleRate == 0) {
4367 reqSampleRate = mSampleRate;
4368 } else if (reqSampleRate > maxSampleRate) {
4369 reqSampleRate = maxSampleRate;
4370 }
Eric Laurent81784c32012-11-19 14:55:58 -08004371 mAudioMixer->setParameter(
4372 name,
4373 AudioMixer::RESAMPLE,
4374 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004375 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004376
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004377 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004378 mAudioMixer->setParameter(
4379 name,
4380 AudioMixer::TIMESTRETCH,
4381 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004382 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004383
Andy Hung69aed5f2014-02-25 17:24:40 -08004384 /*
4385 * Select the appropriate output buffer for the track.
4386 *
Andy Hung98ef9782014-03-04 14:46:50 -08004387 * Tracks with effects go into their own effects chain buffer
4388 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004389 *
4390 * Other tracks can use mMixerBuffer for higher precision
4391 * channel accumulation. If this buffer is enabled
4392 * (mMixerBufferEnabled true), then selected tracks will accumulate
4393 * into it.
4394 *
4395 */
4396 if (mMixerBufferEnabled
4397 && (track->mainBuffer() == mSinkBuffer
4398 || track->mainBuffer() == mMixerBuffer)) {
4399 mAudioMixer->setParameter(
4400 name,
4401 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004402 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004403 mAudioMixer->setParameter(
4404 name,
4405 AudioMixer::TRACK,
4406 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4407 // TODO: override track->mainBuffer()?
4408 mMixerBufferValid = true;
4409 } else {
4410 mAudioMixer->setParameter(
4411 name,
4412 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004413 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004414 mAudioMixer->setParameter(
4415 name,
4416 AudioMixer::TRACK,
4417 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4418 }
Eric Laurent81784c32012-11-19 14:55:58 -08004419 mAudioMixer->setParameter(
4420 name,
4421 AudioMixer::TRACK,
4422 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4423
4424 // reset retry count
4425 track->mRetryCount = kMaxTrackRetries;
4426
4427 // If one track is ready, set the mixer ready if:
4428 // - the mixer was not ready during previous round OR
4429 // - no other track is not ready
4430 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4431 mixerStatus != MIXER_TRACKS_ENABLED) {
4432 mixerStatus = MIXER_TRACKS_READY;
4433 }
4434 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004435 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004436 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4437 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004438 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004439 } else {
4440 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004441 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004442
Eric Laurent81784c32012-11-19 14:55:58 -08004443 // clear effect chain input buffer if an active track underruns to avoid sending
4444 // previous audio buffer again to effects
4445 chain = getEffectChain_l(track->sessionId());
4446 if (chain != 0) {
4447 chain->clearInputBuffer();
4448 }
4449
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004450 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004451 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4452 track->isStopped() || track->isPaused()) {
4453 // We have consumed all the buffers of this track.
4454 // Remove it from the list of active tracks.
4455 // TODO: use actual buffer filling status instead of latency when available from
4456 // audio HAL
4457 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004458 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004459 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4460 if (track->isStopped()) {
4461 track->reset();
4462 }
4463 tracksToRemove->add(track);
4464 }
4465 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004466 // No buffers for this track. Give it a few chances to
4467 // fill a buffer, then remove it from active list.
4468 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004469 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004470 tracksToRemove->add(track);
4471 // indicate to client process that the track was disabled because of underrun;
4472 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004473 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004474 // If one track is not ready, mark the mixer also not ready if:
4475 // - the mixer was ready during previous round OR
4476 // - no other track is ready
4477 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4478 mixerStatus != MIXER_TRACKS_READY) {
4479 mixerStatus = MIXER_TRACKS_ENABLED;
4480 }
4481 }
4482 mAudioMixer->disable(name);
4483 }
4484
4485 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004486
4487 }
4488
4489 // Push the new FastMixer state if necessary
4490 bool pauseAudioWatchdog = false;
4491 if (didModify) {
4492 state->mFastTracksGen++;
4493 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4494 if (kUseFastMixer == FastMixer_Dynamic &&
4495 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4496 state->mCommand = FastMixerState::COLD_IDLE;
4497 state->mColdFutexAddr = &mFastMixerFutex;
4498 state->mColdGen++;
4499 mFastMixerFutex = 0;
4500 if (kUseFastMixer == FastMixer_Dynamic) {
4501 mNormalSink = mOutputSink;
4502 }
4503 // If we go into cold idle, need to wait for acknowledgement
4504 // so that fast mixer stops doing I/O.
4505 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4506 pauseAudioWatchdog = true;
4507 }
Eric Laurent81784c32012-11-19 14:55:58 -08004508 }
4509 if (sq != NULL) {
4510 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004511 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4512 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4513 // when bringing the output sink into standby.)
4514 //
4515 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4516 //
4517 // This occurs with BT suspend when we idle the FastMixer with
4518 // active tracks, which may be added or removed.
4519 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004520 }
4521#ifdef AUDIO_WATCHDOG
4522 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4523 mAudioWatchdog->pause();
4524 }
4525#endif
4526
4527 // Now perform the deferred reset on fast tracks that have stopped
4528 while (resetMask != 0) {
4529 size_t i = __builtin_ctz(resetMask);
4530 ALOG_ASSERT(i < count);
4531 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004532 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004533 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4534 track->reset();
4535 }
4536
4537 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004538 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004539
Eric Laurent97d547d2014-09-02 14:45:53 -07004540 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4541 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004542 }
4543
4544 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004545 // as long as there are effects we should clear the effects buffer, to avoid
4546 // passing a non-clean buffer to the effect chain
4547 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004548 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004549 // sink or mix buffer must be cleared if all tracks are connected to an
4550 // effect chain as in this case the mixer will not write to the sink or mix buffer
4551 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004552 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4553 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004554 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004555 if (mMixerBufferValid) {
4556 memset(mMixerBuffer, 0, mMixerBufferSize);
4557 // TODO: In testing, mSinkBuffer below need not be cleared because
4558 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4559 // after mixing.
4560 //
4561 // To enforce this guarantee:
4562 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4563 // (mixedTracks == 0 && fastTracks > 0))
4564 // must imply MIXER_TRACKS_READY.
4565 // Later, we may clear buffers regardless, and skip much of this logic.
4566 }
Andy Hung98ef9782014-03-04 14:46:50 -08004567 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004568 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004569 }
4570
4571 // if any fast tracks, then status is ready
4572 mMixerStatusIgnoringFastTracks = mixerStatus;
4573 if (fastTracks > 0) {
4574 mixerStatus = MIXER_TRACKS_READY;
4575 }
4576 return mixerStatus;
4577}
4578
Eric Laurentad7dd962016-09-22 12:38:37 -07004579// trackCountForUid_l() must be called with ThreadBase::mLock held
4580uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4581{
4582 uint32_t trackCount = 0;
4583 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004584 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004585 trackCount++;
4586 }
4587 }
4588 return trackCount;
4589}
4590
Eric Laurent81784c32012-11-19 14:55:58 -08004591// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004592int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004593 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004594{
Eric Laurentad7dd962016-09-22 12:38:37 -07004595 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4596 return -1;
4597 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004598 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004599}
4600
4601// deleteTrackName_l() must be called with ThreadBase::mLock held
4602void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4603{
4604 ALOGV("remove track (%d) and delete from mixer", name);
4605 mAudioMixer->deleteTrackName(name);
4606}
4607
Eric Laurent10351942014-05-08 18:49:52 -07004608// checkForNewParameter_l() must be called with ThreadBase::mLock held
4609bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4610 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004611{
Eric Laurent81784c32012-11-19 14:55:58 -08004612 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004613 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004614
Eric Laurent10351942014-05-08 18:49:52 -07004615 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004616
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004617 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004618
Eric Laurent10351942014-05-08 18:49:52 -07004619 AudioParameter param = AudioParameter(keyValuePair);
4620 int value;
4621 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4622 reconfig = true;
4623 }
4624 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004625 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004626 status = BAD_VALUE;
4627 } else {
4628 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004629 reconfig = true;
4630 }
Eric Laurent10351942014-05-08 18:49:52 -07004631 }
4632 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004633 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004634 status = BAD_VALUE;
4635 } else {
4636 // no need to save value, since it's constant
4637 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004638 }
Eric Laurent10351942014-05-08 18:49:52 -07004639 }
4640 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4641 // do not accept frame count changes if tracks are open as the track buffer
4642 // size depends on frame count and correct behavior would not be guaranteed
4643 // if frame count is changed after track creation
4644 if (!mTracks.isEmpty()) {
4645 status = INVALID_OPERATION;
4646 } else {
4647 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004648 }
Eric Laurent10351942014-05-08 18:49:52 -07004649 }
4650 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004651#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004652 // when changing the audio output device, call addBatteryData to notify
4653 // the change
4654 if (mOutDevice != value) {
4655 uint32_t params = 0;
4656 // check whether speaker is on
4657 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4658 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004659 }
Eric Laurent10351942014-05-08 18:49:52 -07004660
4661 audio_devices_t deviceWithoutSpeaker
4662 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4663 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004664 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004665 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4666 }
4667
4668 if (params != 0) {
4669 addBatteryData(params);
4670 }
4671 }
Eric Laurent81784c32012-11-19 14:55:58 -08004672#endif
4673
Eric Laurent10351942014-05-08 18:49:52 -07004674 // forward device change to effects that have requested to be
4675 // aware of attached audio device.
4676 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004677 a2dpDeviceChanged =
4678 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004679 mOutDevice = value;
4680 for (size_t i = 0; i < mEffectChains.size(); i++) {
4681 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004682 }
4683 }
Eric Laurent10351942014-05-08 18:49:52 -07004684 }
Eric Laurent81784c32012-11-19 14:55:58 -08004685
Eric Laurent10351942014-05-08 18:49:52 -07004686 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004687 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004688 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004689 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004690 mStandby = true;
4691 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004692 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004693 }
Eric Laurent10351942014-05-08 18:49:52 -07004694 if (status == NO_ERROR && reconfig) {
4695 readOutputParameters_l();
4696 delete mAudioMixer;
4697 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4698 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004699 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004700 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004701 if (name < 0) {
4702 break;
4703 }
4704 mTracks[i]->mName = name;
4705 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004706 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004707 }
Eric Laurent81784c32012-11-19 14:55:58 -08004708 }
4709
Eric Laurent42537be2016-01-08 17:16:42 -08004710 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004711}
4712
4713
4714void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4715{
Eric Laurent81784c32012-11-19 14:55:58 -08004716 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004717 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004718 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004719 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004720
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004721 if (hasFastMixer()) {
4722 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4723
4724 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4725 // while we are dumping it. It may be inconsistent, but it won't mutate!
4726 // This is a large object so we place it on the heap.
4727 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4728 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4729 copy->dump(fd);
4730 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004731
4732#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004733 // Similar for state queue
4734 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4735 observerCopy.dump(fd);
4736 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4737 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004738#endif
4739
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004740#ifdef AUDIO_WATCHDOG
4741 if (mAudioWatchdog != 0) {
4742 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4743 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4744 wdCopy.dump(fd);
4745 }
4746#endif
4747
4748 } else {
4749 dprintf(fd, " No FastMixer\n");
4750 }
4751
Glenn Kasten46909e72013-02-26 09:20:22 -08004752#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004753 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004754 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004755#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004756
Eric Laurent81784c32012-11-19 14:55:58 -08004757}
4758
4759uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4760{
4761 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4762}
4763
4764uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4765{
4766 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4767}
4768
4769void AudioFlinger::MixerThread::cacheParameters_l()
4770{
4771 PlaybackThread::cacheParameters_l();
4772
4773 // FIXME: Relaxed timing because of a certain device that can't meet latency
4774 // Should be reduced to 2x after the vendor fixes the driver issue
4775 // increase threshold again due to low power audio mode. The way this warning
4776 // threshold is calculated and its usefulness should be reconsidered anyway.
4777 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4778}
4779
4780// ----------------------------------------------------------------------------
4781
4782AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004783 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4784 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004785 // mLeftVolFloat, mRightVolFloat
4786{
4787}
4788
Eric Laurentbfb1b832013-01-07 09:53:42 -08004789AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4790 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004791 ThreadBase::type_t type, bool systemReady)
4792 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004793 // mLeftVolFloat, mRightVolFloat
Andy Hung10cbff12017-02-21 17:30:14 -08004794 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004795{
4796}
4797
Eric Laurent81784c32012-11-19 14:55:58 -08004798AudioFlinger::DirectOutputThread::~DirectOutputThread()
4799{
4800}
4801
Eric Laurent5850c4c2016-11-10 13:04:31 -08004802void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004803{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004804 float left, right;
4805
4806 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4807 left = right = 0;
4808 } else {
4809 float typeVolume = mStreamTypes[track->streamType()].volume;
4810 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004811 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004812
Andy Hung10cbff12017-02-21 17:30:14 -08004813 // Get volumeshaper scaling
4814 std::pair<float /* volume */, bool /* active */>
4815 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004816 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004817 v *= vh.first;
4818 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004819
Glenn Kastenc56f3422014-03-21 17:53:17 -07004820 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4821 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4822 if (left > GAIN_FLOAT_UNITY) {
4823 left = GAIN_FLOAT_UNITY;
4824 }
4825 left *= v;
4826 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4827 if (right > GAIN_FLOAT_UNITY) {
4828 right = GAIN_FLOAT_UNITY;
4829 }
4830 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004831 }
4832
4833 if (lastTrack) {
4834 if (left != mLeftVolFloat || right != mRightVolFloat) {
4835 mLeftVolFloat = left;
4836 mRightVolFloat = right;
4837
4838 // Convert volumes from float to 8.24
4839 uint32_t vl = (uint32_t)(left * (1 << 24));
4840 uint32_t vr = (uint32_t)(right * (1 << 24));
4841
4842 // Delegate volume control to effect in track effect chain if needed
4843 // only one effect chain can be present on DirectOutputThread, so if
4844 // there is one, the track is connected to it
4845 if (!mEffectChains.isEmpty()) {
4846 mEffectChains[0]->setVolume_l(&vl, &vr);
4847 left = (float)vl / (1 << 24);
4848 right = (float)vr / (1 << 24);
4849 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004850 status_t result = mOutput->stream->setVolume(left, right);
4851 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004852 }
4853 }
4854}
4855
Phil Burk43b4dcc2015-06-09 16:53:44 -07004856void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4857{
4858 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004859 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004860
Eric Laurent0f0631e2015-07-06 18:01:25 -07004861 if (previousTrack != 0 && latestTrack != 0) {
4862 if (mType == DIRECT) {
4863 if (previousTrack.get() != latestTrack.get()) {
4864 mFlushPending = true;
4865 }
4866 } else /* mType == OFFLOAD */ {
4867 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4868 mFlushPending = true;
4869 }
4870 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004871 }
4872 PlaybackThread::onAddNewTrack_l();
4873}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004874
Eric Laurent81784c32012-11-19 14:55:58 -08004875AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4876 Vector< sp<Track> > *tracksToRemove
4877)
4878{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004879 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004880 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004881 bool doHwPause = false;
4882 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004883
4884 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004885 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004886 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004887 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004888 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004889 continue;
4890 }
4891
Eric Laurent5850c4c2016-11-10 13:04:31 -08004892 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004893#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004894 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004895#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004896 // Only consider last track started for volume and mixer state control.
4897 // In theory an older track could underrun and restart after the new one starts
4898 // but as we only care about the transition phase between two tracks on a
4899 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004900 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004901 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004902
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004903 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004904 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004905 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004906 doHwPause = true;
4907 mHwPaused = true;
4908 }
4909 tracksToRemove->add(track);
4910 } else if (track->isFlushPending()) {
4911 track->flushAck();
4912 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004913 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004914 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004915 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004916 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004917 if (last) {
4918 mLeftVolFloat = mRightVolFloat = -1.0;
4919 if (mHwPaused) {
4920 doHwResume = true;
4921 mHwPaused = false;
4922 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004923 }
4924 }
4925
Eric Laurent81784c32012-11-19 14:55:58 -08004926 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004927 // for all its buffers to be filled before processing it.
4928 // Allow draining the buffer in case the client
4929 // app does not call stop() and relies on underrun to stop:
4930 // hence the test on (track->mRetryCount > 1).
4931 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004932 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004933 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004934 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004935 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004936 minFrames = mNormalFrameCount;
4937 } else {
4938 minFrames = 1;
4939 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004940
Eric Laurentab5cdba2014-06-09 17:22:27 -07004941 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4942 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004943 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004944 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004945
4946 if (track->mFillingUpStatus == Track::FS_FILLED) {
4947 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004948 if (last) {
4949 // make sure processVolume_l() will apply new volume even if 0
4950 mLeftVolFloat = mRightVolFloat = -1.0;
4951 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004952 if (!mHwSupportsPause) {
4953 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004954 }
4955 }
4956
4957 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004958 processVolume_l(track, last);
4959 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004960 sp<Track> previousTrack = mPreviousTrack.promote();
4961 if (previousTrack != 0) {
4962 if (track != previousTrack.get()) {
4963 // Flush any data still being written from last track
4964 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004965 // Invalidate previous track to force a seek when resuming.
4966 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004967 }
4968 }
4969 mPreviousTrack = track;
4970
Eric Laurentd595b7c2013-04-03 17:27:56 -07004971 // reset retry count
4972 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004973 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004974 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004975 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004976 doHwResume = true;
4977 mHwPaused = false;
4978 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004979 }
Eric Laurent81784c32012-11-19 14:55:58 -08004980 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004981 // clear effect chain input buffer if the last active track started underruns
4982 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004983 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004984 mEffectChains[0]->clearInputBuffer();
4985 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004986 if (track->isStopping_1()) {
4987 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004988 if (last && mHwPaused) {
4989 doHwResume = true;
4990 mHwPaused = false;
4991 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004992 }
4993 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4994 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004995 // We have consumed all the buffers of this track.
4996 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004997 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004998 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004999 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5000 } else {
5001 audioHALFrames = 0;
5002 }
5003
Andy Hung818e7a32016-02-16 18:08:07 -08005004 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005005 if (mStandby || !last ||
5006 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005007 if (track->isStopping_2()) {
5008 track->mState = TrackBase::STOPPED;
5009 }
Eric Laurent81784c32012-11-19 14:55:58 -08005010 if (track->isStopped()) {
5011 track->reset();
5012 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005013 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005014 }
5015 } else {
5016 // No buffers for this track. Give it a few chances to
5017 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005018 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005019 if (--(track->mRetryCount) <= 0) {
5020 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005021 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005022 // indicate to client process that the track was disabled because of underrun;
5023 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005024 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005025 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005026 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5027 "minFrames = %u, mFormat = %#x",
5028 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005029 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005030 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005031 doHwPause = true;
5032 mHwPaused = true;
5033 }
Eric Laurent81784c32012-11-19 14:55:58 -08005034 }
5035 }
5036 }
5037 }
5038
Eric Laurentd1f69b02014-12-15 14:33:13 -08005039 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005040 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005041 for (size_t i = 0; i < mTracks.size(); i++) {
5042 if (mTracks[i]->isFlushPending()) {
5043 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005044 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005045 }
5046 }
5047 }
5048
5049 // make sure the pause/flush/resume sequence is executed in the right order.
5050 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5051 // before flush and then resume HW. This can happen in case of pause/flush/resume
5052 // if resume is received before pause is executed.
5053 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005054 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005055 status_t result = mOutput->stream->pause();
5056 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005057 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005058 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005059 flushHw_l();
5060 }
5061 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005062 status_t result = mOutput->stream->resume();
5063 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005064 }
Eric Laurent81784c32012-11-19 14:55:58 -08005065 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005066 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005067
5068 return mixerStatus;
5069}
5070
5071void AudioFlinger::DirectOutputThread::threadLoop_mix()
5072{
Eric Laurent81784c32012-11-19 14:55:58 -08005073 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005074 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005075 // output audio to hardware
5076 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005077 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005078 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005079 status_t status = mActiveTrack->getNextBuffer(&buffer);
5080 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005081 // no need to pad with 0 for compressed audio
5082 if (audio_has_proportional_frames(mFormat)) {
5083 memset(curBuf, 0, frameCount * mFrameSize);
5084 }
Eric Laurent81784c32012-11-19 14:55:58 -08005085 break;
5086 }
5087 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5088 frameCount -= buffer.frameCount;
5089 curBuf += buffer.frameCount * mFrameSize;
5090 mActiveTrack->releaseBuffer(&buffer);
5091 }
Andy Hung2098f272014-02-27 14:00:06 -08005092 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005093 mSleepTimeUs = 0;
5094 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005095 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005096}
5097
5098void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5099{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005100 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005101 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005102 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005103 return;
5104 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005105 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005106 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005107 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005108 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005109 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005110 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005111 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005112 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005113 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005114 }
5115}
5116
Eric Laurentd1f69b02014-12-15 14:33:13 -08005117void AudioFlinger::DirectOutputThread::threadLoop_exit()
5118{
5119 {
5120 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005121 for (size_t i = 0; i < mTracks.size(); i++) {
5122 if (mTracks[i]->isFlushPending()) {
5123 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005124 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005125 }
5126 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005127 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005128 flushHw_l();
5129 }
5130 }
5131 PlaybackThread::threadLoop_exit();
5132}
5133
5134// must be called with thread mutex locked
5135bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5136{
5137 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005138 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005139
vivek mehta9cd7ad12016-03-17 00:18:29 -07005140 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5141 return !mStandby;
5142 }
5143
Eric Laurentd1f69b02014-12-15 14:33:13 -08005144 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5145 // after a timeout and we will enter standby then.
5146 if (mTracks.size() > 0) {
5147 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005148 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5149 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005150 }
5151
Eric Laurent5cff4032015-05-26 13:49:58 -07005152 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005153}
5154
Eric Laurent81784c32012-11-19 14:55:58 -08005155// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005156int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005157 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005158{
Eric Laurentad7dd962016-09-22 12:38:37 -07005159 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5160 return -1;
5161 }
Eric Laurent81784c32012-11-19 14:55:58 -08005162 return 0;
5163}
5164
5165// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005166void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005167{
5168}
5169
Eric Laurent10351942014-05-08 18:49:52 -07005170// checkForNewParameter_l() must be called with ThreadBase::mLock held
5171bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5172 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005173{
5174 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005175 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005176
Eric Laurent10351942014-05-08 18:49:52 -07005177 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005178
Eric Laurent10351942014-05-08 18:49:52 -07005179 AudioParameter param = AudioParameter(keyValuePair);
5180 int value;
5181 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5182 // forward device change to effects that have requested to be
5183 // aware of attached audio device.
5184 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005185 a2dpDeviceChanged =
5186 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005187 mOutDevice = value;
5188 for (size_t i = 0; i < mEffectChains.size(); i++) {
5189 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005190 }
5191 }
Eric Laurent81784c32012-11-19 14:55:58 -08005192 }
Eric Laurent10351942014-05-08 18:49:52 -07005193 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5194 // do not accept frame count changes if tracks are open as the track buffer
5195 // size depends on frame count and correct behavior would not be garantied
5196 // if frame count is changed after track creation
5197 if (!mTracks.isEmpty()) {
5198 status = INVALID_OPERATION;
5199 } else {
5200 reconfig = true;
5201 }
5202 }
5203 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005204 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005205 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005206 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005207 mStandby = true;
5208 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005209 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005210 }
5211 if (status == NO_ERROR && reconfig) {
5212 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005213 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005214 }
5215 }
5216
Eric Laurent42537be2016-01-08 17:16:42 -08005217 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005218}
5219
5220uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5221{
5222 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005223 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005224 time = PlaybackThread::activeSleepTimeUs();
5225 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005226 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005227 }
5228 return time;
5229}
5230
5231uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5232{
5233 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005234 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005235 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5236 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005237 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005238 }
5239 return time;
5240}
5241
5242uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5243{
5244 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005245 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005246 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5247 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005248 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005249 }
5250 return time;
5251}
5252
5253void AudioFlinger::DirectOutputThread::cacheParameters_l()
5254{
5255 PlaybackThread::cacheParameters_l();
5256
5257 // use shorter standby delay as on normal output to release
5258 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005259 // no delay on outputs with HW A/V sync
5260 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005261 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005262 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005263 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005264 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005265 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005266 }
Eric Laurent81784c32012-11-19 14:55:58 -08005267}
5268
Eric Laurente659ef42014-09-29 13:06:46 -07005269void AudioFlinger::DirectOutputThread::flushHw_l()
5270{
Phil Burk062e67a2015-02-11 13:40:50 -08005271 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005272 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005273 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005274}
5275
Andy Hung10cbff12017-02-21 17:30:14 -08005276int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5277 // If a VolumeShaper is active, we must wake up periodically to update volume.
5278 const int64_t NS_PER_MS = 1000000;
5279 return mVolumeShaperActive ?
5280 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5281}
5282
Eric Laurent81784c32012-11-19 14:55:58 -08005283// ----------------------------------------------------------------------------
5284
Eric Laurentbfb1b832013-01-07 09:53:42 -08005285AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005286 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005287 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005288 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005289 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005290 mDrainSequence(0),
5291 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005292{
5293}
5294
5295AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5296{
5297}
5298
5299void AudioFlinger::AsyncCallbackThread::onFirstRef()
5300{
5301 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5302}
5303
5304bool AudioFlinger::AsyncCallbackThread::threadLoop()
5305{
5306 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005307 uint32_t writeAckSequence;
5308 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005309 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005310
5311 {
5312 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005313 while (!((mWriteAckSequence & 1) ||
5314 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005315 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005316 exitPending())) {
5317 mWaitWorkCV.wait(mLock);
5318 }
5319
Eric Laurentbfb1b832013-01-07 09:53:42 -08005320 if (exitPending()) {
5321 break;
5322 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005323 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5324 mWriteAckSequence, mDrainSequence);
5325 writeAckSequence = mWriteAckSequence;
5326 mWriteAckSequence &= ~1;
5327 drainSequence = mDrainSequence;
5328 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005329 asyncError = mAsyncError;
5330 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005331 }
5332 {
Eric Laurent4de95592013-09-26 15:28:21 -07005333 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5334 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005335 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005336 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005337 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005338 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005339 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005340 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005341 if (asyncError) {
5342 playbackThread->onAsyncError();
5343 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344 }
5345 }
5346 }
5347 return false;
5348}
5349
5350void AudioFlinger::AsyncCallbackThread::exit()
5351{
5352 ALOGV("AsyncCallbackThread::exit");
5353 Mutex::Autolock _l(mLock);
5354 requestExit();
5355 mWaitWorkCV.broadcast();
5356}
5357
Eric Laurent3b4529e2013-09-05 18:09:19 -07005358void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005359{
5360 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005361 // bit 0 is cleared
5362 mWriteAckSequence = sequence << 1;
5363}
5364
5365void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5366{
5367 Mutex::Autolock _l(mLock);
5368 // ignore unexpected callbacks
5369 if (mWriteAckSequence & 2) {
5370 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005371 mWaitWorkCV.signal();
5372 }
5373}
5374
Eric Laurent3b4529e2013-09-05 18:09:19 -07005375void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005376{
5377 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005378 // bit 0 is cleared
5379 mDrainSequence = sequence << 1;
5380}
5381
5382void AudioFlinger::AsyncCallbackThread::resetDraining()
5383{
5384 Mutex::Autolock _l(mLock);
5385 // ignore unexpected callbacks
5386 if (mDrainSequence & 2) {
5387 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005388 mWaitWorkCV.signal();
5389 }
5390}
5391
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005392void AudioFlinger::AsyncCallbackThread::setAsyncError()
5393{
5394 Mutex::Autolock _l(mLock);
5395 mAsyncError = true;
5396 mWaitWorkCV.signal();
5397}
5398
Eric Laurentbfb1b832013-01-07 09:53:42 -08005399
5400// ----------------------------------------------------------------------------
5401AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005402 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5403 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005404 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5405 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005406{
Eric Laurentfd477972013-10-25 18:10:40 -07005407 //FIXME: mStandby should be set to true by ThreadBase constructor
5408 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005409 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005410}
5411
Eric Laurentbfb1b832013-01-07 09:53:42 -08005412void AudioFlinger::OffloadThread::threadLoop_exit()
5413{
5414 if (mFlushPending || mHwPaused) {
5415 // If a flush is pending or track was paused, just discard buffered data
5416 flushHw_l();
5417 } else {
5418 mMixerStatus = MIXER_DRAIN_ALL;
5419 threadLoop_drain();
5420 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005421 if (mUseAsyncWrite) {
5422 ALOG_ASSERT(mCallbackThread != 0);
5423 mCallbackThread->exit();
5424 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005425 PlaybackThread::threadLoop_exit();
5426}
5427
5428AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5429 Vector< sp<Track> > *tracksToRemove
5430)
5431{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 size_t count = mActiveTracks.size();
5433
5434 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005435 bool doHwPause = false;
5436 bool doHwResume = false;
5437
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005438 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005439
Eric Laurentbfb1b832013-01-07 09:53:42 -08005440 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005441 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005442 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005443#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005444 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005445#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005446 // Only consider last track started for volume and mixer state control.
5447 // In theory an older track could underrun and restart after the new one starts
5448 // but as we only care about the transition phase between two tracks on a
5449 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005450 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005451 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005452
Haynes Mathew George7844f672014-01-15 12:32:55 -08005453 if (track->isInvalid()) {
5454 ALOGW("An invalidated track shouldn't be in active list");
5455 tracksToRemove->add(track);
5456 continue;
5457 }
5458
5459 if (track->mState == TrackBase::IDLE) {
5460 ALOGW("An idle track shouldn't be in active list");
5461 continue;
5462 }
5463
Eric Laurentbfb1b832013-01-07 09:53:42 -08005464 if (track->isPausing()) {
5465 track->setPaused();
5466 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005467 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005468 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005469 mHwPaused = true;
5470 }
5471 // If we were part way through writing the mixbuffer to
5472 // the HAL we must save this until we resume
5473 // BUG - this will be wrong if a different track is made active,
5474 // in that case we want to discard the pending data in the
5475 // mixbuffer and tell the client to present it again when the
5476 // track is resumed
5477 mPausedWriteLength = mCurrentWriteLength;
5478 mPausedBytesRemaining = mBytesRemaining;
5479 mBytesRemaining = 0; // stop writing
5480 }
5481 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005482 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005483 if (track->isStopping_1()) {
5484 track->mRetryCount = kMaxTrackStopRetriesOffload;
5485 } else {
5486 track->mRetryCount = kMaxTrackRetriesOffload;
5487 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005488 track->flushAck();
5489 if (last) {
5490 mFlushPending = true;
5491 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005492 } else if (track->isResumePending()){
5493 track->resumeAck();
5494 if (last) {
5495 if (mPausedBytesRemaining) {
5496 // Need to continue write that was interrupted
5497 mCurrentWriteLength = mPausedWriteLength;
5498 mBytesRemaining = mPausedBytesRemaining;
5499 mPausedBytesRemaining = 0;
5500 }
5501 if (mHwPaused) {
5502 doHwResume = true;
5503 mHwPaused = false;
5504 // threadLoop_mix() will handle the case that we need to
5505 // resume an interrupted write
5506 }
5507 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005508 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005509
Eric Laurent3df841a2016-07-15 15:15:40 -07005510 mLeftVolFloat = mRightVolFloat = -1.0;
5511
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005512 // Do not handle new data in this iteration even if track->framesReady()
5513 mixerStatus = MIXER_TRACKS_ENABLED;
5514 }
5515 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005516 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005517 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005518 if (track->mFillingUpStatus == Track::FS_FILLED) {
5519 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005520 if (last) {
5521 // make sure processVolume_l() will apply new volume even if 0
5522 mLeftVolFloat = mRightVolFloat = -1.0;
5523 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005524 }
5525
5526 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005527 sp<Track> previousTrack = mPreviousTrack.promote();
5528 if (previousTrack != 0) {
5529 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005530 // Flush any data still being written from last track
5531 mBytesRemaining = 0;
5532 if (mPausedBytesRemaining) {
5533 // Last track was paused so we also need to flush saved
5534 // mixbuffer state and invalidate track so that it will
5535 // re-submit that unwritten data when it is next resumed
5536 mPausedBytesRemaining = 0;
5537 // Invalidate is a bit drastic - would be more efficient
5538 // to have a flag to tell client that some of the
5539 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005540 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005541 }
5542 // flush data already sent to the DSP if changing audio session as audio
5543 // comes from a different source. Also invalidate previous track to force a
5544 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005545 if (previousTrack->sessionId() != track->sessionId()) {
5546 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005547 }
5548 }
5549 }
5550 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005551 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005552 if (track->isStopping_1()) {
5553 track->mRetryCount = kMaxTrackStopRetriesOffload;
5554 } else {
5555 track->mRetryCount = kMaxTrackRetriesOffload;
5556 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005557 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005558 mixerStatus = MIXER_TRACKS_READY;
5559 }
5560 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005561 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005562 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005563 if (--(track->mRetryCount) <= 0) {
5564 // Hardware buffer can hold a large amount of audio so we must
5565 // wait for all current track's data to drain before we say
5566 // that the track is stopped.
5567 if (mBytesRemaining == 0) {
5568 // Only start draining when all data in mixbuffer
5569 // has been written
5570 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5571 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5572 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5573 if (last && !mStandby) {
5574 // do not modify drain sequence if we are already draining. This happens
5575 // when resuming from pause after drain.
5576 if ((mDrainSequence & 1) == 0) {
5577 mSleepTimeUs = 0;
5578 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5579 mixerStatus = MIXER_DRAIN_TRACK;
5580 mDrainSequence += 2;
5581 }
5582 if (mHwPaused) {
5583 // It is possible to move from PAUSED to STOPPING_1 without
5584 // a resume so we must ensure hardware is running
5585 doHwResume = true;
5586 mHwPaused = false;
5587 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005588 }
5589 }
Eric Laurente93cc032016-05-05 10:15:10 -07005590 } else if (last) {
5591 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5592 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005593 }
5594 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005595 // Drain has completed or we are in standby, signal presentation complete
5596 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005597 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005598 uint32_t latency = 0;
5599 status_t result = mOutput->stream->getLatency(&latency);
5600 ALOGE_IF(result != OK,
5601 "Error when retrieving output stream latency: %d", result);
5602 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005603 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005604 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005605 track->presentationComplete(framesWritten, audioHALFrames);
5606 track->reset();
5607 tracksToRemove->add(track);
5608 }
5609 } else {
5610 // No buffers for this track. Give it a few chances to
5611 // fill a buffer, then remove it from active list.
5612 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005613 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005614 uint64_t position = 0;
5615 struct timespec unused;
5616 // The running check restarts the retry counter at least once.
5617 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5618 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5619 running = true;
5620 mOffloadUnderrunPosition = position;
5621 }
5622 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005623 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5624 (long long)position, (long long)mOffloadUnderrunPosition);
5625 }
5626 if (running) { // still running, give us more time.
5627 track->mRetryCount = kMaxTrackRetriesOffload;
5628 } else {
5629 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5630 track->name());
5631 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005632 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005633 // it will then automatically call start() when data is available
5634 track->disable();
5635 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005636 } else if (last){
5637 mixerStatus = MIXER_TRACKS_ENABLED;
5638 }
5639 }
5640 }
5641 // compute volume for this track
5642 processVolume_l(track, last);
5643 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005644
Eric Laurentea0fade2013-10-04 16:23:48 -07005645 // make sure the pause/flush/resume sequence is executed in the right order.
5646 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5647 // before flush and then resume HW. This can happen in case of pause/flush/resume
5648 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005649 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005650 status_t result = mOutput->stream->pause();
5651 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005652 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005653 if (mFlushPending) {
5654 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005655 }
Eric Laurentfd477972013-10-25 18:10:40 -07005656 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005657 status_t result = mOutput->stream->resume();
5658 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005659 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005660
Eric Laurentbfb1b832013-01-07 09:53:42 -08005661 // remove all the tracks that need to be...
5662 removeTracks_l(*tracksToRemove);
5663
5664 return mixerStatus;
5665}
5666
Eric Laurentbfb1b832013-01-07 09:53:42 -08005667// must be called with thread mutex locked
5668bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5669{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005670 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5671 mWriteAckSequence, mDrainSequence);
5672 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005673 return true;
5674 }
5675 return false;
5676}
5677
Eric Laurentbfb1b832013-01-07 09:53:42 -08005678bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5679{
5680 Mutex::Autolock _l(mLock);
5681 return waitingAsyncCallback_l();
5682}
5683
5684void AudioFlinger::OffloadThread::flushHw_l()
5685{
Eric Laurente659ef42014-09-29 13:06:46 -07005686 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005687 // Flush anything still waiting in the mixbuffer
5688 mCurrentWriteLength = 0;
5689 mBytesRemaining = 0;
5690 mPausedWriteLength = 0;
5691 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005692 // reset bytes written count to reflect that DSP buffers are empty after flush.
5693 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005694 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005695
Eric Laurentbfb1b832013-01-07 09:53:42 -08005696 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005697 // discard any pending drain or write ack by incrementing sequence
5698 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5699 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005700 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005701 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5702 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005703 }
5704}
5705
Haynes Mathew George05317d22016-05-03 16:34:26 -07005706void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5707{
5708 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005709 if (PlaybackThread::invalidateTracks_l(streamType)) {
5710 mFlushPending = true;
5711 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005712}
5713
Eric Laurentbfb1b832013-01-07 09:53:42 -08005714// ----------------------------------------------------------------------------
5715
Eric Laurent81784c32012-11-19 14:55:58 -08005716AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005717 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005718 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005719 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005720 mWaitTimeMs(UINT_MAX)
5721{
5722 addOutputTrack(mainThread);
5723}
5724
5725AudioFlinger::DuplicatingThread::~DuplicatingThread()
5726{
5727 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5728 mOutputTracks[i]->destroy();
5729 }
5730}
5731
5732void AudioFlinger::DuplicatingThread::threadLoop_mix()
5733{
5734 // mix buffers...
5735 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005736 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005737 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005738 if (mMixerBufferValid) {
5739 memset(mMixerBuffer, 0, mMixerBufferSize);
5740 } else {
5741 memset(mSinkBuffer, 0, mSinkBufferSize);
5742 }
Eric Laurent81784c32012-11-19 14:55:58 -08005743 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005744 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005745 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005746 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005747 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005748}
5749
5750void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5751{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005752 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005753 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005754 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005755 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005756 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005757 }
5758 } else if (mBytesWritten != 0) {
5759 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5760 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005761 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005762 } else {
5763 // flush remaining overflow buffers in output tracks
5764 writeFrames = 0;
5765 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005766 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005767 }
5768}
5769
Eric Laurentbfb1b832013-01-07 09:53:42 -08005770ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005771{
5772 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005773 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005774 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005775 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005776 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005777}
5778
5779void AudioFlinger::DuplicatingThread::threadLoop_standby()
5780{
5781 // DuplicatingThread implements standby by stopping all tracks
5782 for (size_t i = 0; i < outputTracks.size(); i++) {
5783 outputTracks[i]->stop();
5784 }
5785}
5786
5787void AudioFlinger::DuplicatingThread::saveOutputTracks()
5788{
5789 outputTracks = mOutputTracks;
5790}
5791
5792void AudioFlinger::DuplicatingThread::clearOutputTracks()
5793{
5794 outputTracks.clear();
5795}
5796
5797void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5798{
5799 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005800 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5801 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5802 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5803 const size_t frameCount =
5804 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5805 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5806 // from different OutputTracks and their associated MixerThreads (e.g. one may
5807 // nearly empty and the other may be dropping data).
5808
5809 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005810 this,
5811 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005812 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005813 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005814 frameCount,
5815 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005816 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5817 if (status != NO_ERROR) {
5818 ALOGE("addOutputTrack() initCheck failed %d", status);
5819 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005820 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005821 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5822 mOutputTracks.add(outputTrack);
5823 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5824 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005825}
5826
5827void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5828{
5829 Mutex::Autolock _l(mLock);
5830 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5831 if (mOutputTracks[i]->thread() == thread) {
5832 mOutputTracks[i]->destroy();
5833 mOutputTracks.removeAt(i);
5834 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005835 if (thread->getOutput() == mOutput) {
5836 mOutput = NULL;
5837 }
Eric Laurent81784c32012-11-19 14:55:58 -08005838 return;
5839 }
5840 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005841 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005842}
5843
5844// caller must hold mLock
5845void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5846{
5847 mWaitTimeMs = UINT_MAX;
5848 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5849 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5850 if (strong != 0) {
5851 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5852 if (waitTimeMs < mWaitTimeMs) {
5853 mWaitTimeMs = waitTimeMs;
5854 }
5855 }
5856 }
5857}
5858
5859
5860bool AudioFlinger::DuplicatingThread::outputsReady(
5861 const SortedVector< sp<OutputTrack> > &outputTracks)
5862{
5863 for (size_t i = 0; i < outputTracks.size(); i++) {
5864 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5865 if (thread == 0) {
5866 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5867 outputTracks[i].get());
5868 return false;
5869 }
5870 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5871 // see note at standby() declaration
5872 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5873 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5874 thread.get());
5875 return false;
5876 }
5877 }
5878 return true;
5879}
5880
5881uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5882{
5883 return (mWaitTimeMs * 1000) / 2;
5884}
5885
5886void AudioFlinger::DuplicatingThread::cacheParameters_l()
5887{
5888 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5889 updateWaitTime_l();
5890
5891 MixerThread::cacheParameters_l();
5892}
5893
Eric Laurent6acd1d42017-01-04 14:23:29 -08005894
Eric Laurent81784c32012-11-19 14:55:58 -08005895// ----------------------------------------------------------------------------
5896// Record
5897// ----------------------------------------------------------------------------
5898
5899AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5900 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005901 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005902 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005903 audio_devices_t inDevice,
5904 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005905#ifdef TEE_SINK
5906 , const sp<NBAIO_Sink>& teeSink
5907#endif
5908 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005909 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005910 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005911 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005912 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005913#ifdef TEE_SINK
5914 , mTeeSink(teeSink)
5915#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005916 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5917 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005918 // mFastCapture below
5919 , mFastCaptureFutex(0)
5920 // mInputSource
5921 // mPipeSink
5922 // mPipeSource
5923 , mPipeFramesP2(0)
5924 // mPipeMemory
5925 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005926 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005927{
Glenn Kastend7dca052015-03-05 16:05:54 -08005928 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5929 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005930
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005931 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005932
5933 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005934 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005935 size_t numCounterOffers = 0;
5936 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005937#if !LOG_NDEBUG
5938 ssize_t index =
5939#else
5940 (void)
5941#endif
5942 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005943 ALOG_ASSERT(index == 0);
5944
5945 // initialize fast capture depending on configuration
5946 bool initFastCapture;
5947 switch (kUseFastCapture) {
5948 case FastCapture_Never:
5949 initFastCapture = false;
5950 break;
5951 case FastCapture_Always:
5952 initFastCapture = true;
5953 break;
5954 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005955 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005956 break;
5957 // case FastCapture_Dynamic:
5958 }
5959
5960 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005961 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005962 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005963 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5964 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005965 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5966 void *pipeBuffer;
5967 const sp<MemoryDealer> roHeap(readOnlyHeap());
5968 sp<IMemory> pipeMemory;
5969 if ((roHeap == 0) ||
5970 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5971 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5972 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5973 goto failed;
5974 }
5975 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5976 memset(pipeBuffer, 0, pipeSize);
5977 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5978 const NBAIO_Format offers[1] = {format};
5979 size_t numCounterOffers = 0;
5980 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5981 ALOG_ASSERT(index == 0);
5982 mPipeSink = pipe;
5983 PipeReader *pipeReader = new PipeReader(*pipe);
5984 numCounterOffers = 0;
5985 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5986 ALOG_ASSERT(index == 0);
5987 mPipeSource = pipeReader;
5988 mPipeFramesP2 = pipeFramesP2;
5989 mPipeMemory = pipeMemory;
5990
5991 // create fast capture
5992 mFastCapture = new FastCapture();
5993 FastCaptureStateQueue *sq = mFastCapture->sq();
5994#ifdef STATE_QUEUE_DUMP
5995 // FIXME
5996#endif
5997 FastCaptureState *state = sq->begin();
5998 state->mCblk = NULL;
5999 state->mInputSource = mInputSource.get();
6000 state->mInputSourceGen++;
6001 state->mPipeSink = pipe;
6002 state->mPipeSinkGen++;
6003 state->mFrameCount = mFrameCount;
6004 state->mCommand = FastCaptureState::COLD_IDLE;
6005 // already done in constructor initialization list
6006 //mFastCaptureFutex = 0;
6007 state->mColdFutexAddr = &mFastCaptureFutex;
6008 state->mColdGen++;
6009 state->mDumpState = &mFastCaptureDumpState;
6010#ifdef TEE_SINK
6011 // FIXME
6012#endif
6013 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6014 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6015 sq->end();
6016 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6017
6018 // start the fast capture
6019 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6020 pid_t tid = mFastCapture->getTid();
Mikhail Naganov83f04272017-02-07 10:45:09 -08006021 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006022 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006023#ifdef AUDIO_WATCHDOG
6024 // FIXME
6025#endif
6026
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006027 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006028 }
6029failed: ;
6030
6031 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006032}
6033
Eric Laurent81784c32012-11-19 14:55:58 -08006034AudioFlinger::RecordThread::~RecordThread()
6035{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006036 if (mFastCapture != 0) {
6037 FastCaptureStateQueue *sq = mFastCapture->sq();
6038 FastCaptureState *state = sq->begin();
6039 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6040 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6041 if (old == -1) {
6042 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6043 }
6044 }
6045 state->mCommand = FastCaptureState::EXIT;
6046 sq->end();
6047 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6048 mFastCapture->join();
6049 mFastCapture.clear();
6050 }
6051 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006052 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006053 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006054}
6055
6056void AudioFlinger::RecordThread::onFirstRef()
6057{
Glenn Kastend7dca052015-03-05 16:05:54 -08006058 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006059}
6060
Eric Laurent555530a2017-02-07 18:17:24 -08006061void AudioFlinger::RecordThread::preExit()
6062{
6063 ALOGV(" preExit()");
6064 Mutex::Autolock _l(mLock);
6065 for (size_t i = 0; i < mTracks.size(); i++) {
6066 sp<RecordTrack> track = mTracks[i];
6067 track->invalidate();
6068 }
6069 mActiveTracks.clear();
6070 mStartStopCond.broadcast();
6071}
6072
Eric Laurent81784c32012-11-19 14:55:58 -08006073bool AudioFlinger::RecordThread::threadLoop()
6074{
Eric Laurent81784c32012-11-19 14:55:58 -08006075 nsecs_t lastWarning = 0;
6076
6077 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006078
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006079reacquire_wakelock:
6080 sp<RecordTrack> activeTrack;
6081 {
6082 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006083 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006084 }
6085
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006086 // used to request a deferred sleep, to be executed later while mutex is unlocked
6087 uint32_t sleepUs = 0;
6088
6089 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006090 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006091 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006092
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006093 // activeTracks accumulates a copy of a subset of mActiveTracks
6094 Vector< sp<RecordTrack> > activeTracks;
6095
Glenn Kasten735f45f2014-08-18 15:51:59 -07006096 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006097 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006098
Glenn Kasten735f45f2014-08-18 15:51:59 -07006099 // reference to a fast track which is about to be removed
6100 sp<RecordTrack> fastTrackToRemove;
6101
Eric Laurent81784c32012-11-19 14:55:58 -08006102 { // scope for mLock
6103 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006104
Eric Laurent021cf962014-05-13 10:18:14 -07006105 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006106
Eric Laurent000a4192014-01-29 15:17:32 -08006107 // check exitPending here because checkForNewParameters_l() and
6108 // checkForNewParameters_l() can temporarily release mLock
6109 if (exitPending()) {
6110 break;
6111 }
6112
Eric Laurent5c25d562016-07-13 17:17:45 -07006113 // sleep with mutex unlocked
6114 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006115 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006116 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6117 ATRACE_END();
6118 sleepUs = 0;
6119 continue;
6120 }
6121
Glenn Kasten2b806402013-11-20 16:37:38 -08006122 // if no active track(s), then standby and release wakelock
6123 size_t size = mActiveTracks.size();
6124 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006125 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006126 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006127 releaseWakeLock_l();
6128 ALOGV("RecordThread: loop stopping");
6129 // go to sleep
6130 mWaitWorkCV.wait(mLock);
6131 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006132 goto reacquire_wakelock;
6133 }
6134
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006135 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006136 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006137 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006138
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006139 activeTrack = mActiveTracks[i];
6140 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006141 if (activeTrack->isFastTrack()) {
6142 ALOG_ASSERT(fastTrackToRemove == 0);
6143 fastTrackToRemove = activeTrack;
6144 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006145 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006146 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006147 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006148 continue;
6149 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006150
6151 TrackBase::track_state activeTrackState = activeTrack->mState;
6152 switch (activeTrackState) {
6153
6154 case TrackBase::PAUSING:
6155 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006156 doBroadcast = true;
6157 size--;
6158 continue;
6159
6160 case TrackBase::STARTING_1:
6161 sleepUs = 10000;
6162 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006163 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006164 continue;
6165
6166 case TrackBase::STARTING_2:
6167 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006168 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006169 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006170 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006171 break;
6172
6173 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006174 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006175 break;
6176
6177 case TrackBase::IDLE:
6178 i++;
6179 continue;
6180
6181 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006182 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006183 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006184
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185 activeTracks.add(activeTrack);
6186 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006187
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006188 if (activeTrack->isFastTrack()) {
6189 ALOG_ASSERT(!mFastTrackAvail);
6190 ALOG_ASSERT(fastTrack == 0);
6191 fastTrack = activeTrack;
6192 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006193 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006194
Andy Hungdae27702016-10-31 14:01:16 -07006195 mActiveTracks.updatePowerState(this);
6196
Eric Laurent5c25d562016-07-13 17:17:45 -07006197 if (allStopped) {
6198 standbyIfNotAlreadyInStandby();
6199 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006200 if (doBroadcast) {
6201 mStartStopCond.broadcast();
6202 }
6203
6204 // sleep if there are no active tracks to process
6205 if (activeTracks.size() == 0) {
6206 if (sleepUs == 0) {
6207 sleepUs = kRecordThreadSleepUs;
6208 }
6209 continue;
6210 }
6211 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006212
Eric Laurent81784c32012-11-19 14:55:58 -08006213 lockEffectChains_l(effectChains);
6214 }
6215
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006216 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006217
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006218 size_t size = effectChains.size();
6219 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006220 // thread mutex is not locked, but effect chain is locked
6221 effectChains[i]->process_l();
6222 }
6223
Glenn Kasten735f45f2014-08-18 15:51:59 -07006224 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006225 if (mFastCapture != 0) {
6226 FastCaptureStateQueue *sq = mFastCapture->sq();
6227 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006228 bool didModify = false;
6229 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006230 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6231 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6232 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6233 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6234 if (old == -1) {
6235 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6236 }
6237 }
6238 state->mCommand = FastCaptureState::READ_WRITE;
6239#if 0 // FIXME
6240 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006241 FastThreadDumpState::kSamplingNforLowRamDevice :
6242 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006243#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006244 didModify = true;
6245 }
6246 audio_track_cblk_t *cblkOld = state->mCblk;
6247 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6248 if (cblkNew != cblkOld) {
6249 state->mCblk = cblkNew;
6250 // block until acked if removing a fast track
6251 if (cblkOld != NULL) {
6252 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6253 }
6254 didModify = true;
6255 }
6256 sq->end(didModify);
6257 if (didModify) {
6258 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006259#if 0
6260 if (kUseFastCapture == FastCapture_Dynamic) {
6261 mNormalSource = mPipeSource;
6262 }
6263#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006264 }
6265 }
6266
Glenn Kasten735f45f2014-08-18 15:51:59 -07006267 // now run the fast track destructor with thread mutex unlocked
6268 fastTrackToRemove.clear();
6269
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006270 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6271 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6272 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6273 // If destination is non-contiguous, first read past the nominal end of buffer, then
6274 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006275
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006276 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006277 ssize_t framesRead;
6278
6279 // If an NBAIO source is present, use it to read the normal capture's data
6280 if (mPipeSource != 0) {
6281 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006282 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006283 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006284 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006285 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6286 // buffer size or at least for 20ms.
6287 size_t sleepFrames = max(
6288 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6289 if (framesRead <= (ssize_t) sleepFrames) {
6290 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6291 }
6292 if (framesRead < 0) {
6293 status_t status = (status_t) framesRead;
6294 switch (status) {
6295 case OVERRUN:
6296 ALOGW("overrun on read from pipe");
6297 framesRead = 0;
6298 break;
6299 case NEGOTIATE:
6300 ALOGE("re-negotiation is needed");
6301 framesRead = -1; // Will cause an attempt to recover.
6302 break;
6303 default:
6304 ALOGE("unknown error %d on read from pipe", status);
6305 break;
6306 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006307 }
6308 // otherwise use the HAL / AudioStreamIn directly
6309 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006310 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006311 size_t bytesRead;
6312 status_t result = mInput->stream->read(
6313 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006314 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006315 if (result < 0) {
6316 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006317 } else {
6318 framesRead = bytesRead / mFrameSize;
6319 }
6320 }
6321
Andy Hung3f0c9022016-01-15 17:49:46 -08006322 // Update server timestamp with server stats
6323 // systemTime() is optional if the hardware supports timestamps.
6324 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6325 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6326
6327 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006328 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006329 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006330 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006331 if (ret == NO_ERROR) {
6332 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6333 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6334 // Note: In general record buffers should tend to be empty in
6335 // a properly running pipeline.
6336 //
6337 // Also, it is not advantageous to call get_presentation_position during the read
6338 // as the read obtains a lock, preventing the timestamp call from executing.
6339 }
6340 }
6341 // Use this to track timestamp information
6342 // ALOGD("%s", mTimestamp.toString().c_str());
6343
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006344 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006345 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006346 // Force input into standby so that it tries to recover at next read attempt
6347 inputStandBy();
6348 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006349 }
6350 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006351 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006352 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006353 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006354
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006355 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006356 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006357 }
6358 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006359 {
6360 size_t part1 = mRsmpInFramesP2 - rear;
6361 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006362 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006363 (framesRead - part1) * mFrameSize);
6364 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006365 }
6366 rear = mRsmpInRear += framesRead;
6367
6368 size = activeTracks.size();
6369 // loop over each active track
6370 for (size_t i = 0; i < size; i++) {
6371 activeTrack = activeTracks[i];
6372
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006373 // skip fast tracks, as those are handled directly by FastCapture
6374 if (activeTrack->isFastTrack()) {
6375 continue;
6376 }
6377
Andy Hung73c02e42015-03-29 01:13:58 -07006378 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006379 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6380
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006381 enum {
6382 OVERRUN_UNKNOWN,
6383 OVERRUN_TRUE,
6384 OVERRUN_FALSE
6385 } overrun = OVERRUN_UNKNOWN;
6386
6387 // loop over getNextBuffer to handle circular sink
6388 for (;;) {
6389
6390 activeTrack->mSink.frameCount = ~0;
6391 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6392 size_t framesOut = activeTrack->mSink.frameCount;
6393 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6394
Andy Hung73c02e42015-03-29 01:13:58 -07006395 // check available frames and handle overrun conditions
6396 // if the record track isn't draining fast enough.
6397 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006398 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006399 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6400 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006401 overrun = OVERRUN_TRUE;
6402 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006403 if (framesOut == 0 || framesIn == 0) {
6404 break;
6405 }
6406
Andy Hung6770c6f2015-04-07 13:43:36 -07006407 // Don't allow framesOut to be larger than what is possible with resampling
6408 // from framesIn.
6409 // This isn't strictly necessary but helps limit buffer resizing in
6410 // RecordBufferConverter. TODO: remove when no longer needed.
6411 framesOut = min(framesOut,
6412 destinationFramesPossible(
6413 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006414 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6415 framesOut = activeTrack->mRecordBufferConverter->convert(
6416 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006417
6418 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6419 overrun = OVERRUN_FALSE;
6420 }
6421
6422 if (activeTrack->mFramesToDrop == 0) {
6423 if (framesOut > 0) {
6424 activeTrack->mSink.frameCount = framesOut;
6425 activeTrack->releaseBuffer(&activeTrack->mSink);
6426 }
6427 } else {
6428 // FIXME could do a partial drop of framesOut
6429 if (activeTrack->mFramesToDrop > 0) {
6430 activeTrack->mFramesToDrop -= framesOut;
6431 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006432 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006433 }
6434 } else {
6435 activeTrack->mFramesToDrop += framesOut;
6436 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6437 activeTrack->mSyncStartEvent->isCancelled()) {
6438 ALOGW("Synced record %s, session %d, trigger session %d",
6439 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6440 activeTrack->sessionId(),
6441 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006442 activeTrack->mSyncStartEvent->triggerSession() :
6443 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006444 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006445 }
6446 }
6447 }
6448
6449 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006450 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006451 }
6452 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006453
6454 switch (overrun) {
6455 case OVERRUN_TRUE:
6456 // client isn't retrieving buffers fast enough
6457 if (!activeTrack->setOverflow()) {
6458 nsecs_t now = systemTime();
6459 // FIXME should lastWarning per track?
6460 if ((now - lastWarning) > kWarningThrottleNs) {
6461 ALOGW("RecordThread: buffer overflow");
6462 lastWarning = now;
6463 }
6464 }
6465 break;
6466 case OVERRUN_FALSE:
6467 activeTrack->clearOverflow();
6468 break;
6469 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006470 break;
6471 }
6472
Andy Hung3f0c9022016-01-15 17:49:46 -08006473 // update frame information and push timestamp out
6474 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006475 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006476 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6477 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006478 }
6479
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006480unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006481 // enable changes in effect chain
6482 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006483 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006484 }
6485
Glenn Kasten93e471f2013-08-19 08:40:07 -07006486 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006487
6488 {
6489 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006490 for (size_t i = 0; i < mTracks.size(); i++) {
6491 sp<RecordTrack> track = mTracks[i];
6492 track->invalidate();
6493 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006494 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006495 mStartStopCond.broadcast();
6496 }
6497
6498 releaseWakeLock();
6499
6500 ALOGV("RecordThread %p exiting", this);
6501 return false;
6502}
6503
Glenn Kasten93e471f2013-08-19 08:40:07 -07006504void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006505{
6506 if (!mStandby) {
6507 inputStandBy();
6508 mStandby = true;
6509 }
6510}
6511
6512void AudioFlinger::RecordThread::inputStandBy()
6513{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006514 // Idle the fast capture if it's currently running
6515 if (mFastCapture != 0) {
6516 FastCaptureStateQueue *sq = mFastCapture->sq();
6517 FastCaptureState *state = sq->begin();
6518 if (!(state->mCommand & FastCaptureState::IDLE)) {
6519 state->mCommand = FastCaptureState::COLD_IDLE;
6520 state->mColdFutexAddr = &mFastCaptureFutex;
6521 state->mColdGen++;
6522 mFastCaptureFutex = 0;
6523 sq->end();
6524 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6525 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6526#if 0
6527 if (kUseFastCapture == FastCapture_Dynamic) {
6528 // FIXME
6529 }
6530#endif
6531#ifdef AUDIO_WATCHDOG
6532 // FIXME
6533#endif
6534 } else {
6535 sq->end(false /*didModify*/);
6536 }
6537 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006538 status_t result = mInput->stream->standby();
6539 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006540
6541 // If going into standby, flush the pipe source.
6542 if (mPipeSource.get() != nullptr) {
6543 const ssize_t flushed = mPipeSource->flush();
6544 if (flushed > 0) {
6545 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6546 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6547 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6548 }
6549 }
Eric Laurent81784c32012-11-19 14:55:58 -08006550}
6551
Glenn Kasten05997e22014-03-13 15:08:33 -07006552// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006553sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006554 const sp<AudioFlinger::Client>& client,
6555 uint32_t sampleRate,
6556 audio_format_t format,
6557 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006558 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006559 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006560 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006561 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006562 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006563 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006564 status_t *status,
6565 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006566{
Glenn Kasten74935e42013-12-19 08:56:45 -08006567 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006568 sp<RecordTrack> track;
6569 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006570 audio_input_flags_t inputFlags = mInput->flags;
6571
6572 // special case for FAST flag considered OK if fast capture is present
6573 if (hasFastCapture()) {
6574 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6575 }
6576
6577 // Check if requested flags are compatible with output stream flags
6578 if ((*flags & inputFlags) != *flags) {
6579 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6580 " input flags (%08x)",
6581 *flags, inputFlags);
6582 *flags = (audio_input_flags_t)(*flags & inputFlags);
6583 }
Eric Laurent81784c32012-11-19 14:55:58 -08006584
Glenn Kasten90e58b12013-07-31 16:16:02 -07006585 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006586 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006587 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006588 // we formerly checked for a callback handler (non-0 tid),
6589 // but that is no longer required for TRANSFER_OBTAIN mode
6590 //
Glenn Kasten74105912014-07-03 12:28:53 -07006591 // frame count is not specified, or is exactly the pipe depth
6592 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006593 // PCM data
6594 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006595 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006596 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006597 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006598 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006599 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006600 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006601 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006602 hasFastCapture() &&
6603 // there are sufficient fast track slots available
6604 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006605 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006606 // check compatibility with audio effects.
6607 Mutex::Autolock _l(mLock);
6608 // Do not accept FAST flag if the session has software effects
6609 sp<EffectChain> chain = getEffectChain_l(sessionId);
6610 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006611 audio_input_flags_t old = *flags;
6612 chain->checkInputFlagCompatibility(flags);
6613 if (old != *flags) {
6614 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6615 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006616 }
6617 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006618 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006619 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6620 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006621 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006622 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006623 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006624 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006625 frameCount, mFrameCount, mPipeFramesP2,
6626 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6627 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006628 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006629 }
6630 }
6631
6632 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006633 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006634 // fast track: frame count is exactly the pipe depth
6635 frameCount = mPipeFramesP2;
6636 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6637 *notificationFrames = mFrameCount;
6638 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006639 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6640 // or 20 ms if there is a fast capture
6641 // TODO This could be a roundupRatio inline, and const
6642 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6643 * sampleRate + mSampleRate - 1) / mSampleRate;
6644 // minimum number of notification periods is at least kMinNotifications,
6645 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6646 static const size_t kMinNotifications = 3;
6647 static const uint32_t kMinMs = 30;
6648 // TODO This could be a roundupRatio inline
6649 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6650 // TODO This could be a roundupRatio inline
6651 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6652 maxNotificationFrames;
6653 const size_t minFrameCount = maxNotificationFrames *
6654 max(kMinNotifications, minNotificationsByMs);
6655 frameCount = max(frameCount, minFrameCount);
6656 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6657 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006658 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006659 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006660 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006661
Glenn Kasten15e57982013-09-24 11:52:37 -07006662 lStatus = initCheck();
6663 if (lStatus != NO_ERROR) {
6664 ALOGE("createRecordTrack_l() audio driver not initialized");
6665 goto Exit;
6666 }
Eric Laurent81784c32012-11-19 14:55:58 -08006667
6668 { // scope for mLock
6669 Mutex::Autolock _l(mLock);
6670
6671 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006672 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006673 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006674
Glenn Kasten03003332013-08-06 15:40:54 -07006675 lStatus = track->initCheck();
6676 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006677 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006678 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006679 goto Exit;
6680 }
6681 mTracks.add(track);
6682
6683 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6684 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6685 mAudioFlinger->btNrecIsOff();
6686 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6687 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006688
Eric Laurent05067782016-06-01 18:27:28 -07006689 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006690 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6691 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6692 // so ask activity manager to do this on our behalf
Mikhail Naganov83f04272017-02-07 10:45:09 -08006693 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006694 }
Eric Laurent81784c32012-11-19 14:55:58 -08006695 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006696
Eric Laurent81784c32012-11-19 14:55:58 -08006697 lStatus = NO_ERROR;
6698
6699Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006700 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006701 return track;
6702}
6703
6704status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6705 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006706 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006707{
6708 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6709 sp<ThreadBase> strongMe = this;
6710 status_t status = NO_ERROR;
6711
6712 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006713 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006714 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006715 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006716 triggerSession,
6717 recordTrack->sessionId(),
6718 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006719 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006720 // Sync event can be cancelled by the trigger session if the track is not in a
6721 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006722 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006723 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006724 } else {
6725 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006726 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006727 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006728 }
6729 }
6730
6731 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006732 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006733 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006734 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6735 if (recordTrack->mState == TrackBase::PAUSING) {
6736 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006737 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006738 } else {
6739 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006740 }
6741 return status;
6742 }
6743
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006744 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6745 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6746 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006747 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006748 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006749 status_t status = NO_ERROR;
6750 if (recordTrack->isExternalTrack()) {
6751 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006752 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006753 mLock.lock();
6754 // FIXME should verify that recordTrack is still in mActiveTracks
6755 if (status != NO_ERROR) {
6756 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006757 recordTrack->clearSyncStartEvent();
6758 ALOGV("RecordThread::start error %d", status);
6759 return status;
6760 }
Eric Laurent81784c32012-11-19 14:55:58 -08006761 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006762 // Catch up with current buffer indices if thread is already running.
6763 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6764 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6765 // see previously buffered data before it called start(), but with greater risk of overrun.
6766
Andy Hung73c02e42015-03-29 01:13:58 -07006767 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006768 // clear any converter state as new data will be discontinuous
6769 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006770 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006771 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006772 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006773 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006774 ALOGV("Record failed to start");
6775 status = BAD_VALUE;
6776 goto startError;
6777 }
Eric Laurent81784c32012-11-19 14:55:58 -08006778 return status;
6779 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006780
Eric Laurent81784c32012-11-19 14:55:58 -08006781startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006782 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006783 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006784 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006785 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006786 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006787 return status;
6788}
6789
Eric Laurent81784c32012-11-19 14:55:58 -08006790void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6791{
6792 sp<SyncEvent> strongEvent = event.promote();
6793
6794 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006795 sp<RefBase> ptr = strongEvent->cookie().promote();
6796 if (ptr != 0) {
6797 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6798 recordTrack->handleSyncStartEvent(strongEvent);
6799 }
Eric Laurent81784c32012-11-19 14:55:58 -08006800 }
6801}
6802
Glenn Kastena8356f62013-07-25 14:37:52 -07006803bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006804 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006805 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006806 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006807 return false;
6808 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006809 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006810 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006811 // signal thread to stop
6812 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006813 // do not wait for mStartStopCond if exiting
6814 if (exitPending()) {
6815 return true;
6816 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006817 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006818 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006819 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006820 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006821 ALOGV("Record stopped OK");
6822 return true;
6823 }
6824 return false;
6825}
6826
Glenn Kasten0f11b512014-01-31 16:18:54 -08006827bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006828{
6829 return false;
6830}
6831
Glenn Kasten0f11b512014-01-31 16:18:54 -08006832status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006833{
6834#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6835 if (!isValidSyncEvent(event)) {
6836 return BAD_VALUE;
6837 }
6838
Glenn Kastend848eb42016-03-08 13:42:11 -08006839 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006840 status_t ret = NAME_NOT_FOUND;
6841
6842 Mutex::Autolock _l(mLock);
6843
6844 for (size_t i = 0; i < mTracks.size(); i++) {
6845 sp<RecordTrack> track = mTracks[i];
6846 if (eventSession == track->sessionId()) {
6847 (void) track->setSyncEvent(event);
6848 ret = NO_ERROR;
6849 }
6850 }
6851 return ret;
6852#else
6853 return BAD_VALUE;
6854#endif
6855}
6856
6857// destroyTrack_l() must be called with ThreadBase::mLock held
6858void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6859{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006860 track->terminate();
6861 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006862 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006863 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006864 removeTrack_l(track);
6865 }
6866}
6867
6868void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6869{
6870 mTracks.remove(track);
6871 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006872 if (track->isFastTrack()) {
6873 ALOG_ASSERT(!mFastTrackAvail);
6874 mFastTrackAvail = true;
6875 }
Eric Laurent81784c32012-11-19 14:55:58 -08006876}
6877
6878void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6879{
6880 dumpInternals(fd, args);
6881 dumpTracks(fd, args);
6882 dumpEffectChains(fd, args);
6883}
6884
6885void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6886{
Glenn Kasten44182c22015-03-05 17:12:23 -08006887 dumpBase(fd, args);
6888
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006889 AudioStreamIn *input = mInput;
6890 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6891 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6892 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006893 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006894 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006895 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006896 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006897 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006898
Glenn Kasten2f90c512015-12-02 11:40:09 -08006899 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6900 // while we are dumping it. It may be inconsistent, but it won't mutate!
6901 // This is a large object so we place it on the heap.
6902 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6903 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6904 copy->dump(fd);
6905 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006906}
6907
Glenn Kasten0f11b512014-01-31 16:18:54 -08006908void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006909{
6910 const size_t SIZE = 256;
6911 char buffer[SIZE];
6912 String8 result;
6913
Marco Nelissenb2208842014-02-07 14:00:50 -08006914 size_t numtracks = mTracks.size();
6915 size_t numactive = mActiveTracks.size();
6916 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006917 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006918 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006919 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006920 RecordTrack::appendDumpHeader(result);
6921 for (size_t i = 0; i < numtracks ; ++i) {
6922 sp<RecordTrack> track = mTracks[i];
6923 if (track != 0) {
6924 bool active = mActiveTracks.indexOf(track) >= 0;
6925 if (active) {
6926 numactiveseen++;
6927 }
6928 track->dump(buffer, SIZE, active);
6929 result.append(buffer);
6930 }
Eric Laurent81784c32012-11-19 14:55:58 -08006931 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006932 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006933 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006934 }
6935
Marco Nelissenb2208842014-02-07 14:00:50 -08006936 if (numactiveseen != numactive) {
6937 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6938 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006939 result.append(buffer);
6940 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006941 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006942 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006943 if (mTracks.indexOf(track) < 0) {
6944 track->dump(buffer, SIZE, true);
6945 result.append(buffer);
6946 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006947 }
Eric Laurent81784c32012-11-19 14:55:58 -08006948
6949 }
6950 write(fd, result.string(), result.size());
6951}
6952
Andy Hung73c02e42015-03-29 01:13:58 -07006953
6954void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6955{
6956 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6957 RecordThread *recordThread = (RecordThread *) threadBase.get();
6958 mRsmpInFront = recordThread->mRsmpInRear;
6959 mRsmpInUnrel = 0;
6960}
6961
6962void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6963 size_t *framesAvailable, bool *hasOverrun)
6964{
6965 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6966 RecordThread *recordThread = (RecordThread *) threadBase.get();
6967 const int32_t rear = recordThread->mRsmpInRear;
6968 const int32_t front = mRsmpInFront;
6969 const ssize_t filled = rear - front;
6970
6971 size_t framesIn;
6972 bool overrun = false;
6973 if (filled < 0) {
6974 // should not happen, but treat like a massive overrun and re-sync
6975 framesIn = 0;
6976 mRsmpInFront = rear;
6977 overrun = true;
6978 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6979 framesIn = (size_t) filled;
6980 } else {
6981 // client is not keeping up with server, but give it latest data
6982 framesIn = recordThread->mRsmpInFrames;
6983 mRsmpInFront = /* front = */ rear - framesIn;
6984 overrun = true;
6985 }
6986 if (framesAvailable != NULL) {
6987 *framesAvailable = framesIn;
6988 }
6989 if (hasOverrun != NULL) {
6990 *hasOverrun = overrun;
6991 }
6992}
6993
Eric Laurent81784c32012-11-19 14:55:58 -08006994// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006995status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006996 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006997{
Andy Hung73c02e42015-03-29 01:13:58 -07006998 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006999 if (threadBase == 0) {
7000 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007001 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007002 return NOT_ENOUGH_DATA;
7003 }
7004 RecordThread *recordThread = (RecordThread *) threadBase.get();
7005 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007006 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007007 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007008 // FIXME should not be P2 (don't want to increase latency)
7009 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007010 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007011 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007012 front &= recordThread->mRsmpInFramesP2 - 1;
7013 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007014 if (part1 > (size_t) filled) {
7015 part1 = filled;
7016 }
7017 size_t ask = buffer->frameCount;
7018 ALOG_ASSERT(ask > 0);
7019 if (part1 > ask) {
7020 part1 = ask;
7021 }
7022 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007023 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007024 buffer->raw = NULL;
7025 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007026 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007027 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007028 }
7029
Andy Hung57446612015-04-19 23:56:46 -07007030 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007031 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007032 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007033 return NO_ERROR;
7034}
7035
7036// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007037void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7038 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007039{
Glenn Kasten85948432013-08-19 12:09:05 -07007040 size_t stepCount = buffer->frameCount;
7041 if (stepCount == 0) {
7042 return;
7043 }
Andy Hung73c02e42015-03-29 01:13:58 -07007044 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7045 mRsmpInUnrel -= stepCount;
7046 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007047 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007048 buffer->frameCount = 0;
7049}
7050
Andy Hung97a893e2015-03-29 01:03:07 -07007051
Eric Laurent10351942014-05-08 18:49:52 -07007052bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7053 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007054{
7055 bool reconfig = false;
7056
Eric Laurent10351942014-05-08 18:49:52 -07007057 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007058
Eric Laurent10351942014-05-08 18:49:52 -07007059 audio_format_t reqFormat = mFormat;
7060 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007061 // 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 -07007062 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7063
7064 AudioParameter param = AudioParameter(keyValuePair);
7065 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007066
7067 // scope for AutoPark extends to end of method
7068 AutoPark<FastCapture> park(mFastCapture);
7069
Eric Laurent10351942014-05-08 18:49:52 -07007070 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7071 // channel count change can be requested. Do we mandate the first client defines the
7072 // HAL sampling rate and channel count or do we allow changes on the fly?
7073 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7074 samplingRate = value;
7075 reconfig = true;
7076 }
7077 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007078 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007079 status = BAD_VALUE;
7080 } else {
7081 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007082 reconfig = true;
7083 }
Eric Laurent10351942014-05-08 18:49:52 -07007084 }
7085 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7086 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007087 if (!audio_is_input_channel(mask) ||
7088 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007089 status = BAD_VALUE;
7090 } else {
7091 channelMask = mask;
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::keyFrameCount), value) == NO_ERROR) {
7096 // do not accept frame count changes if tracks are open as the track buffer
7097 // size depends on frame count and correct behavior would not be guaranteed
7098 // if frame count is changed after track creation
7099 if (mActiveTracks.size() > 0) {
7100 status = INVALID_OPERATION;
7101 } else {
7102 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007103 }
Eric Laurent10351942014-05-08 18:49:52 -07007104 }
7105 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7106 // forward device change to effects that have requested to be
7107 // aware of attached audio device.
7108 for (size_t i = 0; i < mEffectChains.size(); i++) {
7109 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007110 }
Eric Laurent81784c32012-11-19 14:55:58 -08007111
Eric Laurent10351942014-05-08 18:49:52 -07007112 // store input device and output device but do not forward output device to audio HAL.
7113 // Note that status is ignored by the caller for output device
7114 // (see AudioFlinger::setParameters()
7115 if (audio_is_output_devices(value)) {
7116 mOutDevice = value;
7117 status = BAD_VALUE;
7118 } else {
7119 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007120 if (value != AUDIO_DEVICE_NONE) {
7121 mPrevInDevice = value;
7122 }
Eric Laurent10351942014-05-08 18:49:52 -07007123 // disable AEC and NS if the device is a BT SCO headset supporting those
7124 // pre processings
7125 if (mTracks.size() > 0) {
7126 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7127 mAudioFlinger->btNrecIsOff();
7128 for (size_t i = 0; i < mTracks.size(); i++) {
7129 sp<RecordTrack> track = mTracks[i];
7130 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7131 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007132 }
7133 }
7134 }
Eric Laurent10351942014-05-08 18:49:52 -07007135 }
7136 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7137 mAudioSource != (audio_source_t)value) {
7138 // forward device change to effects that have requested to be
7139 // aware of attached audio device.
7140 for (size_t i = 0; i < mEffectChains.size(); i++) {
7141 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007142 }
Eric Laurent10351942014-05-08 18:49:52 -07007143 mAudioSource = (audio_source_t)value;
7144 }
Glenn Kastene198c362013-08-13 09:13:36 -07007145
Eric Laurent10351942014-05-08 18:49:52 -07007146 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007147 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007148 if (status == INVALID_OPERATION) {
7149 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007150 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007151 }
7152 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007153 if (status == BAD_VALUE) {
7154 uint32_t sRate;
7155 audio_channel_mask_t channelMask;
7156 audio_format_t format;
7157 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7158 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7159 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7160 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7161 status = NO_ERROR;
7162 }
Eric Laurent81784c32012-11-19 14:55:58 -08007163 }
Eric Laurent10351942014-05-08 18:49:52 -07007164 if (status == NO_ERROR) {
7165 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007166 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007167 }
7168 }
Eric Laurent81784c32012-11-19 14:55:58 -08007169 }
Eric Laurent10351942014-05-08 18:49:52 -07007170
Eric Laurent81784c32012-11-19 14:55:58 -08007171 return reconfig;
7172}
7173
7174String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7175{
Eric Laurent81784c32012-11-19 14:55:58 -08007176 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007177 if (initCheck() == NO_ERROR) {
7178 String8 out_s8;
7179 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7180 return out_s8;
7181 }
Eric Laurent81784c32012-11-19 14:55:58 -08007182 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007183 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007184}
7185
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007186void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007187 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7188
7189 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007190
7191 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007192 case AUDIO_INPUT_OPENED:
7193 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007194 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007195 desc->mChannelMask = mChannelMask;
7196 desc->mSamplingRate = mSampleRate;
7197 desc->mFormat = mFormat;
7198 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007199 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007200 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007201 break;
7202
Eric Laurent73e26b62015-04-27 16:55:58 -07007203 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007204 default:
7205 break;
7206 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007207 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007208}
7209
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007210void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007211{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007212 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7213 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007214 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007215 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007216 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007217 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7218 result = mInput->stream->getFrameSize(&mFrameSize);
7219 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7220 result = mInput->stream->getBufferSize(&mBufferSize);
7221 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007222 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007223 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007224 // 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 -07007225 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007226 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007227 // A larger value should allow more old data to be read after a track calls start(),
7228 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007229 //
7230 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007231 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007232 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007233 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007234 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007235
7236 // TODO optimize audio capture buffer sizes ...
7237 // Here we calculate the size of the sliding buffer used as a source
7238 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7239 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7240 // be better to have it derived from the pipe depth in the long term.
7241 // The current value is higher than necessary. However it should not add to latency.
7242
Glenn Kasten85948432013-08-19 12:09:05 -07007243 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007244 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7245 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007246 // if posix_memalign fails, will segv here.
7247 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007248
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007249 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7250 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007251}
7252
Glenn Kasten5f972c02014-01-13 09:59:31 -08007253uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007254{
7255 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007256 uint32_t result;
7257 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7258 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007259 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007260 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007261}
7262
Eric Laurent4c415062016-06-17 16:14:16 -07007263// hasAudioSession_l() must be called with ThreadBase::mLock held
7264uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007265{
Eric Laurent81784c32012-11-19 14:55:58 -08007266 uint32_t result = 0;
7267 if (getEffectChain_l(sessionId) != 0) {
7268 result = EFFECT_SESSION;
7269 }
7270
7271 for (size_t i = 0; i < mTracks.size(); ++i) {
7272 if (sessionId == mTracks[i]->sessionId()) {
7273 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007274 if (mTracks[i]->isFastTrack()) {
7275 result |= FAST_SESSION;
7276 }
Eric Laurent81784c32012-11-19 14:55:58 -08007277 break;
7278 }
7279 }
7280
7281 return result;
7282}
7283
Glenn Kastend848eb42016-03-08 13:42:11 -08007284KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007285{
Glenn Kastend848eb42016-03-08 13:42:11 -08007286 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007287 Mutex::Autolock _l(mLock);
7288 for (size_t j = 0; j < mTracks.size(); ++j) {
7289 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007290 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007291 if (ids.indexOfKey(sessionId) < 0) {
7292 ids.add(sessionId, true);
7293 }
7294 }
7295 return ids;
7296}
7297
7298AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7299{
7300 Mutex::Autolock _l(mLock);
7301 AudioStreamIn *input = mInput;
7302 mInput = NULL;
7303 return input;
7304}
7305
7306// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007307sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007308{
7309 if (mInput == NULL) {
7310 return NULL;
7311 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007312 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007313}
7314
7315status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7316{
7317 // only one chain per input thread
7318 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007319 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007320 return INVALID_OPERATION;
7321 }
7322 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007323 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007324 chain->setInBuffer(NULL);
7325 chain->setOutBuffer(NULL);
7326
7327 checkSuspendOnAddEffectChain_l(chain);
7328
Eric Laurent1b928682014-10-02 19:41:47 -07007329 // make sure enabled pre processing effects state is communicated to the HAL as we
7330 // just moved them to a new input stream.
7331 chain->syncHalEffectsState();
7332
Eric Laurent81784c32012-11-19 14:55:58 -08007333 mEffectChains.add(chain);
7334
7335 return NO_ERROR;
7336}
7337
7338size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7339{
7340 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7341 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007342 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007343 chain.get(), mEffectChains.size(), this);
7344 if (mEffectChains.size() == 1) {
7345 mEffectChains.removeAt(0);
7346 }
7347 return 0;
7348}
7349
Eric Laurent1c333e22014-05-20 10:48:17 -07007350status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7351 audio_patch_handle_t *handle)
7352{
7353 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007354
7355 // store new device and send to effects
7356 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007357 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007358 for (size_t i = 0; i < mEffectChains.size(); i++) {
7359 mEffectChains[i]->setDevice_l(mInDevice);
7360 }
7361
7362 // disable AEC and NS if the device is a BT SCO headset supporting those
7363 // pre processings
7364 if (mTracks.size() > 0) {
7365 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7366 mAudioFlinger->btNrecIsOff();
7367 for (size_t i = 0; i < mTracks.size(); i++) {
7368 sp<RecordTrack> track = mTracks[i];
7369 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7370 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7371 }
7372 }
7373
7374 // store new source and send to effects
7375 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7376 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007377 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007378 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007379 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007380 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007381
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007382 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007383 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7384 status = hwDevice->createAudioPatch(patch->num_sources,
7385 patch->sources,
7386 patch->num_sinks,
7387 patch->sinks,
7388 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007389 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007390 char *address;
7391 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7392 address = audio_device_address_to_parameter(
7393 patch->sources[0].ext.device.type,
7394 patch->sources[0].ext.device.address);
7395 } else {
7396 address = (char *)calloc(1, 1);
7397 }
7398 AudioParameter param = AudioParameter(String8(address));
7399 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007400 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007401 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007402 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007403 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007404 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007405 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007406 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007407
Eric Laurente8726fe2015-06-26 09:39:24 -07007408 if (mInDevice != mPrevInDevice) {
7409 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7410 mPrevInDevice = mInDevice;
7411 }
Eric Laurent296fb132015-05-01 11:38:42 -07007412
Eric Laurent1c333e22014-05-20 10:48:17 -07007413 return status;
7414}
7415
7416status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7417{
7418 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007419
7420 mInDevice = AUDIO_DEVICE_NONE;
7421
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007422 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007423 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7424 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007425 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007426 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007427 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007428 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007429 }
7430 return status;
7431}
7432
Eric Laurent83b88082014-06-20 18:31:16 -07007433void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7434{
7435 Mutex::Autolock _l(mLock);
7436 mTracks.add(record);
7437}
7438
7439void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7440{
7441 Mutex::Autolock _l(mLock);
7442 destroyTrack_l(record);
7443}
7444
7445void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7446{
7447 ThreadBase::getAudioPortConfig(config);
7448 config->role = AUDIO_PORT_ROLE_SINK;
7449 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7450 config->ext.mix.usecase.source = mAudioSource;
7451}
Eric Laurent1c333e22014-05-20 10:48:17 -07007452
Eric Laurent6acd1d42017-01-04 14:23:29 -08007453// ----------------------------------------------------------------------------
7454// Mmap
7455// ----------------------------------------------------------------------------
7456
7457AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7458 : mThread(thread)
7459{
7460}
7461
7462AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7463{
7464 MmapThread *thread = mThread.get();
7465 // clear our strong reference before disconnecting the thread: the last strong reference
Eric Laurent18b57012017-02-13 16:23:52 -08007466 // will be removed when closeInput/closeOutput is executed upon call from audio policy manager
Eric Laurent6acd1d42017-01-04 14:23:29 -08007467 // and the thread removed from mMMapThreads list causing the thread destruction.
7468 mThread.clear();
7469 if (thread != nullptr) {
7470 thread->disconnect();
7471 }
7472}
7473
7474status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7475 struct audio_mmap_buffer_info *info)
7476{
7477 if (mThread == 0) {
7478 return NO_INIT;
7479 }
7480 return mThread->createMmapBuffer(minSizeFrames, info);
7481}
7482
7483status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7484{
7485 if (mThread == 0) {
7486 return NO_INIT;
7487 }
7488 return mThread->getMmapPosition(position);
7489}
7490
Glenn Kastend3bb6452016-12-05 18:14:37 -08007491status_t AudioFlinger::MmapThreadHandle::start(const MmapStreamInterface::Client& client,
7492 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007493
7494{
7495 if (mThread == 0) {
7496 return NO_INIT;
7497 }
7498 return mThread->start(client, handle);
7499}
7500
7501status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7502{
7503 if (mThread == 0) {
7504 return NO_INIT;
7505 }
7506 return mThread->stop(handle);
7507}
7508
Eric Laurent18b57012017-02-13 16:23:52 -08007509status_t AudioFlinger::MmapThreadHandle::standby()
7510{
7511 if (mThread == 0) {
7512 return NO_INIT;
7513 }
7514 return mThread->standby();
7515}
7516
Eric Laurent6acd1d42017-01-04 14:23:29 -08007517
7518AudioFlinger::MmapThread::MmapThread(
7519 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7520 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7521 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7522 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
7523 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev)
7524{
Eric Laurent18b57012017-02-13 16:23:52 -08007525 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007526 readHalParameters_l();
7527}
7528
7529AudioFlinger::MmapThread::~MmapThread()
7530{
Eric Laurent18b57012017-02-13 16:23:52 -08007531 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007532}
7533
7534void AudioFlinger::MmapThread::onFirstRef()
7535{
7536 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7537}
7538
7539void AudioFlinger::MmapThread::disconnect()
7540{
7541 for (const sp<MmapTrack> &t : mActiveTracks) {
7542 stop(t->portId());
7543 }
7544 // this will cause the destruction of this thread.
7545 if (isOutput()) {
7546 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7547 } else {
7548 AudioSystem::releaseInput(mId, mSessionId);
7549 }
7550}
7551
7552
7553void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7554 audio_stream_type_t streamType __unused,
7555 audio_session_t sessionId,
7556 const sp<MmapStreamCallback>& callback,
7557 audio_port_handle_t portId)
7558{
7559 mAttr = *attr;
7560 mSessionId = sessionId;
7561 mCallback = callback;
7562 mPortId = portId;
7563}
7564
7565status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7566 struct audio_mmap_buffer_info *info)
7567{
7568 if (mHalStream == 0) {
7569 return NO_INIT;
7570 }
Eric Laurent18b57012017-02-13 16:23:52 -08007571 mStandby = true;
7572 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007573 return mHalStream->createMmapBuffer(minSizeFrames, info);
7574}
7575
7576status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7577{
7578 if (mHalStream == 0) {
7579 return NO_INIT;
7580 }
7581 return mHalStream->getMmapPosition(position);
7582}
7583
7584status_t AudioFlinger::MmapThread::start(const MmapStreamInterface::Client& client,
7585 audio_port_handle_t *handle)
7586{
Eric Laurent18b57012017-02-13 16:23:52 -08007587 ALOGV("%s clientUid %d mStandby %d", __FUNCTION__, client.clientUid, mStandby);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007588 if (mHalStream == 0) {
7589 return NO_INIT;
7590 }
7591
7592 status_t ret;
7593 audio_session_t sessionId;
7594 audio_port_handle_t portId;
7595
7596 if (mActiveTracks.size() == 0) {
7597 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007598 ret = mHalStream->start();
7599 if (ret != NO_ERROR) {
7600 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7601 return ret;
7602 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08007603 portId = mPortId;
7604 sessionId = mSessionId;
Eric Laurent18b57012017-02-13 16:23:52 -08007605 mStandby = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007606 } else {
7607 // for other tracks than first one, get a new port ID from APM.
7608 sessionId = (audio_session_t)mAudioFlinger->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
7609 audio_io_handle_t io;
7610 if (isOutput()) {
7611 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7612 config.sample_rate = mSampleRate;
7613 config.channel_mask = mChannelMask;
7614 config.format = mFormat;
7615 audio_stream_type_t stream = streamType();
7616 audio_output_flags_t flags =
7617 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
7618 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7619 sessionId,
7620 &stream,
7621 client.clientUid,
7622 &config,
7623 flags,
7624 AUDIO_PORT_HANDLE_NONE,
7625 &portId);
7626 } else {
7627 audio_config_base_t config;
7628 config.sample_rate = mSampleRate;
7629 config.channel_mask = mChannelMask;
7630 config.format = mFormat;
7631 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7632 sessionId,
7633 client.clientPid,
7634 client.clientUid,
7635 &config,
7636 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7637 AUDIO_PORT_HANDLE_NONE,
7638 &portId);
7639 }
7640 // APM should not chose a different input or output stream for the same set of attributes
7641 // and audo configuration
7642 if (ret != NO_ERROR || io != mId) {
7643 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7644 __FUNCTION__, ret, io, mId);
7645 return BAD_VALUE;
7646 }
7647 }
7648
7649 if (isOutput()) {
7650 ret = AudioSystem::startOutput(mId, streamType(), sessionId);
7651 } else {
7652 ret = AudioSystem::startInput(mId, sessionId);
7653 }
7654
7655 // abort if start is rejected by audio policy manager
7656 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007657 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007658 if (mActiveTracks.size() != 0) {
7659 if (isOutput()) {
7660 AudioSystem::releaseOutput(mId, streamType(), sessionId);
7661 } else {
7662 AudioSystem::releaseInput(mId, sessionId);
7663 }
Eric Laurent18b57012017-02-13 16:23:52 -08007664 } else {
7665 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007666 }
7667 return PERMISSION_DENIED;
7668 }
7669
7670 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, sessionId,
7671 client.clientUid, portId);
7672
7673 mActiveTracks.add(track);
7674 sp<EffectChain> chain = getEffectChain_l(sessionId);
7675 if (chain != 0) {
7676 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7677 chain->incTrackCnt();
7678 chain->incActiveTrackCnt();
7679 }
7680
7681 *handle = portId;
7682
7683 broadcast_l();
7684
Eric Laurent18b57012017-02-13 16:23:52 -08007685 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, portId, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007686
7687 return NO_ERROR;
7688}
7689
7690status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7691{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007692 ALOGV("%s handle %d", __FUNCTION__, handle);
7693
7694 if (mHalStream == 0) {
7695 return NO_INIT;
7696 }
7697
7698 sp<MmapTrack> track;
7699 for (const sp<MmapTrack> &t : mActiveTracks) {
7700 if (handle == t->portId()) {
7701 track = t;
7702 break;
7703 }
7704 }
7705 if (track == 0) {
7706 return BAD_VALUE;
7707 }
7708
7709 mActiveTracks.remove(track);
7710
7711 if (isOutput()) {
7712 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
7713 if (mActiveTracks.size() != 0) {
7714 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
7715 }
7716 } else {
7717 AudioSystem::stopInput(mId, track->sessionId());
7718 if (mActiveTracks.size() != 0) {
7719 AudioSystem::releaseInput(mId, track->sessionId());
7720 }
7721 }
7722
7723 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7724 if (chain != 0) {
7725 chain->decActiveTrackCnt();
7726 chain->decTrackCnt();
7727 }
7728
7729 broadcast_l();
7730
7731 if (mActiveTracks.size() == 0) {
7732 mHalStream->stop();
7733 }
7734 return NO_ERROR;
7735}
7736
Eric Laurent18b57012017-02-13 16:23:52 -08007737status_t AudioFlinger::MmapThread::standby()
7738{
7739 ALOGV("%s", __FUNCTION__);
7740
7741 if (mHalStream == 0) {
7742 return NO_INIT;
7743 }
7744 if (mActiveTracks.size() != 0) {
7745 return INVALID_OPERATION;
7746 }
7747 mHalStream->standby();
7748 mStandby = true;
7749 releaseWakeLock();
7750 return NO_ERROR;
7751}
7752
Eric Laurent6acd1d42017-01-04 14:23:29 -08007753
7754void AudioFlinger::MmapThread::readHalParameters_l()
7755{
7756 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7757 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7758 mFormat = mHALFormat;
7759 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7760 result = mHalStream->getFrameSize(&mFrameSize);
7761 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7762 result = mHalStream->getBufferSize(&mBufferSize);
7763 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7764 mFrameCount = mBufferSize / mFrameSize;
7765}
7766
7767bool AudioFlinger::MmapThread::threadLoop()
7768{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007769 checkSilentMode_l();
7770
7771 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7772
7773 while (!exitPending())
7774 {
7775 Mutex::Autolock _l(mLock);
7776 Vector< sp<EffectChain> > effectChains;
7777
7778 if (mSignalPending) {
7779 // A signal was raised while we were unlocked
7780 mSignalPending = false;
7781 } else {
7782 if (mConfigEvents.isEmpty()) {
7783 // we're about to wait, flush the binder command buffer
7784 IPCThreadState::self()->flushCommands();
7785
7786 if (exitPending()) {
7787 break;
7788 }
7789
Eric Laurent6acd1d42017-01-04 14:23:29 -08007790 // wait until we have something to do...
7791 ALOGV("%s going to sleep", myName.string());
7792 mWaitWorkCV.wait(mLock);
7793 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007794
7795 checkSilentMode_l();
7796
7797 continue;
7798 }
7799 }
7800
7801 processConfigEvents_l();
7802
7803 processVolume_l();
7804
7805 checkInvalidTracks_l();
7806
7807 mActiveTracks.updatePowerState(this);
7808
7809 lockEffectChains_l(effectChains);
7810 for (size_t i = 0; i < effectChains.size(); i ++) {
7811 effectChains[i]->process_l();
7812 }
7813 // enable changes in effect chain
7814 unlockEffectChains(effectChains);
7815 // Effect chains will be actually deleted here if they were removed from
7816 // mEffectChains list during mixing or effects processing
7817 }
7818
7819 threadLoop_exit();
7820
7821 if (!mStandby) {
7822 threadLoop_standby();
7823 mStandby = true;
7824 }
7825
Eric Laurent6acd1d42017-01-04 14:23:29 -08007826 ALOGV("Thread %p type %d exiting", this, mType);
7827 return false;
7828}
7829
7830// checkForNewParameter_l() must be called with ThreadBase::mLock held
7831bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7832 status_t& status)
7833{
7834 AudioParameter param = AudioParameter(keyValuePair);
7835 int value;
7836 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7837 // forward device change to effects that have requested to be
7838 // aware of attached audio device.
7839 if (value != AUDIO_DEVICE_NONE) {
7840 mOutDevice = value;
7841 for (size_t i = 0; i < mEffectChains.size(); i++) {
7842 mEffectChains[i]->setDevice_l(mOutDevice);
7843 }
7844 }
7845 }
7846 status = mHalStream->setParameters(keyValuePair);
7847
7848 return false;
7849}
7850
7851String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7852{
7853 Mutex::Autolock _l(mLock);
7854 String8 out_s8;
7855 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7856 return out_s8;
7857 }
7858 return String8();
7859}
7860
7861void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7862 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7863
7864 desc->mIoHandle = mId;
7865
7866 switch (event) {
7867 case AUDIO_INPUT_OPENED:
7868 case AUDIO_INPUT_CONFIG_CHANGED:
7869 case AUDIO_OUTPUT_OPENED:
7870 case AUDIO_OUTPUT_CONFIG_CHANGED:
7871 desc->mPatch = mPatch;
7872 desc->mChannelMask = mChannelMask;
7873 desc->mSamplingRate = mSampleRate;
7874 desc->mFormat = mFormat;
7875 desc->mFrameCount = mFrameCount;
7876 desc->mFrameCountHAL = mFrameCount;
7877 desc->mLatency = 0;
7878 break;
7879
7880 case AUDIO_INPUT_CLOSED:
7881 case AUDIO_OUTPUT_CLOSED:
7882 default:
7883 break;
7884 }
7885 mAudioFlinger->ioConfigChanged(event, desc, pid);
7886}
7887
7888status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7889 audio_patch_handle_t *handle)
7890{
7891 status_t status = NO_ERROR;
7892
7893 // store new device and send to effects
7894 audio_devices_t type = AUDIO_DEVICE_NONE;
7895 audio_port_handle_t deviceId;
7896 if (isOutput()) {
7897 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7898 type |= patch->sinks[i].ext.device.type;
7899 }
7900 deviceId = patch->sinks[0].id;
7901 } else {
7902 type = patch->sources[0].ext.device.type;
7903 deviceId = patch->sources[0].id;
7904 }
7905
7906 for (size_t i = 0; i < mEffectChains.size(); i++) {
7907 mEffectChains[i]->setDevice_l(type);
7908 }
7909
7910 if (isOutput()) {
7911 mOutDevice = type;
7912 } else {
7913 mInDevice = type;
7914 // store new source and send to effects
7915 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7916 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7917 for (size_t i = 0; i < mEffectChains.size(); i++) {
7918 mEffectChains[i]->setAudioSource_l(mAudioSource);
7919 }
7920 }
7921 }
7922
7923 if (mAudioHwDev->supportsAudioPatches()) {
7924 status = mHalDevice->createAudioPatch(patch->num_sources,
7925 patch->sources,
7926 patch->num_sinks,
7927 patch->sinks,
7928 handle);
7929 } else {
7930 char *address;
7931 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7932 //FIXME: we only support address on first sink with HAL version < 3.0
7933 address = audio_device_address_to_parameter(
7934 patch->sinks[0].ext.device.type,
7935 patch->sinks[0].ext.device.address);
7936 } else {
7937 address = (char *)calloc(1, 1);
7938 }
7939 AudioParameter param = AudioParameter(String8(address));
7940 free(address);
7941 param.addInt(String8(AudioParameter::keyRouting), (int)type);
7942 if (!isOutput()) {
7943 param.addInt(String8(AudioParameter::keyInputSource),
7944 (int)patch->sinks[0].ext.mix.usecase.source);
7945 }
7946 status = mHalStream->setParameters(param.toString());
7947 *handle = AUDIO_PATCH_HANDLE_NONE;
7948 }
7949
7950 if (isOutput() && mPrevOutDevice != mOutDevice) {
7951 mPrevOutDevice = type;
7952 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08007953 sp<MmapStreamCallback> callback = mCallback.promote();
7954 if (callback != 0) {
7955 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007956 }
7957 }
7958 if (!isOutput() && mPrevInDevice != mInDevice) {
7959 mPrevInDevice = type;
7960 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08007961 sp<MmapStreamCallback> callback = mCallback.promote();
7962 if (callback != 0) {
7963 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007964 }
7965 }
7966 return status;
7967}
7968
7969status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7970{
7971 status_t status = NO_ERROR;
7972
7973 mInDevice = AUDIO_DEVICE_NONE;
7974
7975 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
7976 supportsAudioPatches : false;
7977
7978 if (supportsAudioPatches) {
7979 status = mHalDevice->releaseAudioPatch(handle);
7980 } else {
7981 AudioParameter param;
7982 param.addInt(String8(AudioParameter::keyRouting), 0);
7983 status = mHalStream->setParameters(param.toString());
7984 }
7985 return status;
7986}
7987
7988void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
7989{
7990 ThreadBase::getAudioPortConfig(config);
7991 if (isOutput()) {
7992 config->role = AUDIO_PORT_ROLE_SOURCE;
7993 config->ext.mix.hw_module = mAudioHwDev->handle();
7994 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
7995 } else {
7996 config->role = AUDIO_PORT_ROLE_SINK;
7997 config->ext.mix.hw_module = mAudioHwDev->handle();
7998 config->ext.mix.usecase.source = mAudioSource;
7999 }
8000}
8001
8002status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8003{
8004 audio_session_t session = chain->sessionId();
8005
8006 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8007 // Attach all tracks with same session ID to this chain.
8008 // indicate all active tracks in the chain
8009 for (const sp<MmapTrack> &track : mActiveTracks) {
8010 if (session == track->sessionId()) {
8011 chain->incTrackCnt();
8012 chain->incActiveTrackCnt();
8013 }
8014 }
8015
8016 chain->setThread(this);
8017 chain->setInBuffer(nullptr);
8018 chain->setOutBuffer(nullptr);
8019 chain->syncHalEffectsState();
8020
8021 mEffectChains.add(chain);
8022 checkSuspendOnAddEffectChain_l(chain);
8023 return NO_ERROR;
8024}
8025
8026size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8027{
8028 audio_session_t session = chain->sessionId();
8029
8030 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8031
8032 for (size_t i = 0; i < mEffectChains.size(); i++) {
8033 if (chain == mEffectChains[i]) {
8034 mEffectChains.removeAt(i);
8035 // detach all active tracks from the chain
8036 // detach all tracks with same session ID from this chain
8037 for (const sp<MmapTrack> &track : mActiveTracks) {
8038 if (session == track->sessionId()) {
8039 chain->decActiveTrackCnt();
8040 chain->decTrackCnt();
8041 }
8042 }
8043 break;
8044 }
8045 }
8046 return mEffectChains.size();
8047}
8048
8049// hasAudioSession_l() must be called with ThreadBase::mLock held
8050uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8051{
8052 uint32_t result = 0;
8053 if (getEffectChain_l(sessionId) != 0) {
8054 result = EFFECT_SESSION;
8055 }
8056
8057 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8058 sp<MmapTrack> track = mActiveTracks[i];
8059 if (sessionId == track->sessionId()) {
8060 result |= TRACK_SESSION;
8061 if (track->isFastTrack()) {
8062 result |= FAST_SESSION;
8063 }
8064 break;
8065 }
8066 }
8067
8068 return result;
8069}
8070
8071void AudioFlinger::MmapThread::threadLoop_standby()
8072{
8073 mHalStream->standby();
8074}
8075
8076void AudioFlinger::MmapThread::threadLoop_exit()
8077{
Phil Burk7f6b40d2017-02-09 13:18:38 -08008078 sp<MmapStreamCallback> callback = mCallback.promote();
8079 if (callback != 0) {
8080 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008081 }
8082}
8083
8084status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8085{
8086 return BAD_VALUE;
8087}
8088
8089bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8090{
8091 return false;
8092}
8093
8094status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8095 const effect_descriptor_t *desc, audio_session_t sessionId)
8096{
8097 // No global effect sessions on mmap threads
8098 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8099 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8100 desc->name, mThreadName);
8101 return BAD_VALUE;
8102 }
8103
8104 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8105 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8106 desc->name);
8107 return BAD_VALUE;
8108 }
8109 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008110 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8111 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008112 return BAD_VALUE;
8113 }
8114
8115 // Only allow effects without processing load or latency
8116 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8117 return BAD_VALUE;
8118 }
8119
8120 return NO_ERROR;
8121
8122}
8123
8124void AudioFlinger::MmapThread::checkInvalidTracks_l()
8125{
8126 for (const sp<MmapTrack> &track : mActiveTracks) {
8127 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008128 sp<MmapStreamCallback> callback = mCallback.promote();
8129 if (callback != 0) {
8130 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008131 }
8132 break;
8133 }
8134 }
8135}
8136
8137void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8138{
8139 dumpInternals(fd, args);
8140 dumpTracks(fd, args);
8141 dumpEffectChains(fd, args);
8142}
8143
8144void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8145{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008146 dumpBase(fd, args);
8147
8148 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8149 mAttr.content_type, mAttr.usage, mAttr.source);
8150 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8151 if (mActiveTracks.size() == 0) {
8152 dprintf(fd, " No active clients\n");
8153 }
8154}
8155
8156void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8157{
8158 const size_t SIZE = 256;
8159 char buffer[SIZE];
8160 String8 result;
8161
8162 size_t numtracks = mActiveTracks.size();
8163 dprintf(fd, " %zu Tracks", numtracks);
8164 if (numtracks) {
8165 MmapTrack::appendDumpHeader(result);
8166 for (size_t i = 0; i < numtracks ; ++i) {
8167 sp<MmapTrack> track = mActiveTracks[i];
8168 track->dump(buffer, SIZE);
8169 result.append(buffer);
8170 }
8171 } else {
8172 dprintf(fd, "\n");
8173 }
8174 write(fd, result.string(), result.size());
8175}
8176
8177AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8178 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8179 AudioHwDevice *hwDev, AudioStreamOut *output,
8180 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8181 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8182 mStreamType(AUDIO_STREAM_MUSIC),
8183 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8184{
8185 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8186 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8187 mMasterVolume = audioFlinger->masterVolume_l();
8188 mMasterMute = audioFlinger->masterMute_l();
8189 if (mAudioHwDev) {
8190 if (mAudioHwDev->canSetMasterVolume()) {
8191 mMasterVolume = 1.0;
8192 }
8193
8194 if (mAudioHwDev->canSetMasterMute()) {
8195 mMasterMute = false;
8196 }
8197 }
8198}
8199
8200void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8201 audio_stream_type_t streamType,
8202 audio_session_t sessionId,
8203 const sp<MmapStreamCallback>& callback,
8204 audio_port_handle_t portId)
8205{
8206 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8207 mStreamType = streamType;
8208}
8209
8210AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8211{
8212 Mutex::Autolock _l(mLock);
8213 AudioStreamOut *output = mOutput;
8214 mOutput = NULL;
8215 return output;
8216}
8217
8218void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8219{
8220 Mutex::Autolock _l(mLock);
8221 // Don't apply master volume in SW if our HAL can do it for us.
8222 if (mAudioHwDev &&
8223 mAudioHwDev->canSetMasterVolume()) {
8224 mMasterVolume = 1.0;
8225 } else {
8226 mMasterVolume = value;
8227 }
8228}
8229
8230void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8231{
8232 Mutex::Autolock _l(mLock);
8233 // Don't apply master mute in SW if our HAL can do it for us.
8234 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8235 mMasterMute = false;
8236 } else {
8237 mMasterMute = muted;
8238 }
8239}
8240
8241void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8242{
8243 Mutex::Autolock _l(mLock);
8244 if (stream == mStreamType) {
8245 mStreamVolume = value;
8246 broadcast_l();
8247 }
8248}
8249
8250float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8251{
8252 Mutex::Autolock _l(mLock);
8253 if (stream == mStreamType) {
8254 return mStreamVolume;
8255 }
8256 return 0.0f;
8257}
8258
8259void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8260{
8261 Mutex::Autolock _l(mLock);
8262 if (stream == mStreamType) {
8263 mStreamMute= muted;
8264 broadcast_l();
8265 }
8266}
8267
8268void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8269{
8270 Mutex::Autolock _l(mLock);
8271 if (streamType == mStreamType) {
8272 for (const sp<MmapTrack> &track : mActiveTracks) {
8273 track->invalidate();
8274 }
8275 broadcast_l();
8276 }
8277}
8278
8279void AudioFlinger::MmapPlaybackThread::processVolume_l()
8280{
8281 float volume;
8282
8283 if (mMasterMute || mStreamMute) {
8284 volume = 0;
8285 } else {
8286 volume = mMasterVolume * mStreamVolume;
8287 }
8288
8289 if (volume != mHalVolFloat) {
8290 mHalVolFloat = volume;
8291
8292 // Convert volumes from float to 8.24
8293 uint32_t vol = (uint32_t)(volume * (1 << 24));
8294
8295 // Delegate volume control to effect in track effect chain if needed
8296 // only one effect chain can be present on DirectOutputThread, so if
8297 // there is one, the track is connected to it
8298 if (!mEffectChains.isEmpty()) {
8299 mEffectChains[0]->setVolume_l(&vol, &vol);
8300 volume = (float)vol / (1 << 24);
8301 }
8302
8303 mOutput->stream->setVolume(volume, volume);
8304
Phil Burk7f6b40d2017-02-09 13:18:38 -08008305 sp<MmapStreamCallback> callback = mCallback.promote();
8306 if (callback != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008307 int channelCount;
8308 if (isOutput()) {
8309 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8310 } else {
8311 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8312 }
8313 Vector<float> values;
8314 for (int i = 0; i < channelCount; i++) {
8315 values.add(volume);
8316 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08008317 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008318 }
8319 }
8320}
8321
8322void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8323{
8324 if (!mMasterMute) {
8325 char value[PROPERTY_VALUE_MAX];
8326 if (property_get("ro.audio.silent", value, "0") > 0) {
8327 char *endptr;
8328 unsigned long ul = strtoul(value, &endptr, 0);
8329 if (*endptr == '\0' && ul != 0) {
8330 ALOGD("Silence is golden");
8331 // The setprop command will not allow a property to be changed after
8332 // the first time it is set, so we don't have to worry about un-muting.
8333 setMasterMute_l(true);
8334 }
8335 }
8336 }
8337}
8338
8339void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8340{
8341 MmapThread::dumpInternals(fd, args);
8342
Glenn Kastend3bb6452016-12-05 18:14:37 -08008343 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8344 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008345 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8346}
8347
8348AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8349 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8350 AudioHwDevice *hwDev, AudioStreamIn *input,
8351 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8352 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8353 mInput(input)
8354{
8355 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8356 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8357}
8358
8359AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8360{
8361 Mutex::Autolock _l(mLock);
8362 AudioStreamIn *input = mInput;
8363 mInput = NULL;
8364 return input;
8365}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008366} // namespace android