blob: b07c9143ad19cefd9038a965565303a6f11347bf [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>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
Glenn Kastenc05b8d72016-03-24 09:48:17 -070074#include "AutoPark.h"
75
Mikhail Naganov1dc98672016-08-18 17:50:29 -070076// FIXME: Remove after NBAIO is converted
77#include "StreamHalLocal.h"
78
Eric Laurent81784c32012-11-19 14:55:58 -080079// ----------------------------------------------------------------------------
80
81// Note: the following macro is used for extremely verbose logging message. In
82// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
83// 0; but one side effect of this is to turn all LOGV's as well. Some messages
84// are so verbose that we want to suppress them even when we have ALOG_ASSERT
85// turned on. Do not uncomment the #def below unless you really know what you
86// are doing and want to see all of the extremely verbose messages.
87//#define VERY_VERY_VERBOSE_LOGGING
88#ifdef VERY_VERY_VERBOSE_LOGGING
89#define ALOGVV ALOGV
90#else
91#define ALOGVV(a...) do { } while(0)
92#endif
93
Andy Hung6770c6f2015-04-07 13:43:36 -070094// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070095#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070096template <typename T>
97static inline T min(const T& a, const T& b)
98{
99 return a < b ? a : b;
100}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700101
Andy Hungd330ee42015-04-20 13:23:41 -0700102#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700103#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700104#endif
105
Eric Laurent81784c32012-11-19 14:55:58 -0800106namespace android {
107
108// retry counts for buffer fill timeout
109// 50 * ~20msecs = 1 second
110static const int8_t kMaxTrackRetries = 50;
111static const int8_t kMaxTrackStartupRetries = 50;
112// allow less retry attempts on direct output thread.
113// direct outputs can be a scarce resource in audio hardware and should
114// be released as quickly as possible.
115static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700116
Eric Laurent51716182016-02-29 18:00:56 -0800117
Eric Laurent81784c32012-11-19 14:55:58 -0800118
119// don't warn about blocked writes or record buffer overflows more often than this
120static const nsecs_t kWarningThrottleNs = seconds(5);
121
122// RecordThread loop sleep time upon application overrun or audio HAL read error
123static const int kRecordThreadSleepUs = 5000;
124
Eric Laurent10351942014-05-08 18:49:52 -0700125// maximum time to wait in sendConfigEvent_l() for a status to be received
126static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800127
128// minimum sleep time for the mixer thread loop when tracks are active but in underrun
129static const uint32_t kMinThreadSleepTimeUs = 5000;
130// maximum divider applied to the active sleep time in the mixer thread loop
131static const uint32_t kMaxThreadSleepTimeShift = 2;
132
Andy Hung09a50072014-02-27 14:30:47 -0800133// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700134// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800135static const uint32_t kMinNormalSinkBufferSizeMs = 20;
136// maximum normal sink buffer size
137static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800138
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700139// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
140// FIXME This should be based on experimentally observed scheduling jitter
141static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
142
Eric Laurent972a1732013-09-04 09:42:59 -0700143// Offloaded output thread standby delay: allows track transition without going to standby
144static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
145
Eric Laurent51716182016-02-29 18:00:56 -0800146// Direct output thread minimum sleep time in idle or active(underrun) state
147static const nsecs_t kDirectMinSleepTimeUs = 10000;
148
Glenn Kasten1b291842016-07-18 14:55:21 -0700149// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
150// balance between power consumption and latency, and allows threads to be scheduled reliably
151// by the CFS scheduler.
152// FIXME Express other hardcoded references to 20ms with references to this constant and move
153// it appropriately.
154#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800155
Eric Laurent81784c32012-11-19 14:55:58 -0800156// Whether to use fast mixer
157static const enum {
158 FastMixer_Never, // never initialize or use: for debugging only
159 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
160 // normal mixer multiplier is 1
161 FastMixer_Static, // initialize if needed, then use all the time if initialized,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
164 // multiplier is calculated based on min & max normal mixer buffer size
165 // FIXME for FastMixer_Dynamic:
166 // Supporting this option will require fixing HALs that can't handle large writes.
167 // For example, one HAL implementation returns an error from a large write,
168 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
169 // We could either fix the HAL implementations, or provide a wrapper that breaks
170 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
171} kUseFastMixer = FastMixer_Static;
172
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700173// Whether to use fast capture
174static const enum {
175 FastCapture_Never, // never initialize or use: for debugging only
176 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
177 FastCapture_Static, // initialize if needed, then use all the time if initialized
178} kUseFastCapture = FastCapture_Static;
179
Eric Laurent81784c32012-11-19 14:55:58 -0800180// Priorities for requestPriority
181static const int kPriorityAudioApp = 2;
182static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700183static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800184
Glenn Kastenea38ee72016-04-18 11:08:01 -0700185// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
186// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
187// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700188
189// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800190static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800191
Glenn Kasten03490092014-05-27 12:30:54 -0700192// The minimum and maximum allowed values
193static const int kFastTrackMultiplierMin = 1;
194static const int kFastTrackMultiplierMax = 2;
195
196// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
197static int sFastTrackMultiplier = kFastTrackMultiplier;
198
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700199// See Thread::readOnlyHeap().
200// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
201// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
202// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700203static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700204
Eric Laurent81784c32012-11-19 14:55:58 -0800205// ----------------------------------------------------------------------------
206
Glenn Kasten03490092014-05-27 12:30:54 -0700207static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
208
209static void sFastTrackMultiplierInit()
210{
211 char value[PROPERTY_VALUE_MAX];
212 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
213 char *endptr;
214 unsigned long ul = strtoul(value, &endptr, 0);
215 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
216 sFastTrackMultiplier = (int) ul;
217 }
218 }
219}
220
221// ----------------------------------------------------------------------------
222
Eric Laurent81784c32012-11-19 14:55:58 -0800223#ifdef ADD_BATTERY_DATA
224// To collect the amplifier usage
225static void addBatteryData(uint32_t params) {
226 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
227 if (service == NULL) {
228 // it already logged
229 return;
230 }
231
232 service->addBatteryData(params);
233}
234#endif
235
Andy Hung3f0c9022016-01-15 17:49:46 -0800236// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
237struct {
238 // call when you acquire a partial wakelock
239 void acquire(const sp<IBinder> &wakeLockToken) {
240 pthread_mutex_lock(&mLock);
241 if (wakeLockToken.get() == nullptr) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 } else {
244 if (mCount == 0) {
245 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
246 }
247 ++mCount;
248 }
249 pthread_mutex_unlock(&mLock);
250 }
251
252 // call when you release a partial wakelock.
253 void release(const sp<IBinder> &wakeLockToken) {
254 if (wakeLockToken.get() == nullptr) {
255 return;
256 }
257 pthread_mutex_lock(&mLock);
258 if (--mCount < 0) {
259 ALOGE("negative wakelock count");
260 mCount = 0;
261 }
262 pthread_mutex_unlock(&mLock);
263 }
264
265 // retrieves the boottime timebase offset from monotonic.
266 int64_t getBoottimeOffset() {
267 pthread_mutex_lock(&mLock);
268 int64_t boottimeOffset = mBoottimeOffset;
269 pthread_mutex_unlock(&mLock);
270 return boottimeOffset;
271 }
272
273 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
274 // and the selected timebase.
275 // Currently only TIMEBASE_BOOTTIME is allowed.
276 //
277 // This only needs to be called upon acquiring the first partial wakelock
278 // after all other partial wakelocks are released.
279 //
280 // We do an empirical measurement of the offset rather than parsing
281 // /proc/timer_list since the latter is not a formal kernel ABI.
282 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
283 int clockbase;
284 switch (timebase) {
285 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
286 clockbase = SYSTEM_TIME_BOOTTIME;
287 break;
288 default:
289 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
290 break;
291 }
292 // try three times to get the clock offset, choose the one
293 // with the minimum gap in measurements.
294 const int tries = 3;
295 nsecs_t bestGap, measured;
296 for (int i = 0; i < tries; ++i) {
297 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
298 const nsecs_t tbase = systemTime(clockbase);
299 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
300 const nsecs_t gap = tmono2 - tmono;
301 if (i == 0 || gap < bestGap) {
302 bestGap = gap;
303 measured = tbase - ((tmono + tmono2) >> 1);
304 }
305 }
306
307 // to avoid micro-adjusting, we don't change the timebase
308 // unless it is significantly different.
309 //
310 // Assumption: It probably takes more than toleranceNs to
311 // suspend and resume the device.
312 static int64_t toleranceNs = 10000; // 10 us
313 if (llabs(*offset - measured) > toleranceNs) {
314 ALOGV("Adjusting timebase offset old: %lld new: %lld",
315 (long long)*offset, (long long)measured);
316 *offset = measured;
317 }
318 }
319
320 pthread_mutex_t mLock;
321 int32_t mCount;
322 int64_t mBoottimeOffset;
323} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800324
325// ----------------------------------------------------------------------------
326// CPU Stats
327// ----------------------------------------------------------------------------
328
329class CpuStats {
330public:
331 CpuStats();
332 void sample(const String8 &title);
333#ifdef DEBUG_CPU_USAGE
334private:
335 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
336 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
337
338 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
339
340 int mCpuNum; // thread's current CPU number
341 int mCpukHz; // frequency of thread's current CPU in kHz
342#endif
343};
344
345CpuStats::CpuStats()
346#ifdef DEBUG_CPU_USAGE
347 : mCpuNum(-1), mCpukHz(-1)
348#endif
349{
350}
351
Glenn Kasten0f11b512014-01-31 16:18:54 -0800352void CpuStats::sample(const String8 &title
353#ifndef DEBUG_CPU_USAGE
354 __unused
355#endif
356 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800357#ifdef DEBUG_CPU_USAGE
358 // get current thread's delta CPU time in wall clock ns
359 double wcNs;
360 bool valid = mCpuUsage.sampleAndEnable(wcNs);
361
362 // record sample for wall clock statistics
363 if (valid) {
364 mWcStats.sample(wcNs);
365 }
366
367 // get the current CPU number
368 int cpuNum = sched_getcpu();
369
370 // get the current CPU frequency in kHz
371 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
372
373 // check if either CPU number or frequency changed
374 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
375 mCpuNum = cpuNum;
376 mCpukHz = cpukHz;
377 // ignore sample for purposes of cycles
378 valid = false;
379 }
380
381 // if no change in CPU number or frequency, then record sample for cycle statistics
382 if (valid && mCpukHz > 0) {
383 double cycles = wcNs * cpukHz * 0.000001;
384 mHzStats.sample(cycles);
385 }
386
387 unsigned n = mWcStats.n();
388 // mCpuUsage.elapsed() is expensive, so don't call it every loop
389 if ((n & 127) == 1) {
390 long long elapsed = mCpuUsage.elapsed();
391 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
392 double perLoop = elapsed / (double) n;
393 double perLoop100 = perLoop * 0.01;
394 double perLoop1k = perLoop * 0.001;
395 double mean = mWcStats.mean();
396 double stddev = mWcStats.stddev();
397 double minimum = mWcStats.minimum();
398 double maximum = mWcStats.maximum();
399 double meanCycles = mHzStats.mean();
400 double stddevCycles = mHzStats.stddev();
401 double minCycles = mHzStats.minimum();
402 double maxCycles = mHzStats.maximum();
403 mCpuUsage.resetElapsed();
404 mWcStats.reset();
405 mHzStats.reset();
406 ALOGD("CPU usage for %s over past %.1f secs\n"
407 " (%u mixer loops at %.1f mean ms per loop):\n"
408 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
409 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
410 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
411 title.string(),
412 elapsed * .000000001, n, perLoop * .000001,
413 mean * .001,
414 stddev * .001,
415 minimum * .001,
416 maximum * .001,
417 mean / perLoop100,
418 stddev / perLoop100,
419 minimum / perLoop100,
420 maximum / perLoop100,
421 meanCycles / perLoop1k,
422 stddevCycles / perLoop1k,
423 minCycles / perLoop1k,
424 maxCycles / perLoop1k);
425
426 }
427 }
428#endif
429};
430
431// ----------------------------------------------------------------------------
432// ThreadBase
433// ----------------------------------------------------------------------------
434
Glenn Kasten97b7b752014-09-28 13:04:24 -0700435// static
436const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
437{
438 switch (type) {
439 case MIXER:
440 return "MIXER";
441 case DIRECT:
442 return "DIRECT";
443 case DUPLICATING:
444 return "DUPLICATING";
445 case RECORD:
446 return "RECORD";
447 case OFFLOAD:
448 return "OFFLOAD";
449 default:
450 return "unknown";
451 }
452}
453
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454String8 devicesToString(audio_devices_t devices)
455{
456 static const struct mapping {
457 audio_devices_t mDevices;
458 const char * mString;
459 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800460 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
461 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
462 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
463 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
464 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
465 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
466 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
467 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
468 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
469 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
470 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
471 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
472 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
473 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
474 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
475 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
476 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
477 {AUDIO_DEVICE_OUT_LINE, "LINE"},
478 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
479 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
480 {AUDIO_DEVICE_OUT_FM, "FM"},
481 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
482 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
483 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800484 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800485 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800486 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800487 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
488 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
489 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
490 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
491 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
492 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
493 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
494 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
495 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
496 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
497 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
498 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
499 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
500 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
501 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
502 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
503 {AUDIO_DEVICE_IN_LINE, "LINE"},
504 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
505 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
506 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
507 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800508 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800509 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800510 };
511 String8 result;
512 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
513 const mapping *entry;
514 if (devices & AUDIO_DEVICE_BIT_IN) {
515 devices &= ~AUDIO_DEVICE_BIT_IN;
516 entry = mappingsIn;
517 } else {
518 entry = mappingsOut;
519 }
520 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
521 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
522 if (devices & entry->mDevices) {
523 if (!result.isEmpty()) {
524 result.append("|");
525 }
526 result.append(entry->mString);
527 }
528 }
529 if (devices & ~allDevices) {
530 if (!result.isEmpty()) {
531 result.append("|");
532 }
533 result.appendFormat("0x%X", devices & ~allDevices);
534 }
535 if (result.isEmpty()) {
536 result.append(entry->mString);
537 }
538 return result;
539}
540
541String8 inputFlagsToString(audio_input_flags_t flags)
542{
543 static const struct mapping {
544 audio_input_flags_t mFlag;
545 const char * mString;
546 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800547 {AUDIO_INPUT_FLAG_FAST, "FAST"},
548 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
549 {AUDIO_INPUT_FLAG_RAW, "RAW"},
550 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
551 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800552 };
553 String8 result;
554 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
555 const mapping *entry;
556 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
557 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
558 if (flags & entry->mFlag) {
559 if (!result.isEmpty()) {
560 result.append("|");
561 }
562 result.append(entry->mString);
563 }
564 }
565 if (flags & ~allFlags) {
566 if (!result.isEmpty()) {
567 result.append("|");
568 }
569 result.appendFormat("0x%X", flags & ~allFlags);
570 }
571 if (result.isEmpty()) {
572 result.append(entry->mString);
573 }
574 return result;
575}
576
577String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700578{
579 static const struct mapping {
580 audio_output_flags_t mFlag;
581 const char * mString;
582 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800583 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
584 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
585 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
586 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
587 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
588 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
589 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
590 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
591 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
592 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
593 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700594 };
595 String8 result;
596 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
597 const mapping *entry;
598 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
599 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
600 if (flags & entry->mFlag) {
601 if (!result.isEmpty()) {
602 result.append("|");
603 }
604 result.append(entry->mString);
605 }
606 }
607 if (flags & ~allFlags) {
608 if (!result.isEmpty()) {
609 result.append("|");
610 }
611 result.appendFormat("0x%X", flags & ~allFlags);
612 }
613 if (result.isEmpty()) {
614 result.append(entry->mString);
615 }
616 return result;
617}
618
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800619const char *sourceToString(audio_source_t source)
620{
621 switch (source) {
622 case AUDIO_SOURCE_DEFAULT: return "default";
623 case AUDIO_SOURCE_MIC: return "mic";
624 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
625 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
626 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
627 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
628 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
629 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
630 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800631 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800632 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
633 case AUDIO_SOURCE_HOTWORD: return "hotword";
634 default: return "unknown";
635 }
636}
637
Eric Laurent81784c32012-11-19 14:55:58 -0800638AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700639 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800640 : Thread(false /*canCallJava*/),
641 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700642 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700643 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800644 // are set by PlaybackThread::readOutputParameters_l() or
645 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700646 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800647 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700648 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
649 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800650 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700651 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800652 mSystemReady(systemReady),
653 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800654{
Eric Laurent296fb132015-05-01 11:38:42 -0700655 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800656}
657
658AudioFlinger::ThreadBase::~ThreadBase()
659{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700660 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700661 mConfigEvents.clear();
662
Eric Laurent81784c32012-11-19 14:55:58 -0800663 // do not lock the mutex in destructor
664 releaseWakeLock_l();
665 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800666 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800667 binder->unlinkToDeath(mDeathRecipient);
668 }
669}
670
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700671status_t AudioFlinger::ThreadBase::readyToRun()
672{
673 status_t status = initCheck();
674 if (status == NO_ERROR) {
675 ALOGI("AudioFlinger's thread %p ready to run", this);
676 } else {
677 ALOGE("No working audio driver found.");
678 }
679 return status;
680}
681
Eric Laurent81784c32012-11-19 14:55:58 -0800682void AudioFlinger::ThreadBase::exit()
683{
684 ALOGV("ThreadBase::exit");
685 // do any cleanup required for exit to succeed
686 preExit();
687 {
688 // This lock prevents the following race in thread (uniprocessor for illustration):
689 // if (!exitPending()) {
690 // // context switch from here to exit()
691 // // exit() calls requestExit(), what exitPending() observes
692 // // exit() calls signal(), which is dropped since no waiters
693 // // context switch back from exit() to here
694 // mWaitWorkCV.wait(...);
695 // // now thread is hung
696 // }
697 AutoMutex lock(mLock);
698 requestExit();
699 mWaitWorkCV.broadcast();
700 }
701 // When Thread::requestExitAndWait is made virtual and this method is renamed to
702 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
703 requestExitAndWait();
704}
705
706status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
707{
Eric Laurent81784c32012-11-19 14:55:58 -0800708 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
709 Mutex::Autolock _l(mLock);
710
Eric Laurent10351942014-05-08 18:49:52 -0700711 return sendSetParameterConfigEvent_l(keyValuePairs);
712}
713
714// sendConfigEvent_l() must be called with ThreadBase::mLock held
715// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
716status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
717{
718 status_t status = NO_ERROR;
719
Eric Laurent72e3f392015-05-20 14:43:50 -0700720 if (event->mRequiresSystemReady && !mSystemReady) {
721 event->mWaitStatus = false;
722 mPendingConfigEvents.add(event);
723 return status;
724 }
Eric Laurent10351942014-05-08 18:49:52 -0700725 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700726 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800727 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700728 mLock.unlock();
729 {
730 Mutex::Autolock _l(event->mLock);
731 while (event->mWaitStatus) {
732 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
733 event->mStatus = TIMED_OUT;
734 event->mWaitStatus = false;
735 }
736 }
737 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800738 }
Eric Laurent10351942014-05-08 18:49:52 -0700739 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800740 return status;
741}
742
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700743void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800744{
745 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700746 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800747}
748
749// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700750void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800751{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700752 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700753 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800754}
755
Eric Laurent72e3f392015-05-20 14:43:50 -0700756void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
757{
758 Mutex::Autolock _l(mLock);
759 sendPrioConfigEvent_l(pid, tid, prio);
760}
761
Eric Laurent81784c32012-11-19 14:55:58 -0800762// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
763void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
764{
Eric Laurent10351942014-05-08 18:49:52 -0700765 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
766 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800767}
768
Eric Laurent10351942014-05-08 18:49:52 -0700769// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
770status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800771{
Andy Hung2ddee192015-12-18 17:34:44 -0800772 sp<ConfigEvent> configEvent;
773 AudioParameter param(keyValuePair);
774 int value;
775 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
776 setMasterMono_l(value != 0);
777 if (param.size() == 1) {
778 return NO_ERROR; // should be a solo parameter - we don't pass down
779 }
780 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
781 configEvent = new SetParameterConfigEvent(param.toString());
782 } else {
783 configEvent = new SetParameterConfigEvent(keyValuePair);
784 }
Eric Laurent10351942014-05-08 18:49:52 -0700785 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700786}
787
Eric Laurent1c333e22014-05-20 10:48:17 -0700788status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
789 const struct audio_patch *patch,
790 audio_patch_handle_t *handle)
791{
792 Mutex::Autolock _l(mLock);
793 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
794 status_t status = sendConfigEvent_l(configEvent);
795 if (status == NO_ERROR) {
796 CreateAudioPatchConfigEventData *data =
797 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
798 *handle = data->mHandle;
799 }
800 return status;
801}
802
803status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
804 const audio_patch_handle_t handle)
805{
806 Mutex::Autolock _l(mLock);
807 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
808 return sendConfigEvent_l(configEvent);
809}
810
811
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700812// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700813void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700814{
Eric Laurent10351942014-05-08 18:49:52 -0700815 bool configChanged = false;
816
Eric Laurent81784c32012-11-19 14:55:58 -0800817 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700818 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700819 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800820 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700821 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700822 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700823 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
824 // FIXME Need to understand why this has to be done asynchronously
825 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700826 true /*asynchronous*/);
827 if (err != 0) {
828 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700829 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700830 }
831 } break;
832 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700833 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700834 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700835 } break;
836 case CFG_EVENT_SET_PARAMETER: {
837 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
838 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
839 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700840 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700841 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700842 case CFG_EVENT_CREATE_AUDIO_PATCH: {
843 CreateAudioPatchConfigEventData *data =
844 (CreateAudioPatchConfigEventData *)event->mData.get();
845 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
846 } break;
847 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
848 ReleaseAudioPatchConfigEventData *data =
849 (ReleaseAudioPatchConfigEventData *)event->mData.get();
850 event->mStatus = releaseAudioPatch_l(data->mHandle);
851 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700852 default:
Eric Laurent10351942014-05-08 18:49:52 -0700853 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700854 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800855 }
Eric Laurent10351942014-05-08 18:49:52 -0700856 {
857 Mutex::Autolock _l(event->mLock);
858 if (event->mWaitStatus) {
859 event->mWaitStatus = false;
860 event->mCond.signal();
861 }
862 }
863 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
864 }
865
866 if (configChanged) {
867 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800868 }
Eric Laurent81784c32012-11-19 14:55:58 -0800869}
870
Marco Nelissenb2208842014-02-07 14:00:50 -0800871String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
872 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700873 const audio_channel_representation_t representation =
874 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700875
876 switch (representation) {
877 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
878 if (output) {
879 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
880 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
881 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
882 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
883 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
884 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
887 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
888 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
889 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
890 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
891 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
893 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
895 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
896 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
897 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
898 } else {
899 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
900 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
901 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
902 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
903 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
904 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
905 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
906 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
907 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
908 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
909 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
910 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
911 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
912 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
913 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
914 }
915 const int len = s.length();
916 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700917 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700918 s.unlockBuffer(len - 2); // remove trailing ", "
919 }
920 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800921 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700922 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
923 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
924 return s;
925 default:
926 s.appendFormat("unknown mask, representation:%d bits:%#x",
927 representation, audio_channel_mask_get_bits(mask));
928 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800929 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800930}
931
Glenn Kasten0f11b512014-01-31 16:18:54 -0800932void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800933{
934 const size_t SIZE = 256;
935 char buffer[SIZE];
936 String8 result;
937
938 bool locked = AudioFlinger::dumpTryLock(mLock);
939 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700940 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800941 }
942
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800943 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700944 dprintf(fd, " I/O handle: %d\n", mId);
945 dprintf(fd, " TID: %d\n", getTid());
946 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700947 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700948 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700949 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700950 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700951 dprintf(fd, " Channel count: %u\n", mChannelCount);
952 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800953 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700954 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
955 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700956 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800957 size_t numConfig = mConfigEvents.size();
958 if (numConfig) {
959 for (size_t i = 0; i < numConfig; i++) {
960 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700961 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800962 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700963 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800964 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700965 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800966 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800967 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
968 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
969 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800970
971 if (locked) {
972 mLock.unlock();
973 }
974}
975
976void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
977{
978 const size_t SIZE = 256;
979 char buffer[SIZE];
980 String8 result;
981
Marco Nelissenb2208842014-02-07 14:00:50 -0800982 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000983 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800984 write(fd, buffer, strlen(buffer));
985
Marco Nelissenb2208842014-02-07 14:00:50 -0800986 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800987 sp<EffectChain> chain = mEffectChains[i];
988 if (chain != 0) {
989 chain->dump(fd, args);
990 }
991 }
992}
993
Marco Nelissene14a5d62013-10-03 08:51:24 -0700994void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800995{
996 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700997 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800998}
999
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001000String16 AudioFlinger::ThreadBase::getWakeLockTag()
1001{
1002 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001003 case MIXER:
1004 return String16("AudioMix");
1005 case DIRECT:
1006 return String16("AudioDirectOut");
1007 case DUPLICATING:
1008 return String16("AudioDup");
1009 case RECORD:
1010 return String16("AudioIn");
1011 case OFFLOAD:
1012 return String16("AudioOffload");
1013 default:
1014 ALOG_ASSERT(false);
1015 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001016 }
1017}
1018
Marco Nelissene14a5d62013-10-03 08:51:24 -07001019void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001020{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001021 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001022 if (mPowerManager != 0) {
1023 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001024 status_t status;
1025 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001026 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001027 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001028 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001029 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001030 uid,
1031 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001032 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001033 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001034 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001035 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001036 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001037 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001038 }
Eric Laurent81784c32012-11-19 14:55:58 -08001039 if (status == NO_ERROR) {
1040 mWakeLockToken = binder;
1041 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001042 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001043 }
Wei Jia3f273d12015-11-24 09:06:49 -08001044
1045 if (!mNotifiedBatteryStart) {
1046 BatteryNotifier::getInstance().noteStartAudio();
1047 mNotifiedBatteryStart = true;
1048 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001049 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001050 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1051 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001052}
1053
1054void AudioFlinger::ThreadBase::releaseWakeLock()
1055{
1056 Mutex::Autolock _l(mLock);
1057 releaseWakeLock_l();
1058}
1059
1060void AudioFlinger::ThreadBase::releaseWakeLock_l()
1061{
Andy Hung3f0c9022016-01-15 17:49:46 -08001062 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001063 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001064 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001065 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001066 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1067 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001068 }
1069 mWakeLockToken.clear();
1070 }
Wei Jia3f273d12015-11-24 09:06:49 -08001071
1072 if (mNotifiedBatteryStart) {
1073 BatteryNotifier::getInstance().noteStopAudio();
1074 mNotifiedBatteryStart = false;
1075 }
Eric Laurent81784c32012-11-19 14:55:58 -08001076}
1077
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001078void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1079 Mutex::Autolock _l(mLock);
1080 updateWakeLockUids_l(uids);
1081}
1082
1083void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001084 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001085 // use checkService() to avoid blocking if power service is not up yet
1086 sp<IBinder> binder =
1087 defaultServiceManager()->checkService(String16("power"));
1088 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001089 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001090 } else {
1091 mPowerManager = interface_cast<IPowerManager>(binder);
1092 binder->linkToDeath(mDeathRecipient);
1093 }
1094 }
1095}
1096
1097void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001098 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001099 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1100 if (mSystemReady) {
1101 ALOGE("no wake lock to update, but system ready!");
1102 } else {
1103 ALOGW("no wake lock to update, system not ready yet");
1104 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001105 return;
1106 }
1107 if (mPowerManager != 0) {
1108 sp<IBinder> binder = new BBinder();
1109 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001110 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1111 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001112 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001113 }
1114}
1115
Eric Laurent81784c32012-11-19 14:55:58 -08001116void AudioFlinger::ThreadBase::clearPowerManager()
1117{
1118 Mutex::Autolock _l(mLock);
1119 releaseWakeLock_l();
1120 mPowerManager.clear();
1121}
1122
Glenn Kasten0f11b512014-01-31 16:18:54 -08001123void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001124{
1125 sp<ThreadBase> thread = mThread.promote();
1126 if (thread != 0) {
1127 thread->clearPowerManager();
1128 }
1129 ALOGW("power manager service died !!!");
1130}
1131
1132void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001133 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001134{
1135 Mutex::Autolock _l(mLock);
1136 setEffectSuspended_l(type, suspend, sessionId);
1137}
1138
1139void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001140 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001141{
1142 sp<EffectChain> chain = getEffectChain_l(sessionId);
1143 if (chain != 0) {
1144 if (type != NULL) {
1145 chain->setEffectSuspended_l(type, suspend);
1146 } else {
1147 chain->setEffectSuspendedAll_l(suspend);
1148 }
1149 }
1150
1151 updateSuspendedSessions_l(type, suspend, sessionId);
1152}
1153
1154void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1155{
1156 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1157 if (index < 0) {
1158 return;
1159 }
1160
1161 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1162 mSuspendedSessions.valueAt(index);
1163
1164 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001165 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001166 for (int j = 0; j < desc->mRefCount; j++) {
1167 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1168 chain->setEffectSuspendedAll_l(true);
1169 } else {
1170 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1171 desc->mType.timeLow);
1172 chain->setEffectSuspended_l(&desc->mType, true);
1173 }
1174 }
1175 }
1176}
1177
1178void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1179 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001180 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001181{
1182 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1183
1184 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1185
1186 if (suspend) {
1187 if (index >= 0) {
1188 sessionEffects = mSuspendedSessions.valueAt(index);
1189 } else {
1190 mSuspendedSessions.add(sessionId, sessionEffects);
1191 }
1192 } else {
1193 if (index < 0) {
1194 return;
1195 }
1196 sessionEffects = mSuspendedSessions.valueAt(index);
1197 }
1198
1199
1200 int key = EffectChain::kKeyForSuspendAll;
1201 if (type != NULL) {
1202 key = type->timeLow;
1203 }
1204 index = sessionEffects.indexOfKey(key);
1205
1206 sp<SuspendedSessionDesc> desc;
1207 if (suspend) {
1208 if (index >= 0) {
1209 desc = sessionEffects.valueAt(index);
1210 } else {
1211 desc = new SuspendedSessionDesc();
1212 if (type != NULL) {
1213 desc->mType = *type;
1214 }
1215 sessionEffects.add(key, desc);
1216 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1217 }
1218 desc->mRefCount++;
1219 } else {
1220 if (index < 0) {
1221 return;
1222 }
1223 desc = sessionEffects.valueAt(index);
1224 if (--desc->mRefCount == 0) {
1225 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1226 sessionEffects.removeItemsAt(index);
1227 if (sessionEffects.isEmpty()) {
1228 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1229 sessionId);
1230 mSuspendedSessions.removeItem(sessionId);
1231 }
1232 }
1233 }
1234 if (!sessionEffects.isEmpty()) {
1235 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1236 }
1237}
1238
1239void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1240 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001241 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001242{
1243 Mutex::Autolock _l(mLock);
1244 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1245}
1246
1247void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1248 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001249 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001250{
1251 if (mType != RECORD) {
1252 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1253 // another session. This gives the priority to well behaved effect control panels
1254 // and applications not using global effects.
1255 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1256 // global effects
1257 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1258 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1259 }
1260 }
1261
1262 sp<EffectChain> chain = getEffectChain_l(sessionId);
1263 if (chain != 0) {
1264 chain->checkSuspendOnEffectEnabled(effect, enabled);
1265 }
1266}
1267
Eric Laurent4c415062016-06-17 16:14:16 -07001268// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1269status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1270 const effect_descriptor_t *desc, audio_session_t sessionId)
1271{
1272 // No global effect sessions on record threads
1273 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1274 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1275 desc->name, mThreadName);
1276 return BAD_VALUE;
1277 }
1278 // only pre processing effects on record thread
1279 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1280 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1281 desc->name, mThreadName);
1282 return BAD_VALUE;
1283 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001284
1285 // always allow effects without processing load or latency
1286 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1287 return NO_ERROR;
1288 }
1289
Eric Laurent4c415062016-06-17 16:14:16 -07001290 audio_input_flags_t flags = mInput->flags;
1291 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1292 if (flags & AUDIO_INPUT_FLAG_RAW) {
1293 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1294 desc->name, mThreadName);
1295 return BAD_VALUE;
1296 }
1297 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1298 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1299 desc->name, mThreadName);
1300 return BAD_VALUE;
1301 }
1302 }
1303 return NO_ERROR;
1304}
1305
1306// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1307status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1308 const effect_descriptor_t *desc, audio_session_t sessionId)
1309{
1310 // no preprocessing on playback threads
1311 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1312 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1313 " thread %s", desc->name, mThreadName);
1314 return BAD_VALUE;
1315 }
1316
1317 switch (mType) {
1318 case MIXER: {
1319 // Reject any effect on mixer multichannel sinks.
1320 // TODO: fix both format and multichannel issues with effects.
1321 if (mChannelCount != FCC_2) {
1322 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1323 " thread %s", desc->name, mChannelCount, mThreadName);
1324 return BAD_VALUE;
1325 }
1326 audio_output_flags_t flags = mOutput->flags;
1327 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1328 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1329 // global effects are applied only to non fast tracks if they are SW
1330 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1331 break;
1332 }
1333 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1334 // only post processing on output stage session
1335 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1336 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1337 " on output stage session", desc->name);
1338 return BAD_VALUE;
1339 }
1340 } else {
1341 // no restriction on effects applied on non fast tracks
1342 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1343 break;
1344 }
1345 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001346
1347 // always allow effects without processing load or latency
1348 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1349 break;
1350 }
Eric Laurent4c415062016-06-17 16:14:16 -07001351 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1352 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1353 desc->name);
1354 return BAD_VALUE;
1355 }
1356 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1357 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1358 " in fast mode", desc->name);
1359 return BAD_VALUE;
1360 }
1361 }
1362 } break;
1363 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001364 // nothing actionable on offload threads, if the effect:
1365 // - is offloadable: the effect can be created
1366 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1367 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001368 break;
1369 case DIRECT:
1370 // Reject any effect on Direct output threads for now, since the format of
1371 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1372 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1373 desc->name, mThreadName);
1374 return BAD_VALUE;
1375 case DUPLICATING:
1376 // Reject any effect on mixer multichannel sinks.
1377 // TODO: fix both format and multichannel issues with effects.
1378 if (mChannelCount != FCC_2) {
1379 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1380 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1381 return BAD_VALUE;
1382 }
1383 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1384 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1385 " thread %s", desc->name, mThreadName);
1386 return BAD_VALUE;
1387 }
1388 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1389 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1390 " DUPLICATING thread %s", desc->name, mThreadName);
1391 return BAD_VALUE;
1392 }
1393 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1394 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1395 " DUPLICATING thread %s", desc->name, mThreadName);
1396 return BAD_VALUE;
1397 }
1398 break;
1399 default:
1400 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1401 }
1402
1403 return NO_ERROR;
1404}
1405
Eric Laurent81784c32012-11-19 14:55:58 -08001406// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1407sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1408 const sp<AudioFlinger::Client>& client,
1409 const sp<IEffectClient>& effectClient,
1410 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001411 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001412 effect_descriptor_t *desc,
1413 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001414 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001415{
1416 sp<EffectModule> effect;
1417 sp<EffectHandle> handle;
1418 status_t lStatus;
1419 sp<EffectChain> chain;
1420 bool chainCreated = false;
1421 bool effectCreated = false;
1422 bool effectRegistered = false;
1423
1424 lStatus = initCheck();
1425 if (lStatus != NO_ERROR) {
1426 ALOGW("createEffect_l() Audio driver not initialized.");
1427 goto Exit;
1428 }
1429
Eric Laurent81784c32012-11-19 14:55:58 -08001430 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1431
1432 { // scope for mLock
1433 Mutex::Autolock _l(mLock);
1434
Eric Laurent4c415062016-06-17 16:14:16 -07001435 lStatus = checkEffectCompatibility_l(desc, sessionId);
1436 if (lStatus != NO_ERROR) {
1437 goto Exit;
1438 }
1439
Eric Laurent81784c32012-11-19 14:55:58 -08001440 // check for existing effect chain with the requested audio session
1441 chain = getEffectChain_l(sessionId);
1442 if (chain == 0) {
1443 // create a new chain for this session
1444 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1445 chain = new EffectChain(this, sessionId);
1446 addEffectChain_l(chain);
1447 chain->setStrategy(getStrategyForSession_l(sessionId));
1448 chainCreated = true;
1449 } else {
1450 effect = chain->getEffectFromDesc_l(desc);
1451 }
1452
1453 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1454
1455 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001456 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001457 // Check CPU and memory usage
1458 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1459 if (lStatus != NO_ERROR) {
1460 goto Exit;
1461 }
1462 effectRegistered = true;
1463 // create a new effect module if none present in the chain
1464 effect = new EffectModule(this, chain, desc, id, sessionId);
1465 lStatus = effect->status();
1466 if (lStatus != NO_ERROR) {
1467 goto Exit;
1468 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001469 effect->setOffloaded(mType == OFFLOAD, mId);
1470
Eric Laurent81784c32012-11-19 14:55:58 -08001471 lStatus = chain->addEffect_l(effect);
1472 if (lStatus != NO_ERROR) {
1473 goto Exit;
1474 }
1475 effectCreated = true;
1476
1477 effect->setDevice(mOutDevice);
1478 effect->setDevice(mInDevice);
1479 effect->setMode(mAudioFlinger->getMode());
1480 effect->setAudioSource(mAudioSource);
1481 }
1482 // create effect handle and connect it to effect module
1483 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001484 lStatus = handle->initCheck();
1485 if (lStatus == OK) {
1486 lStatus = effect->addHandle(handle.get());
1487 }
Eric Laurent81784c32012-11-19 14:55:58 -08001488 if (enabled != NULL) {
1489 *enabled = (int)effect->isEnabled();
1490 }
1491 }
1492
1493Exit:
1494 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1495 Mutex::Autolock _l(mLock);
1496 if (effectCreated) {
1497 chain->removeEffect_l(effect);
1498 }
1499 if (effectRegistered) {
1500 AudioSystem::unregisterEffect(effect->id());
1501 }
1502 if (chainCreated) {
1503 removeEffectChain_l(chain);
1504 }
1505 handle.clear();
1506 }
1507
Glenn Kasten9156ef32013-08-06 15:39:08 -07001508 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001509 return handle;
1510}
1511
Glenn Kastend848eb42016-03-08 13:42:11 -08001512sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1513 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001514{
1515 Mutex::Autolock _l(mLock);
1516 return getEffect_l(sessionId, effectId);
1517}
1518
Glenn Kastend848eb42016-03-08 13:42:11 -08001519sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1520 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001521{
1522 sp<EffectChain> chain = getEffectChain_l(sessionId);
1523 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1524}
1525
1526// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1527// PlaybackThread::mLock held
1528status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1529{
1530 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001531 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001532 sp<EffectChain> chain = getEffectChain_l(sessionId);
1533 bool chainCreated = false;
1534
Eric Laurent5baf2af2013-09-12 17:37:00 -07001535 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1536 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1537 this, effect->desc().name, effect->desc().flags);
1538
Eric Laurent81784c32012-11-19 14:55:58 -08001539 if (chain == 0) {
1540 // create a new chain for this session
1541 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1542 chain = new EffectChain(this, sessionId);
1543 addEffectChain_l(chain);
1544 chain->setStrategy(getStrategyForSession_l(sessionId));
1545 chainCreated = true;
1546 }
1547 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1548
1549 if (chain->getEffectFromId_l(effect->id()) != 0) {
1550 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1551 this, effect->desc().name, chain.get());
1552 return BAD_VALUE;
1553 }
1554
Eric Laurent5baf2af2013-09-12 17:37:00 -07001555 effect->setOffloaded(mType == OFFLOAD, mId);
1556
Eric Laurent81784c32012-11-19 14:55:58 -08001557 status_t status = chain->addEffect_l(effect);
1558 if (status != NO_ERROR) {
1559 if (chainCreated) {
1560 removeEffectChain_l(chain);
1561 }
1562 return status;
1563 }
1564
1565 effect->setDevice(mOutDevice);
1566 effect->setDevice(mInDevice);
1567 effect->setMode(mAudioFlinger->getMode());
1568 effect->setAudioSource(mAudioSource);
1569 return NO_ERROR;
1570}
1571
1572void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1573
1574 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1575 effect_descriptor_t desc = effect->desc();
1576 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1577 detachAuxEffect_l(effect->id());
1578 }
1579
1580 sp<EffectChain> chain = effect->chain().promote();
1581 if (chain != 0) {
1582 // remove effect chain if removing last effect
1583 if (chain->removeEffect_l(effect) == 0) {
1584 removeEffectChain_l(chain);
1585 }
1586 } else {
1587 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1588 }
1589}
1590
1591void AudioFlinger::ThreadBase::lockEffectChains_l(
1592 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1593{
1594 effectChains = mEffectChains;
1595 for (size_t i = 0; i < mEffectChains.size(); i++) {
1596 mEffectChains[i]->lock();
1597 }
1598}
1599
1600void AudioFlinger::ThreadBase::unlockEffectChains(
1601 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1602{
1603 for (size_t i = 0; i < effectChains.size(); i++) {
1604 effectChains[i]->unlock();
1605 }
1606}
1607
Glenn Kastend848eb42016-03-08 13:42:11 -08001608sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001609{
1610 Mutex::Autolock _l(mLock);
1611 return getEffectChain_l(sessionId);
1612}
1613
Glenn Kastend848eb42016-03-08 13:42:11 -08001614sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1615 const
Eric Laurent81784c32012-11-19 14:55:58 -08001616{
1617 size_t size = mEffectChains.size();
1618 for (size_t i = 0; i < size; i++) {
1619 if (mEffectChains[i]->sessionId() == sessionId) {
1620 return mEffectChains[i];
1621 }
1622 }
1623 return 0;
1624}
1625
1626void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1627{
1628 Mutex::Autolock _l(mLock);
1629 size_t size = mEffectChains.size();
1630 for (size_t i = 0; i < size; i++) {
1631 mEffectChains[i]->setMode_l(mode);
1632 }
1633}
1634
Eric Laurent83b88082014-06-20 18:31:16 -07001635void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1636{
1637 config->type = AUDIO_PORT_TYPE_MIX;
1638 config->ext.mix.handle = mId;
1639 config->sample_rate = mSampleRate;
1640 config->format = mFormat;
1641 config->channel_mask = mChannelMask;
1642 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1643 AUDIO_PORT_CONFIG_FORMAT;
1644}
1645
Eric Laurent72e3f392015-05-20 14:43:50 -07001646void AudioFlinger::ThreadBase::systemReady()
1647{
1648 Mutex::Autolock _l(mLock);
1649 if (mSystemReady) {
1650 return;
1651 }
1652 mSystemReady = true;
1653
1654 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1655 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1656 }
1657 mPendingConfigEvents.clear();
1658}
1659
Eric Laurent83b88082014-06-20 18:31:16 -07001660
Eric Laurent81784c32012-11-19 14:55:58 -08001661// ----------------------------------------------------------------------------
1662// Playback
1663// ----------------------------------------------------------------------------
1664
1665AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1666 AudioStreamOut* output,
1667 audio_io_handle_t id,
1668 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001669 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001670 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001671 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001672 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001673 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001674 mMixerBuffer(NULL),
1675 mMixerBufferSize(0),
1676 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1677 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001678 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001679 mEffectBuffer(NULL),
1680 mEffectBufferSize(0),
1681 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1682 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001683 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001684 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001685 mSuspendedFrames(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001686 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001687 // mStreamTypes[] initialized in constructor body
1688 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001689 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001690 mMixerStatus(MIXER_IDLE),
1691 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001692 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001693 mBytesRemaining(0),
1694 mCurrentWriteLength(0),
1695 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001696 mWriteAckSequence(0),
1697 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001698 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001699 mScreenState(AudioFlinger::mScreenState),
1700 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001701 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001702 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001703{
Glenn Kastend7dca052015-03-05 16:05:54 -08001704 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1705 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001706
1707 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1708 // it would be safer to explicitly pass initial masterVolume/masterMute as
1709 // parameter.
1710 //
1711 // If the HAL we are using has support for master volume or master mute,
1712 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1713 // and the mute set to false).
1714 mMasterVolume = audioFlinger->masterVolume_l();
1715 mMasterMute = audioFlinger->masterMute_l();
1716 if (mOutput && mOutput->audioHwDev) {
1717 if (mOutput->audioHwDev->canSetMasterVolume()) {
1718 mMasterVolume = 1.0;
1719 }
1720
1721 if (mOutput->audioHwDev->canSetMasterMute()) {
1722 mMasterMute = false;
1723 }
1724 }
1725
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001726 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001727
Eric Laurent223fd5c2014-11-11 13:43:36 -08001728 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001729 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001730 stream = (audio_stream_type_t) (stream + 1)) {
1731 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1732 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1733 }
Eric Laurent81784c32012-11-19 14:55:58 -08001734}
1735
1736AudioFlinger::PlaybackThread::~PlaybackThread()
1737{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001738 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001739 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001740 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001741 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001742}
1743
1744void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1745{
1746 dumpInternals(fd, args);
1747 dumpTracks(fd, args);
1748 dumpEffectChains(fd, args);
1749}
1750
Glenn Kasten0f11b512014-01-31 16:18:54 -08001751void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001752{
1753 const size_t SIZE = 256;
1754 char buffer[SIZE];
1755 String8 result;
1756
Marco Nelissenb2208842014-02-07 14:00:50 -08001757 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001758 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1759 const stream_type_t *st = &mStreamTypes[i];
1760 if (i > 0) {
1761 result.appendFormat(", ");
1762 }
1763 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1764 if (st->mute) {
1765 result.append("M");
1766 }
1767 }
1768 result.append("\n");
1769 write(fd, result.string(), result.length());
1770 result.clear();
1771
Eric Laurent81784c32012-11-19 14:55:58 -08001772 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1773 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001774 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001775 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001776
1777 size_t numtracks = mTracks.size();
1778 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001779 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001780 size_t numactiveseen = 0;
1781 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001782 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001783 Track::appendDumpHeader(result);
1784 for (size_t i = 0; i < numtracks; ++i) {
1785 sp<Track> track = mTracks[i];
1786 if (track != 0) {
1787 bool active = mActiveTracks.indexOf(track) >= 0;
1788 if (active) {
1789 numactiveseen++;
1790 }
1791 track->dump(buffer, SIZE, active);
1792 result.append(buffer);
1793 }
1794 }
1795 } else {
1796 result.append("\n");
1797 }
1798 if (numactiveseen != numactive) {
1799 // some tracks in the active list were not in the tracks list
1800 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1801 " not in the track list\n");
1802 result.append(buffer);
1803 Track::appendDumpHeader(result);
1804 for (size_t i = 0; i < numactive; ++i) {
1805 sp<Track> track = mActiveTracks[i].promote();
1806 if (track != 0 && mTracks.indexOf(track) < 0) {
1807 track->dump(buffer, SIZE, true);
1808 result.append(buffer);
1809 }
1810 }
1811 }
1812
1813 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001814}
1815
1816void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1817{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001818 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001819
1820 dumpBase(fd, args);
1821
Elliott Hughes87cebad2014-05-22 10:14:43 -07001822 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001823 dprintf(fd, " Last write occurred (msecs): %llu\n",
1824 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001825 dprintf(fd, " Total writes: %d\n", mNumWrites);
1826 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1827 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1828 dprintf(fd, " Suspend count: %d\n", mSuspended);
1829 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1830 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1831 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1832 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001833 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001834 AudioStreamOut *output = mOutput;
1835 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1836 String8 flagsAsString = outputFlagsToString(flags);
1837 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001838}
1839
1840// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001841
1842void AudioFlinger::PlaybackThread::onFirstRef()
1843{
Glenn Kastend7dca052015-03-05 16:05:54 -08001844 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001845}
1846
1847// ThreadBase virtuals
1848void AudioFlinger::PlaybackThread::preExit()
1849{
1850 ALOGV(" preExit()");
1851 // FIXME this is using hard-coded strings but in the future, this functionality will be
1852 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001853 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1854 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001855}
1856
1857// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1858sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1859 const sp<AudioFlinger::Client>& client,
1860 audio_stream_type_t streamType,
1861 uint32_t sampleRate,
1862 audio_format_t format,
1863 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001864 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001865 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001866 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001867 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001868 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001869 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001870 status_t *status)
1871{
Glenn Kasten74935e42013-12-19 08:56:45 -08001872 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001873 sp<Track> track;
1874 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001875 audio_output_flags_t outputFlags = mOutput->flags;
1876
1877 // special case for FAST flag considered OK if fast mixer is present
1878 if (hasFastMixer()) {
1879 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1880 }
1881
1882 // Check if requested flags are compatible with output stream flags
1883 if ((*flags & outputFlags) != *flags) {
1884 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1885 *flags, outputFlags);
1886 *flags = (audio_output_flags_t)(*flags & outputFlags);
1887 }
Eric Laurent81784c32012-11-19 14:55:58 -08001888
Eric Laurent81784c32012-11-19 14:55:58 -08001889 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001890 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001891 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001892 // PCM data
1893 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001894 // TODO: extract as a data library function that checks that a computationally
1895 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001896 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001897 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1898 (channelMask == AUDIO_CHANNEL_OUT_MONO
1899 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001900 // hardware sample rate
1901 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001902 // normal mixer has an associated fast mixer
1903 hasFastMixer() &&
1904 // there are sufficient fast track slots available
1905 (mFastTrackAvailMask != 0)
1906 // FIXME test that MixerThread for this fast track has a capable output HAL
1907 // FIXME add a permission test also?
1908 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001909 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1910 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001911 // read the fast track multiplier property the first time it is needed
1912 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1913 if (ok != 0) {
1914 ALOGE("%s pthread_once failed: %d", __func__, ok);
1915 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001916 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001917 }
Eric Laurent4c415062016-06-17 16:14:16 -07001918
1919 // check compatibility with audio effects.
1920 { // scope for mLock
1921 Mutex::Autolock _l(mLock);
1922 // do not accept RAW flag if post processing are present. Note that post processing on
1923 // a fast mixer are necessarily hardware
1924 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
1925 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001926 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001927 "AUDIO_OUTPUT_FLAG_RAW denied: post processing effect present");
1928 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1929 }
1930 // Do not accept FAST flag if software global effects are present
1931 chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
1932 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001933 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001934 "AUDIO_OUTPUT_FLAG_RAW denied: global effect present");
1935 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1936 if (chain->hasSoftwareEffect()) {
1937 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software global effect present");
1938 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1939 }
1940 }
1941 // Do not accept FAST flag if the session has software effects
1942 chain = getEffectChain_l(sessionId);
1943 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001944 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001945 "AUDIO_OUTPUT_FLAG_RAW denied: effect present on session");
1946 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1947 if (chain->hasSoftwareEffect()) {
1948 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software effect present on session");
1949 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1950 }
1951 }
1952 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001953 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001954 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1955 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001956 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001957 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1958 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001959 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001960 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001961 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001962 audio_is_linear_pcm(format),
1963 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001964 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001965 }
1966 }
1967 // For normal PCM streaming tracks, update minimum frame count.
1968 // For compatibility with AudioTrack calculation, buffer depth is forced
1969 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1970 // This is probably too conservative, but legacy application code may depend on it.
1971 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001972 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001973 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001974 // this must match AudioTrack.cpp calculateMinFrameCount().
1975 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001976 uint32_t latencyMs = 0;
1977 lStatus = mOutput->stream->getLatency(&latencyMs);
1978 if (lStatus != OK) {
1979 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1980 goto Exit;
1981 }
Eric Laurent81784c32012-11-19 14:55:58 -08001982 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1983 if (minBufCount < 2) {
1984 minBufCount = 2;
1985 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001986 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1987 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001988 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001989 minBufCount * sourceFramesNeededWithTimestretch(
1990 sampleRate, mNormalFrameCount,
1991 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001992 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001993 frameCount = minFrameCount;
1994 }
Eric Laurent81784c32012-11-19 14:55:58 -08001995 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001996 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001997
Glenn Kastenc3df8382014-03-13 15:05:25 -07001998 switch (mType) {
1999
2000 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002001 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002002 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002003 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2004 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002005 sampleRate, format, channelMask, mOutput, mFormat);
2006 lStatus = BAD_VALUE;
2007 goto Exit;
2008 }
2009 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002010 break;
2011
2012 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002013 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002014 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2015 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002016 sampleRate, format, channelMask, mOutput, mFormat);
2017 lStatus = BAD_VALUE;
2018 goto Exit;
2019 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002020 break;
2021
2022 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002023 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002024 ALOGE("createTrack_l() Bad parameter: format %#x \""
2025 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002026 format, mOutput, mFormat);
2027 lStatus = BAD_VALUE;
2028 goto Exit;
2029 }
Andy Hungcd044842014-08-07 11:04:34 -07002030 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002031 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2032 lStatus = BAD_VALUE;
2033 goto Exit;
2034 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002035 break;
2036
Eric Laurent81784c32012-11-19 14:55:58 -08002037 }
2038
2039 lStatus = initCheck();
2040 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002041 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002042 goto Exit;
2043 }
2044
2045 { // scope for mLock
2046 Mutex::Autolock _l(mLock);
2047
2048 // all tracks in same audio session must share the same routing strategy otherwise
2049 // conflicts will happen when tracks are moved from one output to another by audio policy
2050 // manager
2051 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2052 for (size_t i = 0; i < mTracks.size(); ++i) {
2053 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002054 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002055 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2056 if (sessionId == t->sessionId() && strategy != actual) {
2057 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2058 strategy, actual);
2059 lStatus = BAD_VALUE;
2060 goto Exit;
2061 }
2062 }
2063 }
2064
Glenn Kastend79072e2016-01-06 08:41:20 -08002065 track = new Track(this, client, streamType, sampleRate, format,
2066 channelMask, frameCount, NULL, sharedBuffer,
2067 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002068
Glenn Kasten03003332013-08-06 15:40:54 -07002069 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2070 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002071 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002072 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002073 goto Exit;
2074 }
2075 mTracks.add(track);
2076
2077 sp<EffectChain> chain = getEffectChain_l(sessionId);
2078 if (chain != 0) {
2079 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2080 track->setMainBuffer(chain->inBuffer());
2081 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2082 chain->incTrackCnt();
2083 }
2084
Eric Laurent05067782016-06-01 18:27:28 -07002085 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002086 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2087 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2088 // so ask activity manager to do this on our behalf
2089 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2090 }
2091 }
2092
2093 lStatus = NO_ERROR;
2094
2095Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002096 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002097 return track;
2098}
2099
2100uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2101{
2102 return latency;
2103}
2104
2105uint32_t AudioFlinger::PlaybackThread::latency() const
2106{
2107 Mutex::Autolock _l(mLock);
2108 return latency_l();
2109}
2110uint32_t AudioFlinger::PlaybackThread::latency_l() const
2111{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002112 uint32_t latency;
2113 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2114 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002115 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002116 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002117}
2118
2119void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2120{
2121 Mutex::Autolock _l(mLock);
2122 // Don't apply master volume in SW if our HAL can do it for us.
2123 if (mOutput && mOutput->audioHwDev &&
2124 mOutput->audioHwDev->canSetMasterVolume()) {
2125 mMasterVolume = 1.0;
2126 } else {
2127 mMasterVolume = value;
2128 }
2129}
2130
2131void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2132{
2133 Mutex::Autolock _l(mLock);
2134 // Don't apply master mute in SW if our HAL can do it for us.
2135 if (mOutput && mOutput->audioHwDev &&
2136 mOutput->audioHwDev->canSetMasterMute()) {
2137 mMasterMute = false;
2138 } else {
2139 mMasterMute = muted;
2140 }
2141}
2142
2143void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2144{
2145 Mutex::Autolock _l(mLock);
2146 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002147 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002148}
2149
2150void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2151{
2152 Mutex::Autolock _l(mLock);
2153 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002154 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002155}
2156
2157float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2158{
2159 Mutex::Autolock _l(mLock);
2160 return mStreamTypes[stream].volume;
2161}
2162
2163// addTrack_l() must be called with ThreadBase::mLock held
2164status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2165{
2166 status_t status = ALREADY_EXISTS;
2167
Eric Laurent81784c32012-11-19 14:55:58 -08002168 if (mActiveTracks.indexOf(track) < 0) {
2169 // the track is newly added, make sure it fills up all its
2170 // buffers before playing. This is to ensure the client will
2171 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002172 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002173 TrackBase::track_state state = track->mState;
2174 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002175 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002176 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002177 mLock.lock();
2178 // abort track was stopped/paused while we released the lock
2179 if (state != track->mState) {
2180 if (status == NO_ERROR) {
2181 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002182 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002183 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002184 mLock.lock();
2185 }
2186 return INVALID_OPERATION;
2187 }
2188 // abort if start is rejected by audio policy manager
2189 if (status != NO_ERROR) {
2190 return PERMISSION_DENIED;
2191 }
2192#ifdef ADD_BATTERY_DATA
2193 // to track the speaker usage
2194 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2195#endif
2196 }
2197
Eric Laurent51716182016-02-29 18:00:56 -08002198 // set retry count for buffer fill
2199 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002200 if (track->isStopping_1()) {
2201 track->mRetryCount = kMaxTrackStopRetriesOffload;
2202 } else {
2203 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2204 }
2205 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002206 } else {
2207 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002208 track->mFillingUpStatus =
2209 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002210 }
2211
Eric Laurent81784c32012-11-19 14:55:58 -08002212 track->mResetDone = false;
2213 track->mPresentationCompleteFrames = 0;
2214 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002215 mWakeLockUids.add(track->uid());
2216 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002217 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002218 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2219 if (chain != 0) {
2220 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2221 track->sessionId());
2222 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002223 }
2224
2225 status = NO_ERROR;
2226 }
2227
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002228 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002229 return status;
2230}
2231
Eric Laurentbfb1b832013-01-07 09:53:42 -08002232bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002233{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002234 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002235 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002236 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2237 track->mState = TrackBase::STOPPED;
2238 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002239 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002240 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002241 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002242 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002243
2244 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002245}
2246
2247void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2248{
2249 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2250 mTracks.remove(track);
2251 deleteTrackName_l(track->name());
2252 // redundant as track is about to be destroyed, for dumpsys only
2253 track->mName = -1;
2254 if (track->isFastTrack()) {
2255 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002256 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002257 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2258 mFastTrackAvailMask |= 1 << index;
2259 // redundant as track is about to be destroyed, for dumpsys only
2260 track->mFastIndex = -1;
2261 }
2262 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2263 if (chain != 0) {
2264 chain->decTrackCnt();
2265 }
2266}
2267
Eric Laurentede6c3b2013-09-19 14:37:46 -07002268void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002269{
2270 // Thread could be blocked waiting for async
2271 // so signal it to handle state changes immediately
2272 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2273 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2274 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002275 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002276}
2277
Eric Laurent81784c32012-11-19 14:55:58 -08002278String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2279{
Eric Laurent81784c32012-11-19 14:55:58 -08002280 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002281 String8 out_s8;
2282 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2283 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002284 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002285 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002286}
2287
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002288void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002289 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2290 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002291
Eric Laurent73e26b62015-04-27 16:55:58 -07002292 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002293
2294 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002295 case AUDIO_OUTPUT_OPENED:
2296 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002297 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002298 desc->mChannelMask = mChannelMask;
2299 desc->mSamplingRate = mSampleRate;
2300 desc->mFormat = mFormat;
2301 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002302 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002303 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002304 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002305 break;
2306
Eric Laurent73e26b62015-04-27 16:55:58 -07002307 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002308 default:
2309 break;
2310 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002311 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002312}
2313
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002314void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002315{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002316 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002317}
2318
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002319void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002320{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002321 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002322}
2323
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002324void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002325{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002326 mCallbackThread->setAsyncError();
2327}
2328
Eric Laurent3b4529e2013-09-05 18:09:19 -07002329void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330{
2331 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002332 // reject out of sequence requests
2333 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2334 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002335 mWaitWorkCV.signal();
2336 }
2337}
2338
Eric Laurent3b4529e2013-09-05 18:09:19 -07002339void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002340{
2341 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002342 // reject out of sequence requests
2343 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2344 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002345 mWaitWorkCV.signal();
2346 }
2347}
2348
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002349void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002350{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002351 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002352 mSampleRate = mOutput->getSampleRate();
2353 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002354 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002355 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002356 }
Andy Hung9a592762014-07-21 21:56:01 -07002357 if ((mType == MIXER || mType == DUPLICATING)
2358 && !isValidPcmSinkChannelMask(mChannelMask)) {
2359 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2360 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002361 }
Andy Hunge5412692014-05-16 11:25:07 -07002362 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002363
2364 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002365 status_t result = mOutput->stream->getFormat(&mHALFormat);
2366 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002367 // Get format from the shim, which will be different than the HAL format
2368 // if playing compressed audio over HDMI passthrough.
2369 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002370 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002371 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002372 }
Andy Hung6146c082014-03-18 11:56:15 -07002373 if ((mType == MIXER || mType == DUPLICATING)
2374 && !isValidPcmSinkFormat(mFormat)) {
2375 LOG_FATAL("HAL format %#x not supported for mixed output",
2376 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002377 }
Phil Burk062e67a2015-02-11 13:40:50 -08002378 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002379 result = mOutput->stream->getBufferSize(&mBufferSize);
2380 LOG_ALWAYS_FATAL_IF(result != OK,
2381 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002382 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002383 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002384 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002385 mFrameCount);
2386 }
2387
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002388 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2389 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002391 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002392 }
2393 }
2394
Eric Laurentd1f69b02014-12-15 14:33:13 -08002395 mHwSupportsPause = false;
2396 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002397 bool supportsPause = false, supportsResume = false;
2398 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2399 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002400 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002401 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002402 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002403 } else if (supportsResume) {
2404 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002405 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002406 }
2407 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002408 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2409 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2410 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002411
Andy Hungfbfc3952015-01-15 13:33:51 -08002412 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2413 // For best precision, we use float instead of the associated output
2414 // device format (typically PCM 16 bit).
2415
2416 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2417 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2418 mBufferSize = mFrameSize * mFrameCount;
2419
2420 // TODO: We currently use the associated output device channel mask and sample rate.
2421 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2422 // (if a valid mask) to avoid premature downmix.
2423 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2424 // instead of the output device sample rate to avoid loss of high frequency information.
2425 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2426 }
2427
Andy Hung09a50072014-02-27 14:30:47 -08002428 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002429 double multiplier = 1.0;
2430 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2431 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002432 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2433 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002434
Eric Laurent81784c32012-11-19 14:55:58 -08002435 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2436 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2437 maxNormalFrameCount = maxNormalFrameCount & ~15;
2438 if (maxNormalFrameCount < minNormalFrameCount) {
2439 maxNormalFrameCount = minNormalFrameCount;
2440 }
2441 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2442 if (multiplier <= 1.0) {
2443 multiplier = 1.0;
2444 } else if (multiplier <= 2.0) {
2445 if (2 * mFrameCount <= maxNormalFrameCount) {
2446 multiplier = 2.0;
2447 } else {
2448 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2449 }
2450 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002451 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002452 }
2453 }
2454 mNormalFrameCount = multiplier * mFrameCount;
2455 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002456 if (mType == MIXER || mType == DUPLICATING) {
2457 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2458 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002459 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002460 mNormalFrameCount);
2461
Andy Hung08fb1742015-05-31 23:22:10 -07002462 // Check if we want to throttle the processing to no more than 2x normal rate
2463 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002464 mThreadThrottleTimeMs = 0;
2465 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002466 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2467
Andy Hung010a1a12014-03-13 13:57:33 -07002468 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2469 // Originally this was int16_t[] array, need to remove legacy implications.
2470 free(mSinkBuffer);
2471 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002472 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2473 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2474 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002475 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002476
Andy Hung69aed5f2014-02-25 17:24:40 -08002477 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2478 // drives the output.
2479 free(mMixerBuffer);
2480 mMixerBuffer = NULL;
2481 if (mMixerBufferEnabled) {
2482 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2483 mMixerBufferSize = mNormalFrameCount * mChannelCount
2484 * audio_bytes_per_sample(mMixerBufferFormat);
2485 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2486 }
Andy Hung98ef9782014-03-04 14:46:50 -08002487 free(mEffectBuffer);
2488 mEffectBuffer = NULL;
2489 if (mEffectBufferEnabled) {
2490 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2491 mEffectBufferSize = mNormalFrameCount * mChannelCount
2492 * audio_bytes_per_sample(mEffectBufferFormat);
2493 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2494 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002495
Eric Laurent81784c32012-11-19 14:55:58 -08002496 // force reconfiguration of effect chains and engines to take new buffer size and audio
2497 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002498 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002499 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2500 // matter.
2501 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2502 Vector< sp<EffectChain> > effectChains = mEffectChains;
2503 for (size_t i = 0; i < effectChains.size(); i ++) {
2504 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2505 }
2506}
2507
2508
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002509status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002510{
2511 if (halFrames == NULL || dspFrames == NULL) {
2512 return BAD_VALUE;
2513 }
2514 Mutex::Autolock _l(mLock);
2515 if (initCheck() != NO_ERROR) {
2516 return INVALID_OPERATION;
2517 }
Andy Hung818e7a32016-02-16 18:08:07 -08002518 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002519 *halFrames = framesWritten;
2520
2521 if (isSuspended()) {
2522 // return an estimation of rendered frames when the output is suspended
2523 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002524 *dspFrames = (uint32_t)
2525 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002526 return NO_ERROR;
2527 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002528 status_t status;
2529 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002530 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002531 *dspFrames = (size_t)frames;
2532 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002533 }
2534}
2535
Eric Laurent4c415062016-06-17 16:14:16 -07002536// hasAudioSession_l() must be called with ThreadBase::mLock held
2537uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002538{
Eric Laurent81784c32012-11-19 14:55:58 -08002539 uint32_t result = 0;
2540 if (getEffectChain_l(sessionId) != 0) {
2541 result = EFFECT_SESSION;
2542 }
2543
2544 for (size_t i = 0; i < mTracks.size(); ++i) {
2545 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002546 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002547 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002548 if (track->isFastTrack()) {
2549 result |= FAST_SESSION;
2550 }
Eric Laurent81784c32012-11-19 14:55:58 -08002551 break;
2552 }
2553 }
2554
2555 return result;
2556}
2557
Glenn Kastend848eb42016-03-08 13:42:11 -08002558uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002559{
2560 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2561 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2562 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2563 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2564 }
2565 for (size_t i = 0; i < mTracks.size(); i++) {
2566 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002567 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002568 return AudioSystem::getStrategyForStream(track->streamType());
2569 }
2570 }
2571 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2572}
2573
2574
Phil Burk062e67a2015-02-11 13:40:50 -08002575AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002576{
2577 Mutex::Autolock _l(mLock);
2578 return mOutput;
2579}
2580
Phil Burk062e67a2015-02-11 13:40:50 -08002581AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002582{
2583 Mutex::Autolock _l(mLock);
2584 AudioStreamOut *output = mOutput;
2585 mOutput = NULL;
2586 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2587 // must push a NULL and wait for ack
2588 mOutputSink.clear();
2589 mPipeSink.clear();
2590 mNormalSink.clear();
2591 return output;
2592}
2593
2594// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002595sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002596{
2597 if (mOutput == NULL) {
2598 return NULL;
2599 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002600 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002601}
2602
2603uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2604{
2605 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2606}
2607
2608status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2609{
2610 if (!isValidSyncEvent(event)) {
2611 return BAD_VALUE;
2612 }
2613
2614 Mutex::Autolock _l(mLock);
2615
2616 for (size_t i = 0; i < mTracks.size(); ++i) {
2617 sp<Track> track = mTracks[i];
2618 if (event->triggerSession() == track->sessionId()) {
2619 (void) track->setSyncEvent(event);
2620 return NO_ERROR;
2621 }
2622 }
2623
2624 return NAME_NOT_FOUND;
2625}
2626
2627bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2628{
2629 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2630}
2631
2632void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2633 const Vector< sp<Track> >& tracksToRemove)
2634{
2635 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002636 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002637 for (size_t i = 0 ; i < count ; i++) {
2638 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002639 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002640 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002641 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642#ifdef ADD_BATTERY_DATA
2643 // to track the speaker usage
2644 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2645#endif
2646 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002647 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002648 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002649 }
Eric Laurent81784c32012-11-19 14:55:58 -08002650 }
2651 }
2652 }
Eric Laurent81784c32012-11-19 14:55:58 -08002653}
2654
2655void AudioFlinger::PlaybackThread::checkSilentMode_l()
2656{
2657 if (!mMasterMute) {
2658 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002659 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2660 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2661 return;
2662 }
Eric Laurent81784c32012-11-19 14:55:58 -08002663 if (property_get("ro.audio.silent", value, "0") > 0) {
2664 char *endptr;
2665 unsigned long ul = strtoul(value, &endptr, 0);
2666 if (*endptr == '\0' && ul != 0) {
2667 ALOGD("Silence is golden");
2668 // The setprop command will not allow a property to be changed after
2669 // the first time it is set, so we don't have to worry about un-muting.
2670 setMasterMute_l(true);
2671 }
2672 }
2673 }
2674}
2675
2676// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002678{
Eric Laurent81784c32012-11-19 14:55:58 -08002679 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002680 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002681 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002682
2683 // If an NBAIO sink is present, use it to write the normal mixer's submix
2684 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002685
Andy Hung010a1a12014-03-13 13:57:33 -07002686 const size_t count = mBytesRemaining / mFrameSize;
2687
Simon Wilson2d590962012-11-29 15:18:50 -08002688 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002689 // update the setpoint when AudioFlinger::mScreenState changes
2690 uint32_t screenState = AudioFlinger::mScreenState;
2691 if (screenState != mScreenState) {
2692 mScreenState = screenState;
2693 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2694 if (pipe != NULL) {
2695 pipe->setAvgFrames((mScreenState & 1) ?
2696 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2697 }
2698 }
Andy Hung010a1a12014-03-13 13:57:33 -07002699 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002700 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002701 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002702 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002703 } else {
2704 bytesWritten = framesWritten;
2705 }
2706 // otherwise use the HAL / AudioStreamOut directly
2707 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002708 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002709
Eric Laurentbfb1b832013-01-07 09:53:42 -08002710 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002711 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2712 mWriteAckSequence += 2;
2713 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002714 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002715 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002716 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002717 // FIXME We should have an implementation of timestamps for direct output threads.
2718 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002719 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002720
Eric Laurentbfb1b832013-01-07 09:53:42 -08002721 if (mUseAsyncWrite &&
2722 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2723 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002724 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002725 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002726 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727 }
Eric Laurent81784c32012-11-19 14:55:58 -08002728 }
2729
Eric Laurent81784c32012-11-19 14:55:58 -08002730 mNumWrites++;
2731 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002732 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 return bytesWritten;
2734}
2735
2736void AudioFlinger::PlaybackThread::threadLoop_drain()
2737{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002738 bool supportsDrain = false;
2739 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002740 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2741 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002742 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2743 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002744 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002745 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002746 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002747 status_t result = mOutput->stream->drain(
Eric Laurentbfb1b832013-01-07 09:53:42 -08002748 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2749 : AUDIO_DRAIN_ALL);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002750 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002751 }
2752}
2753
2754void AudioFlinger::PlaybackThread::threadLoop_exit()
2755{
Eric Laurent275e8e92014-11-30 15:14:47 -08002756 {
2757 Mutex::Autolock _l(mLock);
2758 for (size_t i = 0; i < mTracks.size(); i++) {
2759 sp<Track> track = mTracks[i];
2760 track->invalidate();
2761 }
2762 }
Eric Laurent81784c32012-11-19 14:55:58 -08002763}
2764
2765/*
2766The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002767 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002768 - mActiveSleepTimeUs from activeSleepTimeUs()
2769 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002770 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2771 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002772 - maxPeriod from frame count and sample rate (MIXER only)
2773
2774The parameters that affect these derived values are:
2775 - frame count
2776 - frame size
2777 - sample rate
2778 - device type: A2DP or not
2779 - device latency
2780 - format: PCM or not
2781 - active sleep time
2782 - idle sleep time
2783*/
2784
2785void AudioFlinger::PlaybackThread::cacheParameters_l()
2786{
Andy Hung25c2dac2014-02-27 14:56:00 -08002787 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002788 mActiveSleepTimeUs = activeSleepTimeUs();
2789 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002790
2791 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2792 // truncating audio when going to standby.
2793 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2794 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2795 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2796 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2797 }
2798 }
Eric Laurent81784c32012-11-19 14:55:58 -08002799}
2800
Eric Laurent13084622016-05-17 10:51:49 -07002801bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002802{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002803 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002804 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002805 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002806 size_t size = mTracks.size();
2807 for (size_t i = 0; i < size; i++) {
2808 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002809 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002810 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002811 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002812 }
2813 }
Eric Laurent13084622016-05-17 10:51:49 -07002814 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002815}
2816
Haynes Mathew George05317d22016-05-03 16:34:26 -07002817void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2818{
2819 Mutex::Autolock _l(mLock);
2820 invalidateTracks_l(streamType);
2821}
2822
Eric Laurent81784c32012-11-19 14:55:58 -08002823status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2824{
Glenn Kastend848eb42016-03-08 13:42:11 -08002825 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002826 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2827 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002828 bool ownsBuffer = false;
2829
2830 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002831 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002832 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002833 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002834 if (mType != DIRECT) {
2835 size_t numSamples = mNormalFrameCount * mChannelCount;
2836 buffer = new int16_t[numSamples];
2837 memset(buffer, 0, numSamples * sizeof(int16_t));
2838 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2839 ownsBuffer = true;
2840 }
2841
2842 // Attach all tracks with same session ID to this chain.
2843 for (size_t i = 0; i < mTracks.size(); ++i) {
2844 sp<Track> track = mTracks[i];
2845 if (session == track->sessionId()) {
2846 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2847 buffer);
2848 track->setMainBuffer(buffer);
2849 chain->incTrackCnt();
2850 }
2851 }
2852
2853 // indicate all active tracks in the chain
2854 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2855 sp<Track> track = mActiveTracks[i].promote();
2856 if (track == 0) {
2857 continue;
2858 }
2859 if (session == track->sessionId()) {
2860 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2861 chain->incActiveTrackCnt();
2862 }
2863 }
2864 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002865 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002866 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002867 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2868 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002869 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002870 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002871 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2872 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002873 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002874 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002875 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002876 // Effect chain for other sessions are inserted at beginning of effect
2877 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002878 // sessions is not important.
2879 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2880 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2881 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002882 size_t size = mEffectChains.size();
2883 size_t i = 0;
2884 for (i = 0; i < size; i++) {
2885 if (mEffectChains[i]->sessionId() < session) {
2886 break;
2887 }
2888 }
2889 mEffectChains.insertAt(chain, i);
2890 checkSuspendOnAddEffectChain_l(chain);
2891
2892 return NO_ERROR;
2893}
2894
2895size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2896{
Glenn Kastend848eb42016-03-08 13:42:11 -08002897 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002898
2899 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2900
2901 for (size_t i = 0; i < mEffectChains.size(); i++) {
2902 if (chain == mEffectChains[i]) {
2903 mEffectChains.removeAt(i);
2904 // detach all active tracks from the chain
2905 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2906 sp<Track> track = mActiveTracks[i].promote();
2907 if (track == 0) {
2908 continue;
2909 }
2910 if (session == track->sessionId()) {
2911 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2912 chain.get(), session);
2913 chain->decActiveTrackCnt();
2914 }
2915 }
2916
2917 // detach all tracks with same session ID from this chain
2918 for (size_t i = 0; i < mTracks.size(); ++i) {
2919 sp<Track> track = mTracks[i];
2920 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002921 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002922 chain->decTrackCnt();
2923 }
2924 }
2925 break;
2926 }
2927 }
2928 return mEffectChains.size();
2929}
2930
2931status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002932 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002933{
2934 Mutex::Autolock _l(mLock);
2935 return attachAuxEffect_l(track, EffectId);
2936}
2937
2938status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002939 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002940{
2941 status_t status = NO_ERROR;
2942
2943 if (EffectId == 0) {
2944 track->setAuxBuffer(0, NULL);
2945 } else {
2946 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2947 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2948 if (effect != 0) {
2949 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2950 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2951 } else {
2952 status = INVALID_OPERATION;
2953 }
2954 } else {
2955 status = BAD_VALUE;
2956 }
2957 }
2958 return status;
2959}
2960
2961void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2962{
2963 for (size_t i = 0; i < mTracks.size(); ++i) {
2964 sp<Track> track = mTracks[i];
2965 if (track->auxEffectId() == effectId) {
2966 attachAuxEffect_l(track, 0);
2967 }
2968 }
2969}
2970
2971bool AudioFlinger::PlaybackThread::threadLoop()
2972{
2973 Vector< sp<Track> > tracksToRemove;
2974
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002975 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002976 nsecs_t lastWriteFinished = -1; // time last server write completed
2977 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002978
2979 // MIXER
2980 nsecs_t lastWarning = 0;
2981
2982 // DUPLICATING
2983 // FIXME could this be made local to while loop?
2984 writeFrames = 0;
2985
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002986 int lastGeneration = 0;
2987
Eric Laurent81784c32012-11-19 14:55:58 -08002988 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002989 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002990
2991 if (mType == MIXER) {
2992 sleepTimeShift = 0;
2993 }
2994
2995 CpuStats cpuStats;
2996 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2997
2998 acquireWakeLock();
2999
Glenn Kasten9e58b552013-01-18 15:09:48 -08003000 // mNBLogWriter->log can only be called while thread mutex mLock is held.
3001 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3002 // and then that string will be logged at the next convenient opportunity.
3003 const char *logString = NULL;
3004
Eric Laurent664539d2013-09-23 18:24:31 -07003005 checkSilentMode_l();
3006
Eric Laurent81784c32012-11-19 14:55:58 -08003007 while (!exitPending())
3008 {
3009 cpuStats.sample(myName);
3010
3011 Vector< sp<EffectChain> > effectChains;
3012
Eric Laurent81784c32012-11-19 14:55:58 -08003013 { // scope for mLock
3014
3015 Mutex::Autolock _l(mLock);
3016
Eric Laurent021cf962014-05-13 10:18:14 -07003017 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003018
Glenn Kasten9e58b552013-01-18 15:09:48 -08003019 if (logString != NULL) {
3020 mNBLogWriter->logTimestamp();
3021 mNBLogWriter->log(logString);
3022 logString = NULL;
3023 }
3024
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003025 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003026 // and associate with the sink frames written out. We need
3027 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003028 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003029 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003030 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003031 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003032 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003033 ExtendedTimestamp timestamp; // use private copy to fetch
3034 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003035
3036 // We keep track of the last valid kernel position in case we are in underrun
3037 // and the normal mixer period is the same as the fast mixer period, or there
3038 // is some error from the HAL.
3039 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3040 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3041 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3042 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3043 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3044
3045 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3046 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3047 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3048 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003049 }
3050
3051 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3052 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003053 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003054 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003055 }
3056
Andy Hung818e7a32016-02-16 18:08:07 -08003057 // copy over kernel info
3058 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003059 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3060 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003061 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3062 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003063 }
3064 // mFramesWritten for non-offloaded tracks are contiguous
3065 // even after standby() is called. This is useful for the track frame
3066 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003067 bool serverLocationUpdate = false;
3068 if (mFramesWritten != lastFramesWritten) {
3069 serverLocationUpdate = true;
3070 lastFramesWritten = mFramesWritten;
3071 }
3072 // Only update timestamps if there is a meaningful change.
3073 // Either the kernel timestamp must be valid or we have written something.
3074 if (kernelLocationUpdate || serverLocationUpdate) {
3075 if (serverLocationUpdate) {
3076 // use the time before we called the HAL write - it is a bit more accurate
3077 // to when the server last read data than the current time here.
3078 //
3079 // If we haven't written anything, mLastWriteTime will be -1
3080 // and we use systemTime().
3081 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3082 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3083 ? systemTime() : mLastWriteTime;
3084 }
3085 const size_t size = mActiveTracks.size();
3086 for (size_t i = 0; i < size; ++i) {
3087 sp<Track> t = mActiveTracks[i].promote();
3088 if (t != 0 && !t->isFastTrack()) {
3089 t->updateTrackFrameInfo(
3090 t->mAudioTrackServerProxy->framesReleased(),
3091 mFramesWritten,
3092 mTimestamp);
3093 }
Andy Hunge10393e2015-06-12 13:59:33 -07003094 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003095 }
3096
Eric Laurent81784c32012-11-19 14:55:58 -08003097 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003098 if (mSignalPending) {
3099 // A signal was raised while we were unlocked
3100 mSignalPending = false;
3101 } else if (waitingAsyncCallback_l()) {
3102 if (exitPending()) {
3103 break;
3104 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003105 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003106 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003107 releaseWakeLock_l();
3108 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07003109 mWakeLockUids.clear();
3110 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07003111 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112 ALOGV("wait async completion");
3113 mWaitWorkCV.wait(mLock);
3114 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003115 if (released) {
3116 acquireWakeLock_l();
3117 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003118 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3119 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003120
3121 continue;
3122 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003123 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003124 isSuspended()) {
3125 // put audio hardware into standby after short delay
3126 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003127
3128 threadLoop_standby();
3129
3130 mStandby = true;
3131 }
3132
3133 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3134 // we're about to wait, flush the binder command buffer
3135 IPCThreadState::self()->flushCommands();
3136
3137 clearOutputTracks();
3138
3139 if (exitPending()) {
3140 break;
3141 }
3142
3143 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003144 mWakeLockUids.clear();
3145 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003146 // wait until we have something to do...
3147 ALOGV("%s going to sleep", myName.string());
3148 mWaitWorkCV.wait(mLock);
3149 ALOGV("%s waking up", myName.string());
3150 acquireWakeLock_l();
3151
3152 mMixerStatus = MIXER_IDLE;
3153 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3154 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003155 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003156 checkSilentMode_l();
3157
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003158 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3159 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003160 if (mType == MIXER) {
3161 sleepTimeShift = 0;
3162 }
3163
3164 continue;
3165 }
3166 }
Eric Laurent81784c32012-11-19 14:55:58 -08003167 // mMixerStatusIgnoringFastTracks is also updated internally
3168 mMixerStatus = prepareTracks_l(&tracksToRemove);
3169
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003170 // compare with previously applied list
3171 if (lastGeneration != mActiveTracksGeneration) {
3172 // update wakelock
3173 updateWakeLockUids_l(mWakeLockUids);
3174 lastGeneration = mActiveTracksGeneration;
3175 }
3176
Eric Laurent81784c32012-11-19 14:55:58 -08003177 // prevent any changes in effect chain list and in each effect chain
3178 // during mixing and effect process as the audio buffers could be deleted
3179 // or modified if an effect is created or deleted
3180 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003181 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003182
Eric Laurentbfb1b832013-01-07 09:53:42 -08003183 if (mBytesRemaining == 0) {
3184 mCurrentWriteLength = 0;
3185 if (mMixerStatus == MIXER_TRACKS_READY) {
3186 // threadLoop_mix() sets mCurrentWriteLength
3187 threadLoop_mix();
3188 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3189 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003190 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003191 // must be written to HAL
3192 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003193 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003194 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003195 }
3196 }
Andy Hung98ef9782014-03-04 14:46:50 -08003197 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003198 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003199 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3200 // or mSinkBuffer (if there are no effects).
3201 //
3202 // This is done pre-effects computation; if effects change to
3203 // support higher precision, this needs to move.
3204 //
3205 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003206 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003207 if (mMixerBufferValid) {
3208 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3209 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3210
Andy Hung2ddee192015-12-18 17:34:44 -08003211 // mono blend occurs for mixer threads only (not direct or offloaded)
3212 // and is handled here if we're going directly to the sink.
3213 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003214 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3215 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003216 }
3217
Andy Hung98ef9782014-03-04 14:46:50 -08003218 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3219 mNormalFrameCount * mChannelCount);
3220 }
3221
Eric Laurentbfb1b832013-01-07 09:53:42 -08003222 mBytesRemaining = mCurrentWriteLength;
3223 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003224 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3225 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3226 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3227 mBytesWritten += mBytesRemaining;
3228 mFramesWritten += framesRemaining;
3229 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003230 mBytesRemaining = 0;
3231 }
Eric Laurent81784c32012-11-19 14:55:58 -08003232
Eric Laurentbfb1b832013-01-07 09:53:42 -08003233 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003234 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003235 for (size_t i = 0; i < effectChains.size(); i ++) {
3236 effectChains[i]->process_l();
3237 }
Eric Laurent81784c32012-11-19 14:55:58 -08003238 }
3239 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003240 // Process effect chains for offloaded thread even if no audio
3241 // was read from audio track: process only updates effect state
3242 // and thus does have to be synchronized with audio writes but may have
3243 // to be called while waiting for async write callback
3244 if (mType == OFFLOAD) {
3245 for (size_t i = 0; i < effectChains.size(); i ++) {
3246 effectChains[i]->process_l();
3247 }
3248 }
Eric Laurent81784c32012-11-19 14:55:58 -08003249
Andy Hung98ef9782014-03-04 14:46:50 -08003250 // Only if the Effects buffer is enabled and there is data in the
3251 // Effects buffer (buffer valid), we need to
3252 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003253 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003254 if (mEffectBufferValid) {
3255 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003256
3257 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003258 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3259 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003260 }
3261
Andy Hung98ef9782014-03-04 14:46:50 -08003262 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3263 mNormalFrameCount * mChannelCount);
3264 }
3265
Eric Laurent81784c32012-11-19 14:55:58 -08003266 // enable changes in effect chain
3267 unlockEffectChains(effectChains);
3268
Eric Laurentbfb1b832013-01-07 09:53:42 -08003269 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003270 // mSleepTimeUs == 0 means we must write to audio hardware
3271 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003272 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003273 // We save lastWriteFinished here, as previousLastWriteFinished,
3274 // for throttling. On thread start, previousLastWriteFinished will be
3275 // set to -1, which properly results in no throttling after the first write.
3276 nsecs_t previousLastWriteFinished = lastWriteFinished;
3277 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003278 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003279 // FIXME rewrite to reduce number of system calls
3280 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003281 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003282 lastWriteFinished = systemTime();
3283 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003284 if (ret < 0) {
3285 mBytesRemaining = 0;
3286 } else {
3287 mBytesWritten += ret;
3288 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003289 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003290 }
3291 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3292 (mMixerStatus == MIXER_DRAIN_ALL)) {
3293 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003294 }
Andy Hung08fb1742015-05-31 23:22:10 -07003295 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003296 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003297 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003298 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003299 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003300 ATRACE_NAME("underrun");
3301 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003302 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003303 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003304 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003305 }
Andy Hung08fb1742015-05-31 23:22:10 -07003306
3307 if (mThreadThrottle
3308 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3309 && ret > 0) { // we wrote something
3310 // Limit MixerThread data processing to no more than twice the
3311 // expected processing rate.
3312 //
3313 // This helps prevent underruns with NuPlayer and other applications
3314 // which may set up buffers that are close to the minimum size, or use
3315 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3316 //
3317 // The throttle smooths out sudden large data drains from the device,
3318 // e.g. when it comes out of standby, which often causes problems with
3319 // (1) mixer threads without a fast mixer (which has its own warm-up)
3320 // (2) minimum buffer sized tracks (even if the track is full,
3321 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003322 //
3323 // Total time spent in last processing cycle equals time spent in
3324 // 1. threadLoop_write, as well as time spent in
3325 // 2. threadLoop_mix (significant for heavy mixing, especially
3326 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003327
Andy Hung69488c42016-05-16 18:43:33 -07003328 // it's OK if deltaMs is an overestimate.
3329 const int32_t deltaMs =
3330 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003331 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3332 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3333 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003334 // notify of throttle start on verbose log
3335 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3336 "mixer(%p) throttle begin:"
3337 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003338 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003339 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003340 // Throttle must be attributed to the previous mixer loop's write time
3341 // to allow back-to-back throttling.
3342 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003343 } else {
3344 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3345 if (diff > 0) {
3346 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003347 // but prevent spamming for bluetooth
3348 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3349 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003350 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3351 }
Andy Hung08fb1742015-05-31 23:22:10 -07003352 }
3353 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003354 }
Eric Laurent81784c32012-11-19 14:55:58 -08003355
Eric Laurentbfb1b832013-01-07 09:53:42 -08003356 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003357 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003358 Mutex::Autolock _l(mLock);
3359 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3360 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003361 }
Glenn Kastene7754022014-10-31 12:11:26 -07003362 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003363 }
Eric Laurent81784c32012-11-19 14:55:58 -08003364 }
3365
3366 // Finally let go of removed track(s), without the lock held
3367 // since we can't guarantee the destructors won't acquire that
3368 // same lock. This will also mutate and push a new fast mixer state.
3369 threadLoop_removeTracks(tracksToRemove);
3370 tracksToRemove.clear();
3371
3372 // FIXME I don't understand the need for this here;
3373 // it was in the original code but maybe the
3374 // assignment in saveOutputTracks() makes this unnecessary?
3375 clearOutputTracks();
3376
3377 // Effect chains will be actually deleted here if they were removed from
3378 // mEffectChains list during mixing or effects processing
3379 effectChains.clear();
3380
3381 // FIXME Note that the above .clear() is no longer necessary since effectChains
3382 // is now local to this block, but will keep it for now (at least until merge done).
3383 }
3384
Eric Laurentbfb1b832013-01-07 09:53:42 -08003385 threadLoop_exit();
3386
Eric Laurentcf817a22014-08-04 20:36:31 -07003387 if (!mStandby) {
3388 threadLoop_standby();
3389 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003390 }
3391
3392 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003393 mWakeLockUids.clear();
3394 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003395
3396 ALOGV("Thread %p type %d exiting", this, mType);
3397 return false;
3398}
3399
Eric Laurentbfb1b832013-01-07 09:53:42 -08003400// removeTracks_l() must be called with ThreadBase::mLock held
3401void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3402{
3403 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003404 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003405 for (size_t i=0 ; i<count ; i++) {
3406 const sp<Track>& track = tracksToRemove.itemAt(i);
3407 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003408 mWakeLockUids.remove(track->uid());
3409 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003410 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3411 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3412 if (chain != 0) {
3413 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3414 track->sessionId());
3415 chain->decActiveTrackCnt();
3416 }
3417 if (track->isTerminated()) {
3418 removeTrack_l(track);
3419 }
3420 }
3421 }
3422
3423}
Eric Laurent81784c32012-11-19 14:55:58 -08003424
Eric Laurentaccc1472013-09-20 09:36:34 -07003425status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3426{
3427 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003428 ExtendedTimestamp ets;
3429 status_t status = mNormalSink->getTimestamp(ets);
3430 if (status == NO_ERROR) {
3431 status = ets.getBestTimestamp(&timestamp);
3432 }
3433 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003434 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003435 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003436 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003437 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003438 timestamp.mPosition = (uint32_t)position64;
3439 return NO_ERROR;
3440 }
3441 }
3442 return INVALID_OPERATION;
3443}
Eric Laurent1c333e22014-05-20 10:48:17 -07003444
Eric Laurent054d9d32015-04-24 08:48:48 -07003445status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3446 audio_patch_handle_t *handle)
3447{
Andy Hungf60abce2016-08-26 11:37:54 -07003448 status_t status;
3449 if (property_get_bool("af.patch_park", false /* default_value */)) {
3450 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3451 // or if HAL does not properly lock against access.
3452 AutoPark<FastMixer> park(mFastMixer);
3453 status = PlaybackThread::createAudioPatch_l(patch, handle);
3454 } else {
3455 status = PlaybackThread::createAudioPatch_l(patch, handle);
3456 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003457 return status;
3458}
3459
Eric Laurent1c333e22014-05-20 10:48:17 -07003460status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3461 audio_patch_handle_t *handle)
3462{
3463 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003464
3465 // store new device and send to effects
3466 audio_devices_t type = AUDIO_DEVICE_NONE;
3467 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3468 type |= patch->sinks[i].ext.device.type;
3469 }
3470
3471#ifdef ADD_BATTERY_DATA
3472 // when changing the audio output device, call addBatteryData to notify
3473 // the change
3474 if (mOutDevice != type) {
3475 uint32_t params = 0;
3476 // check whether speaker is on
3477 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3478 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003479 }
3480
Eric Laurent054d9d32015-04-24 08:48:48 -07003481 audio_devices_t deviceWithoutSpeaker
3482 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3483 // check if any other device (except speaker) is on
3484 if (type & deviceWithoutSpeaker) {
3485 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3486 }
3487
3488 if (params != 0) {
3489 addBatteryData(params);
3490 }
3491 }
3492#endif
3493
3494 for (size_t i = 0; i < mEffectChains.size(); i++) {
3495 mEffectChains[i]->setDevice_l(type);
3496 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003497
3498 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3499 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3500 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003501 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003502 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003503
3504 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003505 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3506 status = hwDevice->createAudioPatch(patch->num_sources,
3507 patch->sources,
3508 patch->num_sinks,
3509 patch->sinks,
3510 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003511 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003512 char *address;
3513 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3514 //FIXME: we only support address on first sink with HAL version < 3.0
3515 address = audio_device_address_to_parameter(
3516 patch->sinks[0].ext.device.type,
3517 patch->sinks[0].ext.device.address);
3518 } else {
3519 address = (char *)calloc(1, 1);
3520 }
3521 AudioParameter param = AudioParameter(String8(address));
3522 free(address);
3523 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003524 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003525 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003526 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003527 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003528 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003529 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3530 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003531 return status;
3532}
3533
Eric Laurent054d9d32015-04-24 08:48:48 -07003534status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3535{
Andy Hungf60abce2016-08-26 11:37:54 -07003536 status_t status;
3537 if (property_get_bool("af.patch_park", false /* default_value */)) {
3538 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3539 // or if HAL does not properly lock against access.
3540 AutoPark<FastMixer> park(mFastMixer);
3541 status = PlaybackThread::releaseAudioPatch_l(handle);
3542 } else {
3543 status = PlaybackThread::releaseAudioPatch_l(handle);
3544 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003545 return status;
3546}
3547
Eric Laurent1c333e22014-05-20 10:48:17 -07003548status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3549{
3550 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003551
3552 mOutDevice = AUDIO_DEVICE_NONE;
3553
Eric Laurent1c333e22014-05-20 10:48:17 -07003554 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003555 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3556 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003557 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003558 AudioParameter param;
3559 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003560 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003561 }
3562 return status;
3563}
3564
Eric Laurent83b88082014-06-20 18:31:16 -07003565void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3566{
3567 Mutex::Autolock _l(mLock);
3568 mTracks.add(track);
3569}
3570
3571void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3572{
3573 Mutex::Autolock _l(mLock);
3574 destroyTrack_l(track);
3575}
3576
3577void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3578{
3579 ThreadBase::getAudioPortConfig(config);
3580 config->role = AUDIO_PORT_ROLE_SOURCE;
3581 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3582 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3583}
3584
Eric Laurent81784c32012-11-19 14:55:58 -08003585// ----------------------------------------------------------------------------
3586
3587AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003588 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3589 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003590 // mAudioMixer below
3591 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003592 mFastMixerFutex(0),
3593 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003594 // mOutputSink below
3595 // mPipeSink below
3596 // mNormalSink below
3597{
3598 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003599 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3600 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003601 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3602 mNormalFrameCount);
3603 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3604
Andy Hungfbfc3952015-01-15 13:33:51 -08003605 if (type == DUPLICATING) {
3606 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3607 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3608 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3609 return;
3610 }
Eric Laurent81784c32012-11-19 14:55:58 -08003611 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003612 mOutputSink = new AudioStreamOutSink(
3613 static_cast<StreamOutHalLocal*>(output->stream.get())->getStream());
Eric Laurent81784c32012-11-19 14:55:58 -08003614 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003615 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003616#if !LOG_NDEBUG
3617 ssize_t index =
3618#else
3619 (void)
3620#endif
3621 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003622 ALOG_ASSERT(index == 0);
3623
3624 // initialize fast mixer depending on configuration
3625 bool initFastMixer;
3626 switch (kUseFastMixer) {
3627 case FastMixer_Never:
3628 initFastMixer = false;
3629 break;
3630 case FastMixer_Always:
3631 initFastMixer = true;
3632 break;
3633 case FastMixer_Static:
3634 case FastMixer_Dynamic:
3635 initFastMixer = mFrameCount < mNormalFrameCount;
3636 break;
3637 }
3638 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003639 audio_format_t fastMixerFormat;
3640 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3641 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3642 } else {
3643 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3644 }
3645 if (mFormat != fastMixerFormat) {
3646 // change our Sink format to accept our intermediate precision
3647 mFormat = fastMixerFormat;
3648 free(mSinkBuffer);
3649 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3650 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3651 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3652 }
Eric Laurent81784c32012-11-19 14:55:58 -08003653
3654 // create a MonoPipe to connect our submix to FastMixer
3655 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003656#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003657 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003658#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003659 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003660 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003661 format.mFormat = fastMixerFormat;
3662 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3663
Eric Laurent81784c32012-11-19 14:55:58 -08003664 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3665 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3666 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3667 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3668 const NBAIO_Format offers[1] = {format};
3669 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003670#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003671 ssize_t index =
3672#else
3673 (void)
3674#endif
3675 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003676 ALOG_ASSERT(index == 0);
3677 monoPipe->setAvgFrames((mScreenState & 1) ?
3678 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3679 mPipeSink = monoPipe;
3680
Glenn Kasten46909e72013-02-26 09:20:22 -08003681#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003682 if (mTeeSinkOutputEnabled) {
3683 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003684 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3685 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003686 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003687 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003688 ALOG_ASSERT(index == 0);
3689 mTeeSink = teeSink;
3690 PipeReader *teeSource = new PipeReader(*teeSink);
3691 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003692 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003693 ALOG_ASSERT(index == 0);
3694 mTeeSource = teeSource;
3695 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003696#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003697
3698 // create fast mixer and configure it initially with just one fast track for our submix
3699 mFastMixer = new FastMixer();
3700 FastMixerStateQueue *sq = mFastMixer->sq();
3701#ifdef STATE_QUEUE_DUMP
3702 sq->setObserverDump(&mStateQueueObserverDump);
3703 sq->setMutatorDump(&mStateQueueMutatorDump);
3704#endif
3705 FastMixerState *state = sq->begin();
3706 FastTrack *fastTrack = &state->mFastTracks[0];
3707 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3708 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3709 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003710 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3711 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003712 fastTrack->mGeneration++;
3713 state->mFastTracksGen++;
3714 state->mTrackMask = 1;
3715 // fast mixer will use the HAL output sink
3716 state->mOutputSink = mOutputSink.get();
3717 state->mOutputSinkGen++;
3718 state->mFrameCount = mFrameCount;
3719 state->mCommand = FastMixerState::COLD_IDLE;
3720 // already done in constructor initialization list
3721 //mFastMixerFutex = 0;
3722 state->mColdFutexAddr = &mFastMixerFutex;
3723 state->mColdGen++;
3724 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003725#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003726 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003727#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003728 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3729 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003730 sq->end();
3731 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3732
3733 // start the fast mixer
3734 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3735 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003736 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003737
3738#ifdef AUDIO_WATCHDOG
3739 // create and start the watchdog
3740 mAudioWatchdog = new AudioWatchdog();
3741 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3742 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3743 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003744 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003745#endif
3746
Eric Laurent81784c32012-11-19 14:55:58 -08003747 }
3748
3749 switch (kUseFastMixer) {
3750 case FastMixer_Never:
3751 case FastMixer_Dynamic:
3752 mNormalSink = mOutputSink;
3753 break;
3754 case FastMixer_Always:
3755 mNormalSink = mPipeSink;
3756 break;
3757 case FastMixer_Static:
3758 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3759 break;
3760 }
3761}
3762
3763AudioFlinger::MixerThread::~MixerThread()
3764{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003765 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003766 FastMixerStateQueue *sq = mFastMixer->sq();
3767 FastMixerState *state = sq->begin();
3768 if (state->mCommand == FastMixerState::COLD_IDLE) {
3769 int32_t old = android_atomic_inc(&mFastMixerFutex);
3770 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003771 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003772 }
3773 }
3774 state->mCommand = FastMixerState::EXIT;
3775 sq->end();
3776 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3777 mFastMixer->join();
3778 // Though the fast mixer thread has exited, it's state queue is still valid.
3779 // We'll use that extract the final state which contains one remaining fast track
3780 // corresponding to our sub-mix.
3781 state = sq->begin();
3782 ALOG_ASSERT(state->mTrackMask == 1);
3783 FastTrack *fastTrack = &state->mFastTracks[0];
3784 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3785 delete fastTrack->mBufferProvider;
3786 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003787 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003788#ifdef AUDIO_WATCHDOG
3789 if (mAudioWatchdog != 0) {
3790 mAudioWatchdog->requestExit();
3791 mAudioWatchdog->requestExitAndWait();
3792 mAudioWatchdog.clear();
3793 }
3794#endif
3795 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003796 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003797 delete mAudioMixer;
3798}
3799
3800
3801uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3802{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003803 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003804 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3805 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3806 }
3807 return latency;
3808}
3809
3810
3811void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3812{
3813 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3814}
3815
Eric Laurentbfb1b832013-01-07 09:53:42 -08003816ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003817{
3818 // FIXME we should only do one push per cycle; confirm this is true
3819 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003820 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003821 FastMixerStateQueue *sq = mFastMixer->sq();
3822 FastMixerState *state = sq->begin();
3823 if (state->mCommand != FastMixerState::MIX_WRITE &&
3824 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3825 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003826
3827 // FIXME workaround for first HAL write being CPU bound on some devices
3828 ATRACE_BEGIN("write");
3829 mOutput->write((char *)mSinkBuffer, 0);
3830 ATRACE_END();
3831
Eric Laurent81784c32012-11-19 14:55:58 -08003832 int32_t old = android_atomic_inc(&mFastMixerFutex);
3833 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003834 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003835 }
3836#ifdef AUDIO_WATCHDOG
3837 if (mAudioWatchdog != 0) {
3838 mAudioWatchdog->resume();
3839 }
3840#endif
3841 }
3842 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003843#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003844 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003845 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003846#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003847 sq->end();
3848 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3849 if (kUseFastMixer == FastMixer_Dynamic) {
3850 mNormalSink = mPipeSink;
3851 }
3852 } else {
3853 sq->end(false /*didModify*/);
3854 }
3855 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003856 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003857}
3858
3859void AudioFlinger::MixerThread::threadLoop_standby()
3860{
3861 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003862 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003863 FastMixerStateQueue *sq = mFastMixer->sq();
3864 FastMixerState *state = sq->begin();
3865 if (!(state->mCommand & FastMixerState::IDLE)) {
3866 state->mCommand = FastMixerState::COLD_IDLE;
3867 state->mColdFutexAddr = &mFastMixerFutex;
3868 state->mColdGen++;
3869 mFastMixerFutex = 0;
3870 sq->end();
3871 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3872 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3873 if (kUseFastMixer == FastMixer_Dynamic) {
3874 mNormalSink = mOutputSink;
3875 }
3876#ifdef AUDIO_WATCHDOG
3877 if (mAudioWatchdog != 0) {
3878 mAudioWatchdog->pause();
3879 }
3880#endif
3881 } else {
3882 sq->end(false /*didModify*/);
3883 }
3884 }
3885 PlaybackThread::threadLoop_standby();
3886}
3887
Eric Laurentbfb1b832013-01-07 09:53:42 -08003888bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3889{
3890 return false;
3891}
3892
3893bool AudioFlinger::PlaybackThread::shouldStandby_l()
3894{
3895 return !mStandby;
3896}
3897
3898bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3899{
3900 Mutex::Autolock _l(mLock);
3901 return waitingAsyncCallback_l();
3902}
3903
Eric Laurent81784c32012-11-19 14:55:58 -08003904// shared by MIXER and DIRECT, overridden by DUPLICATING
3905void AudioFlinger::PlaybackThread::threadLoop_standby()
3906{
3907 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003908 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003909 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003910 // discard any pending drain or write ack by incrementing sequence
3911 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3912 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003913 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003914 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3915 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003916 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003917 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003918}
3919
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003920void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3921{
3922 ALOGV("signal playback thread");
3923 broadcast_l();
3924}
3925
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003926void AudioFlinger::PlaybackThread::onAsyncError()
3927{
3928 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3929 invalidateTracks((audio_stream_type_t)i);
3930 }
3931}
3932
Eric Laurent81784c32012-11-19 14:55:58 -08003933void AudioFlinger::MixerThread::threadLoop_mix()
3934{
Eric Laurent81784c32012-11-19 14:55:58 -08003935 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003936 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003937 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003938 // increase sleep time progressively when application underrun condition clears.
3939 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3940 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3941 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003942 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003943 sleepTimeShift--;
3944 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003945 mSleepTimeUs = 0;
3946 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003947 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003948
Eric Laurent81784c32012-11-19 14:55:58 -08003949}
3950
3951void AudioFlinger::MixerThread::threadLoop_sleepTime()
3952{
3953 // If no tracks are ready, sleep once for the duration of an output
3954 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003955 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003956 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003957 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3958 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3959 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003960 }
3961 // reduce sleep time in case of consecutive application underruns to avoid
3962 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3963 // duration we would end up writing less data than needed by the audio HAL if
3964 // the condition persists.
3965 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3966 sleepTimeShift++;
3967 }
3968 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003969 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003970 }
3971 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003972 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3973 // before effects processing or output.
3974 if (mMixerBufferValid) {
3975 memset(mMixerBuffer, 0, mMixerBufferSize);
3976 } else {
3977 memset(mSinkBuffer, 0, mSinkBufferSize);
3978 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003979 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003980 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3981 "anticipated start");
3982 }
3983 // TODO add standby time extension fct of effect tail
3984}
3985
3986// prepareTracks_l() must be called with ThreadBase::mLock held
3987AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3988 Vector< sp<Track> > *tracksToRemove)
3989{
3990
3991 mixer_state mixerStatus = MIXER_IDLE;
3992 // find out which tracks need to be processed
3993 size_t count = mActiveTracks.size();
3994 size_t mixedTracks = 0;
3995 size_t tracksWithEffect = 0;
3996 // counts only _active_ fast tracks
3997 size_t fastTracks = 0;
3998 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3999
4000 float masterVolume = mMasterVolume;
4001 bool masterMute = mMasterMute;
4002
4003 if (masterMute) {
4004 masterVolume = 0;
4005 }
4006 // Delegate master volume control to effect in output mix effect chain if needed
4007 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4008 if (chain != 0) {
4009 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4010 chain->setVolume_l(&v, &v);
4011 masterVolume = (float)((v + (1 << 23)) >> 24);
4012 chain.clear();
4013 }
4014
4015 // prepare a new state to push
4016 FastMixerStateQueue *sq = NULL;
4017 FastMixerState *state = NULL;
4018 bool didModify = false;
4019 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004020 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004021 sq = mFastMixer->sq();
4022 state = sq->begin();
4023 }
4024
Andy Hung69aed5f2014-02-25 17:24:40 -08004025 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004026 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004027
Eric Laurent81784c32012-11-19 14:55:58 -08004028 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004029 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004030 if (t == 0) {
4031 continue;
4032 }
4033
4034 // this const just means the local variable doesn't change
4035 Track* const track = t.get();
4036
4037 // process fast tracks
4038 if (track->isFastTrack()) {
4039
4040 // It's theoretically possible (though unlikely) for a fast track to be created
4041 // and then removed within the same normal mix cycle. This is not a problem, as
4042 // the track never becomes active so it's fast mixer slot is never touched.
4043 // The converse, of removing an (active) track and then creating a new track
4044 // at the identical fast mixer slot within the same normal mix cycle,
4045 // is impossible because the slot isn't marked available until the end of each cycle.
4046 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004047 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004048 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4049 FastTrack *fastTrack = &state->mFastTracks[j];
4050
4051 // Determine whether the track is currently in underrun condition,
4052 // and whether it had a recent underrun.
4053 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4054 FastTrackUnderruns underruns = ftDump->mUnderruns;
4055 uint32_t recentFull = (underruns.mBitFields.mFull -
4056 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4057 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4058 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4059 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4060 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4061 uint32_t recentUnderruns = recentPartial + recentEmpty;
4062 track->mObservedUnderruns = underruns;
4063 // don't count underruns that occur while stopping or pausing
4064 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004065 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4066 recentUnderruns > 0) {
4067 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4068 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004069 } else {
4070 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004071 }
4072
4073 // This is similar to the state machine for normal tracks,
4074 // with a few modifications for fast tracks.
4075 bool isActive = true;
4076 switch (track->mState) {
4077 case TrackBase::STOPPING_1:
4078 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004079 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004080 track->mState = TrackBase::STOPPING_2;
4081 }
4082 break;
4083 case TrackBase::PAUSING:
4084 // ramp down is not yet implemented
4085 track->setPaused();
4086 break;
4087 case TrackBase::RESUMING:
4088 // ramp up is not yet implemented
4089 track->mState = TrackBase::ACTIVE;
4090 break;
4091 case TrackBase::ACTIVE:
4092 if (recentFull > 0 || recentPartial > 0) {
4093 // track has provided at least some frames recently: reset retry count
4094 track->mRetryCount = kMaxTrackRetries;
4095 }
4096 if (recentUnderruns == 0) {
4097 // no recent underruns: stay active
4098 break;
4099 }
4100 // there has recently been an underrun of some kind
4101 if (track->sharedBuffer() == 0) {
4102 // were any of the recent underruns "empty" (no frames available)?
4103 if (recentEmpty == 0) {
4104 // no, then ignore the partial underruns as they are allowed indefinitely
4105 break;
4106 }
4107 // there has recently been an "empty" underrun: decrement the retry counter
4108 if (--(track->mRetryCount) > 0) {
4109 break;
4110 }
4111 // indicate to client process that the track was disabled because of underrun;
4112 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004113 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004114 // remove from active list, but state remains ACTIVE [confusing but true]
4115 isActive = false;
4116 break;
4117 }
4118 // fall through
4119 case TrackBase::STOPPING_2:
4120 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004121 case TrackBase::STOPPED:
4122 case TrackBase::FLUSHED: // flush() while active
4123 // Check for presentation complete if track is inactive
4124 // We have consumed all the buffers of this track.
4125 // This would be incomplete if we auto-paused on underrun
4126 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004127 uint32_t latency = 0;
4128 status_t result = mOutput->stream->getLatency(&latency);
4129 ALOGE_IF(result != OK,
4130 "Error when retrieving output stream latency: %d", result);
4131 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004132 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004133 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4134 // track stays in active list until presentation is complete
4135 break;
4136 }
4137 }
4138 if (track->isStopping_2()) {
4139 track->mState = TrackBase::STOPPED;
4140 }
4141 if (track->isStopped()) {
4142 // Can't reset directly, as fast mixer is still polling this track
4143 // track->reset();
4144 // So instead mark this track as needing to be reset after push with ack
4145 resetMask |= 1 << i;
4146 }
4147 isActive = false;
4148 break;
4149 case TrackBase::IDLE:
4150 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004151 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004152 }
4153
4154 if (isActive) {
4155 // was it previously inactive?
4156 if (!(state->mTrackMask & (1 << j))) {
4157 ExtendedAudioBufferProvider *eabp = track;
4158 VolumeProvider *vp = track;
4159 fastTrack->mBufferProvider = eabp;
4160 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004161 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004162 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004163 fastTrack->mGeneration++;
4164 state->mTrackMask |= 1 << j;
4165 didModify = true;
4166 // no acknowledgement required for newly active tracks
4167 }
4168 // cache the combined master volume and stream type volume for fast mixer; this
4169 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004170 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004171 ++fastTracks;
4172 } else {
4173 // was it previously active?
4174 if (state->mTrackMask & (1 << j)) {
4175 fastTrack->mBufferProvider = NULL;
4176 fastTrack->mGeneration++;
4177 state->mTrackMask &= ~(1 << j);
4178 didModify = true;
4179 // If any fast tracks were removed, we must wait for acknowledgement
4180 // because we're about to decrement the last sp<> on those tracks.
4181 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4182 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004183 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4184 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4185 j, track->mState, state->mTrackMask, recentUnderruns,
4186 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004187 }
4188 tracksToRemove->add(track);
4189 // Avoids a misleading display in dumpsys
4190 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4191 }
4192 continue;
4193 }
4194
4195 { // local variable scope to avoid goto warning
4196
4197 audio_track_cblk_t* cblk = track->cblk();
4198
4199 // The first time a track is added we wait
4200 // for all its buffers to be filled before processing it
4201 int name = track->name();
4202 // make sure that we have enough frames to mix one full buffer.
4203 // enforce this condition only once to enable draining the buffer in case the client
4204 // app does not call stop() and relies on underrun to stop:
4205 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4206 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004207 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004208 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004209 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004210
4211 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004212 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004213 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4214 // add frames already consumed but not yet released by the resampler
4215 // because mAudioTrackServerProxy->framesReady() will include these frames
4216 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4217
Eric Laurent81784c32012-11-19 14:55:58 -08004218 uint32_t minFrames = 1;
4219 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4220 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004221 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004222 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004223
4224 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004225 if (ATRACE_ENABLED()) {
4226 // I wish we had formatted trace names
4227 char traceName[16];
4228 strcpy(traceName, "nRdy");
4229 int name = track->name();
4230 if (AudioMixer::TRACK0 <= name &&
4231 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4232 name -= AudioMixer::TRACK0;
4233 traceName[4] = (name / 10) + '0';
4234 traceName[5] = (name % 10) + '0';
4235 } else {
4236 traceName[4] = '?';
4237 traceName[5] = '?';
4238 }
4239 traceName[6] = '\0';
4240 ATRACE_INT(traceName, framesReady);
4241 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004242 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004243 !track->isPaused() && !track->isTerminated())
4244 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004245 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004246
4247 mixedTracks++;
4248
Andy Hung69aed5f2014-02-25 17:24:40 -08004249 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4250 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004251 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004252 if (track->mainBuffer() != mSinkBuffer &&
4253 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004254 if (mEffectBufferEnabled) {
4255 mEffectBufferValid = true; // Later can set directly.
4256 }
Eric Laurent81784c32012-11-19 14:55:58 -08004257 chain = getEffectChain_l(track->sessionId());
4258 // Delegate volume control to effect in track effect chain if needed
4259 if (chain != 0) {
4260 tracksWithEffect++;
4261 } else {
4262 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4263 "session %d",
4264 name, track->sessionId());
4265 }
4266 }
4267
4268
4269 int param = AudioMixer::VOLUME;
4270 if (track->mFillingUpStatus == Track::FS_FILLED) {
4271 // no ramp for the first volume setting
4272 track->mFillingUpStatus = Track::FS_ACTIVE;
4273 if (track->mState == TrackBase::RESUMING) {
4274 track->mState = TrackBase::ACTIVE;
4275 param = AudioMixer::RAMP_VOLUME;
4276 }
4277 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004278 // FIXME should not make a decision based on mServer
4279 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004280 // If the track is stopped before the first frame was mixed,
4281 // do not apply ramp
4282 param = AudioMixer::RAMP_VOLUME;
4283 }
4284
4285 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004286 uint32_t vl, vr; // in U8.24 integer format
4287 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004288 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004289 vl = vr = 0;
4290 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004291 if (track->isPausing()) {
4292 track->setPaused();
4293 }
4294 } else {
4295
4296 // read original volumes with volume control
4297 float typeVolume = mStreamTypes[track->streamType()].volume;
4298 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004299 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004300 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004301 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4302 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004303 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004304 if (vlf > GAIN_FLOAT_UNITY) {
4305 ALOGV("Track left volume out of range: %.3g", vlf);
4306 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004307 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004308 if (vrf > GAIN_FLOAT_UNITY) {
4309 ALOGV("Track right volume out of range: %.3g", vrf);
4310 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004311 }
4312 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004313 vlf *= v;
4314 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004315 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004316 // then derive vl and vr as U8.24 versions for the effect chain
4317 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4318 vl = (uint32_t) (scaleto8_24 * vlf);
4319 vr = (uint32_t) (scaleto8_24 * vrf);
4320 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004321 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004322 // send level comes from shared memory and so may be corrupt
4323 if (sendLevel > MAX_GAIN_INT) {
4324 ALOGV("Track send level out of range: %04X", sendLevel);
4325 sendLevel = MAX_GAIN_INT;
4326 }
Andy Hung6be49402014-05-30 10:42:03 -07004327 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4328 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004329 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004330
Eric Laurent81784c32012-11-19 14:55:58 -08004331 // Delegate volume control to effect in track effect chain if needed
4332 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4333 // Do not ramp volume if volume is controlled by effect
4334 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004335 // Update remaining floating point volume levels
4336 vlf = (float)vl / (1 << 24);
4337 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004338 track->mHasVolumeController = true;
4339 } else {
4340 // force no volume ramp when volume controller was just disabled or removed
4341 // from effect chain to avoid volume spike
4342 if (track->mHasVolumeController) {
4343 param = AudioMixer::VOLUME;
4344 }
4345 track->mHasVolumeController = false;
4346 }
4347
Eric Laurent81784c32012-11-19 14:55:58 -08004348 // XXX: these things DON'T need to be done each time
4349 mAudioMixer->setBufferProvider(name, track);
4350 mAudioMixer->enable(name);
4351
Andy Hung6be49402014-05-30 10:42:03 -07004352 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4353 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4354 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004355 mAudioMixer->setParameter(
4356 name,
4357 AudioMixer::TRACK,
4358 AudioMixer::FORMAT, (void *)track->format());
4359 mAudioMixer->setParameter(
4360 name,
4361 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004362 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004363 mAudioMixer->setParameter(
4364 name,
4365 AudioMixer::TRACK,
4366 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004367 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004368 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004369 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004370 if (reqSampleRate == 0) {
4371 reqSampleRate = mSampleRate;
4372 } else if (reqSampleRate > maxSampleRate) {
4373 reqSampleRate = maxSampleRate;
4374 }
Eric Laurent81784c32012-11-19 14:55:58 -08004375 mAudioMixer->setParameter(
4376 name,
4377 AudioMixer::RESAMPLE,
4378 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004379 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004380
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004381 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004382 mAudioMixer->setParameter(
4383 name,
4384 AudioMixer::TIMESTRETCH,
4385 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004386 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004387
Andy Hung69aed5f2014-02-25 17:24:40 -08004388 /*
4389 * Select the appropriate output buffer for the track.
4390 *
Andy Hung98ef9782014-03-04 14:46:50 -08004391 * Tracks with effects go into their own effects chain buffer
4392 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004393 *
4394 * Other tracks can use mMixerBuffer for higher precision
4395 * channel accumulation. If this buffer is enabled
4396 * (mMixerBufferEnabled true), then selected tracks will accumulate
4397 * into it.
4398 *
4399 */
4400 if (mMixerBufferEnabled
4401 && (track->mainBuffer() == mSinkBuffer
4402 || track->mainBuffer() == mMixerBuffer)) {
4403 mAudioMixer->setParameter(
4404 name,
4405 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004406 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004407 mAudioMixer->setParameter(
4408 name,
4409 AudioMixer::TRACK,
4410 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4411 // TODO: override track->mainBuffer()?
4412 mMixerBufferValid = true;
4413 } else {
4414 mAudioMixer->setParameter(
4415 name,
4416 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004417 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004418 mAudioMixer->setParameter(
4419 name,
4420 AudioMixer::TRACK,
4421 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4422 }
Eric Laurent81784c32012-11-19 14:55:58 -08004423 mAudioMixer->setParameter(
4424 name,
4425 AudioMixer::TRACK,
4426 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4427
4428 // reset retry count
4429 track->mRetryCount = kMaxTrackRetries;
4430
4431 // If one track is ready, set the mixer ready if:
4432 // - the mixer was not ready during previous round OR
4433 // - no other track is not ready
4434 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4435 mixerStatus != MIXER_TRACKS_ENABLED) {
4436 mixerStatus = MIXER_TRACKS_READY;
4437 }
4438 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004439 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004440 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4441 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004442 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004443 } else {
4444 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004445 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004446
Eric Laurent81784c32012-11-19 14:55:58 -08004447 // clear effect chain input buffer if an active track underruns to avoid sending
4448 // previous audio buffer again to effects
4449 chain = getEffectChain_l(track->sessionId());
4450 if (chain != 0) {
4451 chain->clearInputBuffer();
4452 }
4453
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004454 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004455 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4456 track->isStopped() || track->isPaused()) {
4457 // We have consumed all the buffers of this track.
4458 // Remove it from the list of active tracks.
4459 // TODO: use actual buffer filling status instead of latency when available from
4460 // audio HAL
4461 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004462 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004463 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4464 if (track->isStopped()) {
4465 track->reset();
4466 }
4467 tracksToRemove->add(track);
4468 }
4469 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004470 // No buffers for this track. Give it a few chances to
4471 // fill a buffer, then remove it from active list.
4472 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004473 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004474 tracksToRemove->add(track);
4475 // indicate to client process that the track was disabled because of underrun;
4476 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004477 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004478 // If one track is not ready, mark the mixer also not ready if:
4479 // - the mixer was ready during previous round OR
4480 // - no other track is ready
4481 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4482 mixerStatus != MIXER_TRACKS_READY) {
4483 mixerStatus = MIXER_TRACKS_ENABLED;
4484 }
4485 }
4486 mAudioMixer->disable(name);
4487 }
4488
4489 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004490
4491 }
4492
4493 // Push the new FastMixer state if necessary
4494 bool pauseAudioWatchdog = false;
4495 if (didModify) {
4496 state->mFastTracksGen++;
4497 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4498 if (kUseFastMixer == FastMixer_Dynamic &&
4499 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4500 state->mCommand = FastMixerState::COLD_IDLE;
4501 state->mColdFutexAddr = &mFastMixerFutex;
4502 state->mColdGen++;
4503 mFastMixerFutex = 0;
4504 if (kUseFastMixer == FastMixer_Dynamic) {
4505 mNormalSink = mOutputSink;
4506 }
4507 // If we go into cold idle, need to wait for acknowledgement
4508 // so that fast mixer stops doing I/O.
4509 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4510 pauseAudioWatchdog = true;
4511 }
Eric Laurent81784c32012-11-19 14:55:58 -08004512 }
4513 if (sq != NULL) {
4514 sq->end(didModify);
4515 sq->push(block);
4516 }
4517#ifdef AUDIO_WATCHDOG
4518 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4519 mAudioWatchdog->pause();
4520 }
4521#endif
4522
4523 // Now perform the deferred reset on fast tracks that have stopped
4524 while (resetMask != 0) {
4525 size_t i = __builtin_ctz(resetMask);
4526 ALOG_ASSERT(i < count);
4527 resetMask &= ~(1 << i);
4528 sp<Track> t = mActiveTracks[i].promote();
4529 if (t == 0) {
4530 continue;
4531 }
4532 Track* track = t.get();
4533 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
4579// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004580int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004581 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004582{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004583 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004584}
4585
4586// deleteTrackName_l() must be called with ThreadBase::mLock held
4587void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4588{
4589 ALOGV("remove track (%d) and delete from mixer", name);
4590 mAudioMixer->deleteTrackName(name);
4591}
4592
Eric Laurent10351942014-05-08 18:49:52 -07004593// checkForNewParameter_l() must be called with ThreadBase::mLock held
4594bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4595 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004596{
Eric Laurent81784c32012-11-19 14:55:58 -08004597 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004598 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004599
Eric Laurent10351942014-05-08 18:49:52 -07004600 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004601
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004602 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004603
Eric Laurent10351942014-05-08 18:49:52 -07004604 AudioParameter param = AudioParameter(keyValuePair);
4605 int value;
4606 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4607 reconfig = true;
4608 }
4609 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004610 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004611 status = BAD_VALUE;
4612 } else {
4613 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004614 reconfig = true;
4615 }
Eric Laurent10351942014-05-08 18:49:52 -07004616 }
4617 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004618 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004619 status = BAD_VALUE;
4620 } else {
4621 // no need to save value, since it's constant
4622 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004623 }
Eric Laurent10351942014-05-08 18:49:52 -07004624 }
4625 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4626 // do not accept frame count changes if tracks are open as the track buffer
4627 // size depends on frame count and correct behavior would not be guaranteed
4628 // if frame count is changed after track creation
4629 if (!mTracks.isEmpty()) {
4630 status = INVALID_OPERATION;
4631 } else {
4632 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004633 }
Eric Laurent10351942014-05-08 18:49:52 -07004634 }
4635 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004636#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004637 // when changing the audio output device, call addBatteryData to notify
4638 // the change
4639 if (mOutDevice != value) {
4640 uint32_t params = 0;
4641 // check whether speaker is on
4642 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4643 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004644 }
Eric Laurent10351942014-05-08 18:49:52 -07004645
4646 audio_devices_t deviceWithoutSpeaker
4647 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4648 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004649 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004650 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4651 }
4652
4653 if (params != 0) {
4654 addBatteryData(params);
4655 }
4656 }
Eric Laurent81784c32012-11-19 14:55:58 -08004657#endif
4658
Eric Laurent10351942014-05-08 18:49:52 -07004659 // forward device change to effects that have requested to be
4660 // aware of attached audio device.
4661 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004662 a2dpDeviceChanged =
4663 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004664 mOutDevice = value;
4665 for (size_t i = 0; i < mEffectChains.size(); i++) {
4666 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004667 }
4668 }
Eric Laurent10351942014-05-08 18:49:52 -07004669 }
Eric Laurent81784c32012-11-19 14:55:58 -08004670
Eric Laurent10351942014-05-08 18:49:52 -07004671 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004672 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004673 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004674 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004675 mStandby = true;
4676 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004677 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004678 }
Eric Laurent10351942014-05-08 18:49:52 -07004679 if (status == NO_ERROR && reconfig) {
4680 readOutputParameters_l();
4681 delete mAudioMixer;
4682 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4683 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004684 int name = getTrackName_l(mTracks[i]->mChannelMask,
4685 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004686 if (name < 0) {
4687 break;
4688 }
4689 mTracks[i]->mName = name;
4690 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004691 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004692 }
Eric Laurent81784c32012-11-19 14:55:58 -08004693 }
4694
Eric Laurent42537be2016-01-08 17:16:42 -08004695 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004696}
4697
4698
4699void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4700{
Eric Laurent81784c32012-11-19 14:55:58 -08004701 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004702 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004703 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004704 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004705
4706 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004707 // while we are dumping it. It may be inconsistent, but it won't mutate!
4708 // This is a large object so we place it on the heap.
4709 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4710 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4711 copy->dump(fd);
4712 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004713
4714#ifdef STATE_QUEUE_DUMP
4715 // Similar for state queue
4716 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4717 observerCopy.dump(fd);
4718 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4719 mutatorCopy.dump(fd);
4720#endif
4721
Glenn Kasten46909e72013-02-26 09:20:22 -08004722#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004723 // Write the tee output to a .wav file
4724 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004725#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004726
4727#ifdef AUDIO_WATCHDOG
4728 if (mAudioWatchdog != 0) {
4729 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4730 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4731 wdCopy.dump(fd);
4732 }
4733#endif
4734}
4735
4736uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4737{
4738 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4739}
4740
4741uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4742{
4743 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4744}
4745
4746void AudioFlinger::MixerThread::cacheParameters_l()
4747{
4748 PlaybackThread::cacheParameters_l();
4749
4750 // FIXME: Relaxed timing because of a certain device that can't meet latency
4751 // Should be reduced to 2x after the vendor fixes the driver issue
4752 // increase threshold again due to low power audio mode. The way this warning
4753 // threshold is calculated and its usefulness should be reconsidered anyway.
4754 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4755}
4756
4757// ----------------------------------------------------------------------------
4758
4759AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004760 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4761 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004762 // mLeftVolFloat, mRightVolFloat
4763{
4764}
4765
Eric Laurentbfb1b832013-01-07 09:53:42 -08004766AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4767 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004768 ThreadBase::type_t type, bool systemReady)
4769 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004770 // mLeftVolFloat, mRightVolFloat
4771{
4772}
4773
Eric Laurent81784c32012-11-19 14:55:58 -08004774AudioFlinger::DirectOutputThread::~DirectOutputThread()
4775{
4776}
4777
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4779{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004780 float left, right;
4781
4782 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4783 left = right = 0;
4784 } else {
4785 float typeVolume = mStreamTypes[track->streamType()].volume;
4786 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004787 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004788 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4789 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4790 if (left > GAIN_FLOAT_UNITY) {
4791 left = GAIN_FLOAT_UNITY;
4792 }
4793 left *= v;
4794 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4795 if (right > GAIN_FLOAT_UNITY) {
4796 right = GAIN_FLOAT_UNITY;
4797 }
4798 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004799 }
4800
4801 if (lastTrack) {
4802 if (left != mLeftVolFloat || right != mRightVolFloat) {
4803 mLeftVolFloat = left;
4804 mRightVolFloat = right;
4805
4806 // Convert volumes from float to 8.24
4807 uint32_t vl = (uint32_t)(left * (1 << 24));
4808 uint32_t vr = (uint32_t)(right * (1 << 24));
4809
4810 // Delegate volume control to effect in track effect chain if needed
4811 // only one effect chain can be present on DirectOutputThread, so if
4812 // there is one, the track is connected to it
4813 if (!mEffectChains.isEmpty()) {
4814 mEffectChains[0]->setVolume_l(&vl, &vr);
4815 left = (float)vl / (1 << 24);
4816 right = (float)vr / (1 << 24);
4817 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004818 status_t result = mOutput->stream->setVolume(left, right);
4819 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004820 }
4821 }
4822}
4823
Phil Burk43b4dcc2015-06-09 16:53:44 -07004824void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4825{
4826 sp<Track> previousTrack = mPreviousTrack.promote();
4827 sp<Track> latestTrack = mLatestActiveTrack.promote();
4828
Eric Laurent0f0631e2015-07-06 18:01:25 -07004829 if (previousTrack != 0 && latestTrack != 0) {
4830 if (mType == DIRECT) {
4831 if (previousTrack.get() != latestTrack.get()) {
4832 mFlushPending = true;
4833 }
4834 } else /* mType == OFFLOAD */ {
4835 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4836 mFlushPending = true;
4837 }
4838 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004839 }
4840 PlaybackThread::onAddNewTrack_l();
4841}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004842
Eric Laurent81784c32012-11-19 14:55:58 -08004843AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4844 Vector< sp<Track> > *tracksToRemove
4845)
4846{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004847 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004848 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004849 bool doHwPause = false;
4850 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004851
4852 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004853 for (size_t i = 0; i < count; i++) {
4854 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004855 // The track died recently
4856 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004857 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004858 }
4859
Phil Burk43b4dcc2015-06-09 16:53:44 -07004860 if (t->isInvalid()) {
4861 ALOGW("An invalidated track shouldn't be in active list");
4862 tracksToRemove->add(t);
4863 continue;
4864 }
4865
Eric Laurent81784c32012-11-19 14:55:58 -08004866 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004867#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004868 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004869#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004870 // Only consider last track started for volume and mixer state control.
4871 // In theory an older track could underrun and restart after the new one starts
4872 // but as we only care about the transition phase between two tracks on a
4873 // direct output, it is not a problem to ignore the underrun case.
4874 sp<Track> l = mLatestActiveTrack.promote();
4875 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004876
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004877 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004878 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004879 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004880 doHwPause = true;
4881 mHwPaused = true;
4882 }
4883 tracksToRemove->add(track);
4884 } else if (track->isFlushPending()) {
4885 track->flushAck();
4886 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004887 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004888 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004889 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004890 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004891 if (last) {
4892 mLeftVolFloat = mRightVolFloat = -1.0;
4893 if (mHwPaused) {
4894 doHwResume = true;
4895 mHwPaused = false;
4896 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004897 }
4898 }
4899
Eric Laurent81784c32012-11-19 14:55:58 -08004900 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004901 // for all its buffers to be filled before processing it.
4902 // Allow draining the buffer in case the client
4903 // app does not call stop() and relies on underrun to stop:
4904 // hence the test on (track->mRetryCount > 1).
4905 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004906 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004907 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004908 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004909 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004910 minFrames = mNormalFrameCount;
4911 } else {
4912 minFrames = 1;
4913 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004914
Eric Laurentab5cdba2014-06-09 17:22:27 -07004915 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4916 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004917 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004918 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004919
4920 if (track->mFillingUpStatus == Track::FS_FILLED) {
4921 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004922 if (last) {
4923 // make sure processVolume_l() will apply new volume even if 0
4924 mLeftVolFloat = mRightVolFloat = -1.0;
4925 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004926 if (!mHwSupportsPause) {
4927 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004928 }
4929 }
4930
4931 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004932 processVolume_l(track, last);
4933 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004934 sp<Track> previousTrack = mPreviousTrack.promote();
4935 if (previousTrack != 0) {
4936 if (track != previousTrack.get()) {
4937 // Flush any data still being written from last track
4938 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004939 // Invalidate previous track to force a seek when resuming.
4940 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004941 }
4942 }
4943 mPreviousTrack = track;
4944
Eric Laurentd595b7c2013-04-03 17:27:56 -07004945 // reset retry count
4946 track->mRetryCount = kMaxTrackRetriesDirect;
4947 mActiveTrack = t;
4948 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004949 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004950 doHwResume = true;
4951 mHwPaused = false;
4952 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004953 }
Eric Laurent81784c32012-11-19 14:55:58 -08004954 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004955 // clear effect chain input buffer if the last active track started underruns
4956 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004957 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004958 mEffectChains[0]->clearInputBuffer();
4959 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004960 if (track->isStopping_1()) {
4961 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004962 if (last && mHwPaused) {
4963 doHwResume = true;
4964 mHwPaused = false;
4965 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004966 }
4967 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4968 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004969 // We have consumed all the buffers of this track.
4970 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004971 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004972 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004973 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4974 } else {
4975 audioHALFrames = 0;
4976 }
4977
Andy Hung818e7a32016-02-16 18:08:07 -08004978 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004979 if (mStandby || !last ||
4980 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004981 if (track->isStopping_2()) {
4982 track->mState = TrackBase::STOPPED;
4983 }
Eric Laurent81784c32012-11-19 14:55:58 -08004984 if (track->isStopped()) {
4985 track->reset();
4986 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004987 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004988 }
4989 } else {
4990 // No buffers for this track. Give it a few chances to
4991 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004992 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004993 if (--(track->mRetryCount) <= 0) {
4994 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004995 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004996 // indicate to client process that the track was disabled because of underrun;
4997 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004998 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004999 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005000 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5001 "minFrames = %u, mFormat = %#x",
5002 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005003 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005004 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005005 doHwPause = true;
5006 mHwPaused = true;
5007 }
Eric Laurent81784c32012-11-19 14:55:58 -08005008 }
5009 }
5010 }
5011 }
5012
Eric Laurentd1f69b02014-12-15 14:33:13 -08005013 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005014 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005015 for (size_t i = 0; i < mTracks.size(); i++) {
5016 if (mTracks[i]->isFlushPending()) {
5017 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005018 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005019 }
5020 }
5021 }
5022
5023 // make sure the pause/flush/resume sequence is executed in the right order.
5024 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5025 // before flush and then resume HW. This can happen in case of pause/flush/resume
5026 // if resume is received before pause is executed.
5027 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005028 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005029 status_t result = mOutput->stream->pause();
5030 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005031 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005032 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005033 flushHw_l();
5034 }
5035 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005036 status_t result = mOutput->stream->resume();
5037 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005038 }
Eric Laurent81784c32012-11-19 14:55:58 -08005039 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005040 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005041
5042 return mixerStatus;
5043}
5044
5045void AudioFlinger::DirectOutputThread::threadLoop_mix()
5046{
Eric Laurent81784c32012-11-19 14:55:58 -08005047 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005048 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005049 // output audio to hardware
5050 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005051 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005052 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005053 status_t status = mActiveTrack->getNextBuffer(&buffer);
5054 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005055 // no need to pad with 0 for compressed audio
5056 if (audio_has_proportional_frames(mFormat)) {
5057 memset(curBuf, 0, frameCount * mFrameSize);
5058 }
Eric Laurent81784c32012-11-19 14:55:58 -08005059 break;
5060 }
5061 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5062 frameCount -= buffer.frameCount;
5063 curBuf += buffer.frameCount * mFrameSize;
5064 mActiveTrack->releaseBuffer(&buffer);
5065 }
Andy Hung2098f272014-02-27 14:00:06 -08005066 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005067 mSleepTimeUs = 0;
5068 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005069 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005070}
5071
5072void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5073{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005074 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005075 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005076 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005077 return;
5078 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005079 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005080 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005081 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005082 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005083 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005084 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005085 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005086 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005087 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005088 }
5089}
5090
Eric Laurentd1f69b02014-12-15 14:33:13 -08005091void AudioFlinger::DirectOutputThread::threadLoop_exit()
5092{
5093 {
5094 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005095 for (size_t i = 0; i < mTracks.size(); i++) {
5096 if (mTracks[i]->isFlushPending()) {
5097 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005098 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005099 }
5100 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005101 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005102 flushHw_l();
5103 }
5104 }
5105 PlaybackThread::threadLoop_exit();
5106}
5107
5108// must be called with thread mutex locked
5109bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5110{
5111 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005112 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005113
vivek mehta9cd7ad12016-03-17 00:18:29 -07005114 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5115 return !mStandby;
5116 }
5117
Eric Laurentd1f69b02014-12-15 14:33:13 -08005118 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5119 // after a timeout and we will enter standby then.
5120 if (mTracks.size() > 0) {
5121 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005122 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5123 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005124 }
5125
Eric Laurent5cff4032015-05-26 13:49:58 -07005126 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005127}
5128
Eric Laurent81784c32012-11-19 14:55:58 -08005129// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005130int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08005131 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005132{
5133 return 0;
5134}
5135
5136// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005137void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005138{
5139}
5140
Eric Laurent10351942014-05-08 18:49:52 -07005141// checkForNewParameter_l() must be called with ThreadBase::mLock held
5142bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5143 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005144{
5145 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005146 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005147
Eric Laurent10351942014-05-08 18:49:52 -07005148 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005149
Eric Laurent10351942014-05-08 18:49:52 -07005150 AudioParameter param = AudioParameter(keyValuePair);
5151 int value;
5152 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5153 // forward device change to effects that have requested to be
5154 // aware of attached audio device.
5155 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005156 a2dpDeviceChanged =
5157 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005158 mOutDevice = value;
5159 for (size_t i = 0; i < mEffectChains.size(); i++) {
5160 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005161 }
5162 }
Eric Laurent81784c32012-11-19 14:55:58 -08005163 }
Eric Laurent10351942014-05-08 18:49:52 -07005164 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5165 // do not accept frame count changes if tracks are open as the track buffer
5166 // size depends on frame count and correct behavior would not be garantied
5167 // if frame count is changed after track creation
5168 if (!mTracks.isEmpty()) {
5169 status = INVALID_OPERATION;
5170 } else {
5171 reconfig = true;
5172 }
5173 }
5174 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005175 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005176 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005177 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005178 mStandby = true;
5179 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005180 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005181 }
5182 if (status == NO_ERROR && reconfig) {
5183 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005184 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005185 }
5186 }
5187
Eric Laurent42537be2016-01-08 17:16:42 -08005188 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005189}
5190
5191uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5192{
5193 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005194 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005195 time = PlaybackThread::activeSleepTimeUs();
5196 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005197 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005198 }
5199 return time;
5200}
5201
5202uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5203{
5204 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005205 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005206 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5207 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005208 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005209 }
5210 return time;
5211}
5212
5213uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5214{
5215 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005216 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005217 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5218 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005219 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005220 }
5221 return time;
5222}
5223
5224void AudioFlinger::DirectOutputThread::cacheParameters_l()
5225{
5226 PlaybackThread::cacheParameters_l();
5227
5228 // use shorter standby delay as on normal output to release
5229 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005230 // no delay on outputs with HW A/V sync
5231 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005232 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005233 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005234 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005235 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005236 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005237 }
Eric Laurent81784c32012-11-19 14:55:58 -08005238}
5239
Eric Laurente659ef42014-09-29 13:06:46 -07005240void AudioFlinger::DirectOutputThread::flushHw_l()
5241{
Phil Burk062e67a2015-02-11 13:40:50 -08005242 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005243 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005244 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005245}
5246
Eric Laurent81784c32012-11-19 14:55:58 -08005247// ----------------------------------------------------------------------------
5248
Eric Laurentbfb1b832013-01-07 09:53:42 -08005249AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005250 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005251 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005252 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005253 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005254 mDrainSequence(0),
5255 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005256{
5257}
5258
5259AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5260{
5261}
5262
5263void AudioFlinger::AsyncCallbackThread::onFirstRef()
5264{
5265 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5266}
5267
5268bool AudioFlinger::AsyncCallbackThread::threadLoop()
5269{
5270 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005271 uint32_t writeAckSequence;
5272 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005273 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005274
5275 {
5276 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005277 while (!((mWriteAckSequence & 1) ||
5278 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005279 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005280 exitPending())) {
5281 mWaitWorkCV.wait(mLock);
5282 }
5283
Eric Laurentbfb1b832013-01-07 09:53:42 -08005284 if (exitPending()) {
5285 break;
5286 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005287 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5288 mWriteAckSequence, mDrainSequence);
5289 writeAckSequence = mWriteAckSequence;
5290 mWriteAckSequence &= ~1;
5291 drainSequence = mDrainSequence;
5292 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005293 asyncError = mAsyncError;
5294 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005295 }
5296 {
Eric Laurent4de95592013-09-26 15:28:21 -07005297 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5298 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005299 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005300 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005301 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005302 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005303 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005305 if (asyncError) {
5306 playbackThread->onAsyncError();
5307 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308 }
5309 }
5310 }
5311 return false;
5312}
5313
5314void AudioFlinger::AsyncCallbackThread::exit()
5315{
5316 ALOGV("AsyncCallbackThread::exit");
5317 Mutex::Autolock _l(mLock);
5318 requestExit();
5319 mWaitWorkCV.broadcast();
5320}
5321
Eric Laurent3b4529e2013-09-05 18:09:19 -07005322void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005323{
5324 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005325 // bit 0 is cleared
5326 mWriteAckSequence = sequence << 1;
5327}
5328
5329void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5330{
5331 Mutex::Autolock _l(mLock);
5332 // ignore unexpected callbacks
5333 if (mWriteAckSequence & 2) {
5334 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005335 mWaitWorkCV.signal();
5336 }
5337}
5338
Eric Laurent3b4529e2013-09-05 18:09:19 -07005339void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005340{
5341 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005342 // bit 0 is cleared
5343 mDrainSequence = sequence << 1;
5344}
5345
5346void AudioFlinger::AsyncCallbackThread::resetDraining()
5347{
5348 Mutex::Autolock _l(mLock);
5349 // ignore unexpected callbacks
5350 if (mDrainSequence & 2) {
5351 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005352 mWaitWorkCV.signal();
5353 }
5354}
5355
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005356void AudioFlinger::AsyncCallbackThread::setAsyncError()
5357{
5358 Mutex::Autolock _l(mLock);
5359 mAsyncError = true;
5360 mWaitWorkCV.signal();
5361}
5362
Eric Laurentbfb1b832013-01-07 09:53:42 -08005363
5364// ----------------------------------------------------------------------------
5365AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005366 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5367 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005368 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5369 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005370{
Eric Laurentfd477972013-10-25 18:10:40 -07005371 //FIXME: mStandby should be set to true by ThreadBase constructor
5372 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005373 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005374}
5375
Eric Laurentbfb1b832013-01-07 09:53:42 -08005376void AudioFlinger::OffloadThread::threadLoop_exit()
5377{
5378 if (mFlushPending || mHwPaused) {
5379 // If a flush is pending or track was paused, just discard buffered data
5380 flushHw_l();
5381 } else {
5382 mMixerStatus = MIXER_DRAIN_ALL;
5383 threadLoop_drain();
5384 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005385 if (mUseAsyncWrite) {
5386 ALOG_ASSERT(mCallbackThread != 0);
5387 mCallbackThread->exit();
5388 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005389 PlaybackThread::threadLoop_exit();
5390}
5391
5392AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5393 Vector< sp<Track> > *tracksToRemove
5394)
5395{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005396 size_t count = mActiveTracks.size();
5397
5398 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005399 bool doHwPause = false;
5400 bool doHwResume = false;
5401
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005402 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005403
Eric Laurentbfb1b832013-01-07 09:53:42 -08005404 // find out which tracks need to be processed
5405 for (size_t i = 0; i < count; i++) {
5406 sp<Track> t = mActiveTracks[i].promote();
5407 // The track died recently
5408 if (t == 0) {
5409 continue;
5410 }
5411 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005412#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005413 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005414#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005415 // Only consider last track started for volume and mixer state control.
5416 // In theory an older track could underrun and restart after the new one starts
5417 // but as we only care about the transition phase between two tracks on a
5418 // direct output, it is not a problem to ignore the underrun case.
5419 sp<Track> l = mLatestActiveTrack.promote();
5420 bool last = l.get() == track;
5421
Haynes Mathew George7844f672014-01-15 12:32:55 -08005422 if (track->isInvalid()) {
5423 ALOGW("An invalidated track shouldn't be in active list");
5424 tracksToRemove->add(track);
5425 continue;
5426 }
5427
5428 if (track->mState == TrackBase::IDLE) {
5429 ALOGW("An idle track shouldn't be in active list");
5430 continue;
5431 }
5432
Eric Laurentbfb1b832013-01-07 09:53:42 -08005433 if (track->isPausing()) {
5434 track->setPaused();
5435 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005436 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005437 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005438 mHwPaused = true;
5439 }
5440 // If we were part way through writing the mixbuffer to
5441 // the HAL we must save this until we resume
5442 // BUG - this will be wrong if a different track is made active,
5443 // in that case we want to discard the pending data in the
5444 // mixbuffer and tell the client to present it again when the
5445 // track is resumed
5446 mPausedWriteLength = mCurrentWriteLength;
5447 mPausedBytesRemaining = mBytesRemaining;
5448 mBytesRemaining = 0; // stop writing
5449 }
5450 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005451 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005452 if (track->isStopping_1()) {
5453 track->mRetryCount = kMaxTrackStopRetriesOffload;
5454 } else {
5455 track->mRetryCount = kMaxTrackRetriesOffload;
5456 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005457 track->flushAck();
5458 if (last) {
5459 mFlushPending = true;
5460 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005461 } else if (track->isResumePending()){
5462 track->resumeAck();
5463 if (last) {
5464 if (mPausedBytesRemaining) {
5465 // Need to continue write that was interrupted
5466 mCurrentWriteLength = mPausedWriteLength;
5467 mBytesRemaining = mPausedBytesRemaining;
5468 mPausedBytesRemaining = 0;
5469 }
5470 if (mHwPaused) {
5471 doHwResume = true;
5472 mHwPaused = false;
5473 // threadLoop_mix() will handle the case that we need to
5474 // resume an interrupted write
5475 }
5476 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005477 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005478
Eric Laurent3df841a2016-07-15 15:15:40 -07005479 mLeftVolFloat = mRightVolFloat = -1.0;
5480
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005481 // Do not handle new data in this iteration even if track->framesReady()
5482 mixerStatus = MIXER_TRACKS_ENABLED;
5483 }
5484 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005485 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005486 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005487 if (track->mFillingUpStatus == Track::FS_FILLED) {
5488 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005489 if (last) {
5490 // make sure processVolume_l() will apply new volume even if 0
5491 mLeftVolFloat = mRightVolFloat = -1.0;
5492 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005493 }
5494
5495 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005496 sp<Track> previousTrack = mPreviousTrack.promote();
5497 if (previousTrack != 0) {
5498 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005499 // Flush any data still being written from last track
5500 mBytesRemaining = 0;
5501 if (mPausedBytesRemaining) {
5502 // Last track was paused so we also need to flush saved
5503 // mixbuffer state and invalidate track so that it will
5504 // re-submit that unwritten data when it is next resumed
5505 mPausedBytesRemaining = 0;
5506 // Invalidate is a bit drastic - would be more efficient
5507 // to have a flag to tell client that some of the
5508 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005509 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005510 }
5511 // flush data already sent to the DSP if changing audio session as audio
5512 // comes from a different source. Also invalidate previous track to force a
5513 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005514 if (previousTrack->sessionId() != track->sessionId()) {
5515 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005516 }
5517 }
5518 }
5519 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005520 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005521 if (track->isStopping_1()) {
5522 track->mRetryCount = kMaxTrackStopRetriesOffload;
5523 } else {
5524 track->mRetryCount = kMaxTrackRetriesOffload;
5525 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005526 mActiveTrack = t;
5527 mixerStatus = MIXER_TRACKS_READY;
5528 }
5529 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005530 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005531 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005532 if (--(track->mRetryCount) <= 0) {
5533 // Hardware buffer can hold a large amount of audio so we must
5534 // wait for all current track's data to drain before we say
5535 // that the track is stopped.
5536 if (mBytesRemaining == 0) {
5537 // Only start draining when all data in mixbuffer
5538 // has been written
5539 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5540 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5541 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5542 if (last && !mStandby) {
5543 // do not modify drain sequence if we are already draining. This happens
5544 // when resuming from pause after drain.
5545 if ((mDrainSequence & 1) == 0) {
5546 mSleepTimeUs = 0;
5547 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5548 mixerStatus = MIXER_DRAIN_TRACK;
5549 mDrainSequence += 2;
5550 }
5551 if (mHwPaused) {
5552 // It is possible to move from PAUSED to STOPPING_1 without
5553 // a resume so we must ensure hardware is running
5554 doHwResume = true;
5555 mHwPaused = false;
5556 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005557 }
5558 }
Eric Laurente93cc032016-05-05 10:15:10 -07005559 } else if (last) {
5560 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5561 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005562 }
5563 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005564 // Drain has completed or we are in standby, signal presentation complete
5565 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005566 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005567 uint32_t latency = 0;
5568 status_t result = mOutput->stream->getLatency(&latency);
5569 ALOGE_IF(result != OK,
5570 "Error when retrieving output stream latency: %d", result);
5571 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005572 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005573 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005574 track->presentationComplete(framesWritten, audioHALFrames);
5575 track->reset();
5576 tracksToRemove->add(track);
5577 }
5578 } else {
5579 // No buffers for this track. Give it a few chances to
5580 // fill a buffer, then remove it from active list.
5581 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005582 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005583 uint64_t position = 0;
5584 struct timespec unused;
5585 // The running check restarts the retry counter at least once.
5586 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5587 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5588 running = true;
5589 mOffloadUnderrunPosition = position;
5590 }
5591 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005592 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5593 (long long)position, (long long)mOffloadUnderrunPosition);
5594 }
5595 if (running) { // still running, give us more time.
5596 track->mRetryCount = kMaxTrackRetriesOffload;
5597 } else {
5598 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5599 track->name());
5600 tracksToRemove->add(track);
5601 // indicate to client process that the track was disabled because of underrun;
5602 // it will then automatically call start() when data is available
5603 track->disable();
5604 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005605 } else if (last){
5606 mixerStatus = MIXER_TRACKS_ENABLED;
5607 }
5608 }
5609 }
5610 // compute volume for this track
5611 processVolume_l(track, last);
5612 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005613
Eric Laurentea0fade2013-10-04 16:23:48 -07005614 // make sure the pause/flush/resume sequence is executed in the right order.
5615 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5616 // before flush and then resume HW. This can happen in case of pause/flush/resume
5617 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005618 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005619 status_t result = mOutput->stream->pause();
5620 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005621 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005622 if (mFlushPending) {
5623 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005624 }
Eric Laurentfd477972013-10-25 18:10:40 -07005625 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005626 status_t result = mOutput->stream->resume();
5627 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005628 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005629
Eric Laurentbfb1b832013-01-07 09:53:42 -08005630 // remove all the tracks that need to be...
5631 removeTracks_l(*tracksToRemove);
5632
5633 return mixerStatus;
5634}
5635
Eric Laurentbfb1b832013-01-07 09:53:42 -08005636// must be called with thread mutex locked
5637bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5638{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005639 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5640 mWriteAckSequence, mDrainSequence);
5641 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005642 return true;
5643 }
5644 return false;
5645}
5646
Eric Laurentbfb1b832013-01-07 09:53:42 -08005647bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5648{
5649 Mutex::Autolock _l(mLock);
5650 return waitingAsyncCallback_l();
5651}
5652
5653void AudioFlinger::OffloadThread::flushHw_l()
5654{
Eric Laurente659ef42014-09-29 13:06:46 -07005655 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005656 // Flush anything still waiting in the mixbuffer
5657 mCurrentWriteLength = 0;
5658 mBytesRemaining = 0;
5659 mPausedWriteLength = 0;
5660 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005661 // reset bytes written count to reflect that DSP buffers are empty after flush.
5662 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005663 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005664
Eric Laurentbfb1b832013-01-07 09:53:42 -08005665 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005666 // discard any pending drain or write ack by incrementing sequence
5667 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5668 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005669 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005670 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5671 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005672 }
5673}
5674
Haynes Mathew George05317d22016-05-03 16:34:26 -07005675void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5676{
5677 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005678 if (PlaybackThread::invalidateTracks_l(streamType)) {
5679 mFlushPending = true;
5680 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005681}
5682
Eric Laurentbfb1b832013-01-07 09:53:42 -08005683// ----------------------------------------------------------------------------
5684
Eric Laurent81784c32012-11-19 14:55:58 -08005685AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005686 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005687 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005688 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005689 mWaitTimeMs(UINT_MAX)
5690{
5691 addOutputTrack(mainThread);
5692}
5693
5694AudioFlinger::DuplicatingThread::~DuplicatingThread()
5695{
5696 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5697 mOutputTracks[i]->destroy();
5698 }
5699}
5700
5701void AudioFlinger::DuplicatingThread::threadLoop_mix()
5702{
5703 // mix buffers...
5704 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005705 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005706 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005707 if (mMixerBufferValid) {
5708 memset(mMixerBuffer, 0, mMixerBufferSize);
5709 } else {
5710 memset(mSinkBuffer, 0, mSinkBufferSize);
5711 }
Eric Laurent81784c32012-11-19 14:55:58 -08005712 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005713 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005714 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005715 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005716 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005717}
5718
5719void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5720{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005721 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005722 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005723 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005724 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005725 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005726 }
5727 } else if (mBytesWritten != 0) {
5728 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5729 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005730 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005731 } else {
5732 // flush remaining overflow buffers in output tracks
5733 writeFrames = 0;
5734 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005735 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005736 }
5737}
5738
Eric Laurentbfb1b832013-01-07 09:53:42 -08005739ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005740{
5741 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005742 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005743 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005744 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005745 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005746}
5747
5748void AudioFlinger::DuplicatingThread::threadLoop_standby()
5749{
5750 // DuplicatingThread implements standby by stopping all tracks
5751 for (size_t i = 0; i < outputTracks.size(); i++) {
5752 outputTracks[i]->stop();
5753 }
5754}
5755
5756void AudioFlinger::DuplicatingThread::saveOutputTracks()
5757{
5758 outputTracks = mOutputTracks;
5759}
5760
5761void AudioFlinger::DuplicatingThread::clearOutputTracks()
5762{
5763 outputTracks.clear();
5764}
5765
5766void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5767{
5768 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005769 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5770 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5771 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5772 const size_t frameCount =
5773 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5774 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5775 // from different OutputTracks and their associated MixerThreads (e.g. one may
5776 // nearly empty and the other may be dropping data).
5777
5778 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005779 this,
5780 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005781 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005782 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005783 frameCount,
5784 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005785 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5786 if (status != NO_ERROR) {
5787 ALOGE("addOutputTrack() initCheck failed %d", status);
5788 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005789 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005790 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5791 mOutputTracks.add(outputTrack);
5792 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5793 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005794}
5795
5796void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5797{
5798 Mutex::Autolock _l(mLock);
5799 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5800 if (mOutputTracks[i]->thread() == thread) {
5801 mOutputTracks[i]->destroy();
5802 mOutputTracks.removeAt(i);
5803 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005804 if (thread->getOutput() == mOutput) {
5805 mOutput = NULL;
5806 }
Eric Laurent81784c32012-11-19 14:55:58 -08005807 return;
5808 }
5809 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005810 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005811}
5812
5813// caller must hold mLock
5814void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5815{
5816 mWaitTimeMs = UINT_MAX;
5817 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5818 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5819 if (strong != 0) {
5820 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5821 if (waitTimeMs < mWaitTimeMs) {
5822 mWaitTimeMs = waitTimeMs;
5823 }
5824 }
5825 }
5826}
5827
5828
5829bool AudioFlinger::DuplicatingThread::outputsReady(
5830 const SortedVector< sp<OutputTrack> > &outputTracks)
5831{
5832 for (size_t i = 0; i < outputTracks.size(); i++) {
5833 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5834 if (thread == 0) {
5835 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5836 outputTracks[i].get());
5837 return false;
5838 }
5839 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5840 // see note at standby() declaration
5841 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5842 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5843 thread.get());
5844 return false;
5845 }
5846 }
5847 return true;
5848}
5849
5850uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5851{
5852 return (mWaitTimeMs * 1000) / 2;
5853}
5854
5855void AudioFlinger::DuplicatingThread::cacheParameters_l()
5856{
5857 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5858 updateWaitTime_l();
5859
5860 MixerThread::cacheParameters_l();
5861}
5862
5863// ----------------------------------------------------------------------------
5864// Record
5865// ----------------------------------------------------------------------------
5866
5867AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5868 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005869 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005870 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005871 audio_devices_t inDevice,
5872 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005873#ifdef TEE_SINK
5874 , const sp<NBAIO_Sink>& teeSink
5875#endif
5876 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005877 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005878 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005879 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005880 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005881#ifdef TEE_SINK
5882 , mTeeSink(teeSink)
5883#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005884 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5885 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005886 // mFastCapture below
5887 , mFastCaptureFutex(0)
5888 // mInputSource
5889 // mPipeSink
5890 // mPipeSource
5891 , mPipeFramesP2(0)
5892 // mPipeMemory
5893 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005894 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005895{
Glenn Kastend7dca052015-03-05 16:05:54 -08005896 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5897 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005898
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005899 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005900
5901 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005902 mInputSource = new AudioStreamInSource(
5903 static_cast<StreamInHalLocal*>(input->stream.get())->getStream());
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005904 size_t numCounterOffers = 0;
5905 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005906#if !LOG_NDEBUG
5907 ssize_t index =
5908#else
5909 (void)
5910#endif
5911 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005912 ALOG_ASSERT(index == 0);
5913
5914 // initialize fast capture depending on configuration
5915 bool initFastCapture;
5916 switch (kUseFastCapture) {
5917 case FastCapture_Never:
5918 initFastCapture = false;
5919 break;
5920 case FastCapture_Always:
5921 initFastCapture = true;
5922 break;
5923 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005924 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005925 break;
5926 // case FastCapture_Dynamic:
5927 }
5928
5929 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005930 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005931 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005932 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5933 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005934 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5935 void *pipeBuffer;
5936 const sp<MemoryDealer> roHeap(readOnlyHeap());
5937 sp<IMemory> pipeMemory;
5938 if ((roHeap == 0) ||
5939 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5940 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5941 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5942 goto failed;
5943 }
5944 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5945 memset(pipeBuffer, 0, pipeSize);
5946 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5947 const NBAIO_Format offers[1] = {format};
5948 size_t numCounterOffers = 0;
5949 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5950 ALOG_ASSERT(index == 0);
5951 mPipeSink = pipe;
5952 PipeReader *pipeReader = new PipeReader(*pipe);
5953 numCounterOffers = 0;
5954 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5955 ALOG_ASSERT(index == 0);
5956 mPipeSource = pipeReader;
5957 mPipeFramesP2 = pipeFramesP2;
5958 mPipeMemory = pipeMemory;
5959
5960 // create fast capture
5961 mFastCapture = new FastCapture();
5962 FastCaptureStateQueue *sq = mFastCapture->sq();
5963#ifdef STATE_QUEUE_DUMP
5964 // FIXME
5965#endif
5966 FastCaptureState *state = sq->begin();
5967 state->mCblk = NULL;
5968 state->mInputSource = mInputSource.get();
5969 state->mInputSourceGen++;
5970 state->mPipeSink = pipe;
5971 state->mPipeSinkGen++;
5972 state->mFrameCount = mFrameCount;
5973 state->mCommand = FastCaptureState::COLD_IDLE;
5974 // already done in constructor initialization list
5975 //mFastCaptureFutex = 0;
5976 state->mColdFutexAddr = &mFastCaptureFutex;
5977 state->mColdGen++;
5978 state->mDumpState = &mFastCaptureDumpState;
5979#ifdef TEE_SINK
5980 // FIXME
5981#endif
5982 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5983 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5984 sq->end();
5985 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5986
5987 // start the fast capture
5988 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5989 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005990 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005991#ifdef AUDIO_WATCHDOG
5992 // FIXME
5993#endif
5994
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005995 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005996 }
5997failed: ;
5998
5999 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006000}
6001
Eric Laurent81784c32012-11-19 14:55:58 -08006002AudioFlinger::RecordThread::~RecordThread()
6003{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006004 if (mFastCapture != 0) {
6005 FastCaptureStateQueue *sq = mFastCapture->sq();
6006 FastCaptureState *state = sq->begin();
6007 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6008 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6009 if (old == -1) {
6010 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6011 }
6012 }
6013 state->mCommand = FastCaptureState::EXIT;
6014 sq->end();
6015 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6016 mFastCapture->join();
6017 mFastCapture.clear();
6018 }
6019 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006020 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006021 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006022}
6023
6024void AudioFlinger::RecordThread::onFirstRef()
6025{
Glenn Kastend7dca052015-03-05 16:05:54 -08006026 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006027}
6028
Eric Laurent81784c32012-11-19 14:55:58 -08006029bool AudioFlinger::RecordThread::threadLoop()
6030{
Eric Laurent81784c32012-11-19 14:55:58 -08006031 nsecs_t lastWarning = 0;
6032
6033 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006034
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006035reacquire_wakelock:
6036 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08006037 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006038 {
6039 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006040 size_t size = mActiveTracks.size();
6041 activeTracksGen = mActiveTracksGen;
6042 if (size > 0) {
6043 // FIXME an arbitrary choice
6044 activeTrack = mActiveTracks[0];
6045 acquireWakeLock_l(activeTrack->uid());
6046 if (size > 1) {
6047 SortedVector<int> tmp;
6048 for (size_t i = 0; i < size; i++) {
6049 tmp.add(mActiveTracks[i]->uid());
6050 }
6051 updateWakeLockUids_l(tmp);
6052 }
6053 } else {
6054 acquireWakeLock_l(-1);
6055 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006056 }
6057
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006058 // used to request a deferred sleep, to be executed later while mutex is unlocked
6059 uint32_t sleepUs = 0;
6060
6061 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006062 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006063 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006064
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006065 // activeTracks accumulates a copy of a subset of mActiveTracks
6066 Vector< sp<RecordTrack> > activeTracks;
6067
Glenn Kasten735f45f2014-08-18 15:51:59 -07006068 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006069 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006070
Glenn Kasten735f45f2014-08-18 15:51:59 -07006071 // reference to a fast track which is about to be removed
6072 sp<RecordTrack> fastTrackToRemove;
6073
Eric Laurent81784c32012-11-19 14:55:58 -08006074 { // scope for mLock
6075 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006076
Eric Laurent021cf962014-05-13 10:18:14 -07006077 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006078
Eric Laurent000a4192014-01-29 15:17:32 -08006079 // check exitPending here because checkForNewParameters_l() and
6080 // checkForNewParameters_l() can temporarily release mLock
6081 if (exitPending()) {
6082 break;
6083 }
6084
Eric Laurent5c25d562016-07-13 17:17:45 -07006085 // sleep with mutex unlocked
6086 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006087 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006088 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6089 ATRACE_END();
6090 sleepUs = 0;
6091 continue;
6092 }
6093
Glenn Kasten2b806402013-11-20 16:37:38 -08006094 // if no active track(s), then standby and release wakelock
6095 size_t size = mActiveTracks.size();
6096 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006097 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006098 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006099 releaseWakeLock_l();
6100 ALOGV("RecordThread: loop stopping");
6101 // go to sleep
6102 mWaitWorkCV.wait(mLock);
6103 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006104 goto reacquire_wakelock;
6105 }
6106
Glenn Kasten2b806402013-11-20 16:37:38 -08006107 if (mActiveTracksGen != activeTracksGen) {
6108 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006109 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006110 for (size_t i = 0; i < size; i++) {
6111 tmp.add(mActiveTracks[i]->uid());
6112 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006113 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006114 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006115
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006116 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006117 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006118 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006119
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006120 activeTrack = mActiveTracks[i];
6121 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006122 if (activeTrack->isFastTrack()) {
6123 ALOG_ASSERT(fastTrackToRemove == 0);
6124 fastTrackToRemove = activeTrack;
6125 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006126 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006127 mActiveTracks.remove(activeTrack);
6128 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006129 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006130 continue;
6131 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006132
6133 TrackBase::track_state activeTrackState = activeTrack->mState;
6134 switch (activeTrackState) {
6135
6136 case TrackBase::PAUSING:
6137 mActiveTracks.remove(activeTrack);
6138 mActiveTracksGen++;
6139 doBroadcast = true;
6140 size--;
6141 continue;
6142
6143 case TrackBase::STARTING_1:
6144 sleepUs = 10000;
6145 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006146 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006147 continue;
6148
6149 case TrackBase::STARTING_2:
6150 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006151 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006152 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006153 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006154 break;
6155
6156 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006157 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006158 break;
6159
6160 case TrackBase::IDLE:
6161 i++;
6162 continue;
6163
6164 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006165 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006166 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006167
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006168 activeTracks.add(activeTrack);
6169 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006170
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006171 if (activeTrack->isFastTrack()) {
6172 ALOG_ASSERT(!mFastTrackAvail);
6173 ALOG_ASSERT(fastTrack == 0);
6174 fastTrack = activeTrack;
6175 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006176 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006177
6178 if (allStopped) {
6179 standbyIfNotAlreadyInStandby();
6180 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006181 if (doBroadcast) {
6182 mStartStopCond.broadcast();
6183 }
6184
6185 // sleep if there are no active tracks to process
6186 if (activeTracks.size() == 0) {
6187 if (sleepUs == 0) {
6188 sleepUs = kRecordThreadSleepUs;
6189 }
6190 continue;
6191 }
6192 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006193
Eric Laurent81784c32012-11-19 14:55:58 -08006194 lockEffectChains_l(effectChains);
6195 }
6196
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006197 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006198
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006199 size_t size = effectChains.size();
6200 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006201 // thread mutex is not locked, but effect chain is locked
6202 effectChains[i]->process_l();
6203 }
6204
Glenn Kasten735f45f2014-08-18 15:51:59 -07006205 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006206 if (mFastCapture != 0) {
6207 FastCaptureStateQueue *sq = mFastCapture->sq();
6208 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006209 bool didModify = false;
6210 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006211 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6212 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6213 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6214 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6215 if (old == -1) {
6216 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6217 }
6218 }
6219 state->mCommand = FastCaptureState::READ_WRITE;
6220#if 0 // FIXME
6221 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006222 FastThreadDumpState::kSamplingNforLowRamDevice :
6223 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006224#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006225 didModify = true;
6226 }
6227 audio_track_cblk_t *cblkOld = state->mCblk;
6228 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6229 if (cblkNew != cblkOld) {
6230 state->mCblk = cblkNew;
6231 // block until acked if removing a fast track
6232 if (cblkOld != NULL) {
6233 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6234 }
6235 didModify = true;
6236 }
6237 sq->end(didModify);
6238 if (didModify) {
6239 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006240#if 0
6241 if (kUseFastCapture == FastCapture_Dynamic) {
6242 mNormalSource = mPipeSource;
6243 }
6244#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006245 }
6246 }
6247
Glenn Kasten735f45f2014-08-18 15:51:59 -07006248 // now run the fast track destructor with thread mutex unlocked
6249 fastTrackToRemove.clear();
6250
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006251 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6252 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6253 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6254 // If destination is non-contiguous, first read past the nominal end of buffer, then
6255 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006256
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006257 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006258 ssize_t framesRead;
6259
6260 // If an NBAIO source is present, use it to read the normal capture's data
6261 if (mPipeSource != 0) {
6262 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006263 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006264 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006265 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006266 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6267 // buffer size or at least for 20ms.
6268 size_t sleepFrames = max(
6269 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6270 if (framesRead <= (ssize_t) sleepFrames) {
6271 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6272 }
6273 if (framesRead < 0) {
6274 status_t status = (status_t) framesRead;
6275 switch (status) {
6276 case OVERRUN:
6277 ALOGW("overrun on read from pipe");
6278 framesRead = 0;
6279 break;
6280 case NEGOTIATE:
6281 ALOGE("re-negotiation is needed");
6282 framesRead = -1; // Will cause an attempt to recover.
6283 break;
6284 default:
6285 ALOGE("unknown error %d on read from pipe", status);
6286 break;
6287 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006288 }
6289 // otherwise use the HAL / AudioStreamIn directly
6290 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006291 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006292 size_t bytesRead;
6293 status_t result = mInput->stream->read(
6294 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006295 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006296 if (result < 0) {
6297 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006298 } else {
6299 framesRead = bytesRead / mFrameSize;
6300 }
6301 }
6302
Andy Hung3f0c9022016-01-15 17:49:46 -08006303 // Update server timestamp with server stats
6304 // systemTime() is optional if the hardware supports timestamps.
6305 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6306 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6307
6308 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006309 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006310 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006311 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006312 if (ret == NO_ERROR) {
6313 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6314 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6315 // Note: In general record buffers should tend to be empty in
6316 // a properly running pipeline.
6317 //
6318 // Also, it is not advantageous to call get_presentation_position during the read
6319 // as the read obtains a lock, preventing the timestamp call from executing.
6320 }
6321 }
6322 // Use this to track timestamp information
6323 // ALOGD("%s", mTimestamp.toString().c_str());
6324
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006325 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006326 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006327 // Force input into standby so that it tries to recover at next read attempt
6328 inputStandBy();
6329 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006330 }
6331 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006332 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006333 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006335
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006336 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006337 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006338 }
6339 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006340 {
6341 size_t part1 = mRsmpInFramesP2 - rear;
6342 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006343 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006344 (framesRead - part1) * mFrameSize);
6345 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006346 }
6347 rear = mRsmpInRear += framesRead;
6348
6349 size = activeTracks.size();
6350 // loop over each active track
6351 for (size_t i = 0; i < size; i++) {
6352 activeTrack = activeTracks[i];
6353
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006354 // skip fast tracks, as those are handled directly by FastCapture
6355 if (activeTrack->isFastTrack()) {
6356 continue;
6357 }
6358
Andy Hung73c02e42015-03-29 01:13:58 -07006359 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006360 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6361
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006362 enum {
6363 OVERRUN_UNKNOWN,
6364 OVERRUN_TRUE,
6365 OVERRUN_FALSE
6366 } overrun = OVERRUN_UNKNOWN;
6367
6368 // loop over getNextBuffer to handle circular sink
6369 for (;;) {
6370
6371 activeTrack->mSink.frameCount = ~0;
6372 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6373 size_t framesOut = activeTrack->mSink.frameCount;
6374 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6375
Andy Hung73c02e42015-03-29 01:13:58 -07006376 // check available frames and handle overrun conditions
6377 // if the record track isn't draining fast enough.
6378 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006379 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006380 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6381 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006382 overrun = OVERRUN_TRUE;
6383 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006384 if (framesOut == 0 || framesIn == 0) {
6385 break;
6386 }
6387
Andy Hung6770c6f2015-04-07 13:43:36 -07006388 // Don't allow framesOut to be larger than what is possible with resampling
6389 // from framesIn.
6390 // This isn't strictly necessary but helps limit buffer resizing in
6391 // RecordBufferConverter. TODO: remove when no longer needed.
6392 framesOut = min(framesOut,
6393 destinationFramesPossible(
6394 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006395 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6396 framesOut = activeTrack->mRecordBufferConverter->convert(
6397 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006398
6399 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6400 overrun = OVERRUN_FALSE;
6401 }
6402
6403 if (activeTrack->mFramesToDrop == 0) {
6404 if (framesOut > 0) {
6405 activeTrack->mSink.frameCount = framesOut;
6406 activeTrack->releaseBuffer(&activeTrack->mSink);
6407 }
6408 } else {
6409 // FIXME could do a partial drop of framesOut
6410 if (activeTrack->mFramesToDrop > 0) {
6411 activeTrack->mFramesToDrop -= framesOut;
6412 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006413 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006414 }
6415 } else {
6416 activeTrack->mFramesToDrop += framesOut;
6417 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6418 activeTrack->mSyncStartEvent->isCancelled()) {
6419 ALOGW("Synced record %s, session %d, trigger session %d",
6420 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6421 activeTrack->sessionId(),
6422 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006423 activeTrack->mSyncStartEvent->triggerSession() :
6424 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006425 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006426 }
6427 }
6428 }
6429
6430 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006431 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006432 }
6433 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006434
6435 switch (overrun) {
6436 case OVERRUN_TRUE:
6437 // client isn't retrieving buffers fast enough
6438 if (!activeTrack->setOverflow()) {
6439 nsecs_t now = systemTime();
6440 // FIXME should lastWarning per track?
6441 if ((now - lastWarning) > kWarningThrottleNs) {
6442 ALOGW("RecordThread: buffer overflow");
6443 lastWarning = now;
6444 }
6445 }
6446 break;
6447 case OVERRUN_FALSE:
6448 activeTrack->clearOverflow();
6449 break;
6450 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006451 break;
6452 }
6453
Andy Hung3f0c9022016-01-15 17:49:46 -08006454 // update frame information and push timestamp out
6455 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006456 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006457 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6458 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006459 }
6460
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006461unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006462 // enable changes in effect chain
6463 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006464 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006465 }
6466
Glenn Kasten93e471f2013-08-19 08:40:07 -07006467 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006468
6469 {
6470 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006471 for (size_t i = 0; i < mTracks.size(); i++) {
6472 sp<RecordTrack> track = mTracks[i];
6473 track->invalidate();
6474 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006475 mActiveTracks.clear();
6476 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006477 mStartStopCond.broadcast();
6478 }
6479
6480 releaseWakeLock();
6481
6482 ALOGV("RecordThread %p exiting", this);
6483 return false;
6484}
6485
Glenn Kasten93e471f2013-08-19 08:40:07 -07006486void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006487{
6488 if (!mStandby) {
6489 inputStandBy();
6490 mStandby = true;
6491 }
6492}
6493
6494void AudioFlinger::RecordThread::inputStandBy()
6495{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006496 // Idle the fast capture if it's currently running
6497 if (mFastCapture != 0) {
6498 FastCaptureStateQueue *sq = mFastCapture->sq();
6499 FastCaptureState *state = sq->begin();
6500 if (!(state->mCommand & FastCaptureState::IDLE)) {
6501 state->mCommand = FastCaptureState::COLD_IDLE;
6502 state->mColdFutexAddr = &mFastCaptureFutex;
6503 state->mColdGen++;
6504 mFastCaptureFutex = 0;
6505 sq->end();
6506 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6507 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6508#if 0
6509 if (kUseFastCapture == FastCapture_Dynamic) {
6510 // FIXME
6511 }
6512#endif
6513#ifdef AUDIO_WATCHDOG
6514 // FIXME
6515#endif
6516 } else {
6517 sq->end(false /*didModify*/);
6518 }
6519 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006520 status_t result = mInput->stream->standby();
6521 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006522
6523 // If going into standby, flush the pipe source.
6524 if (mPipeSource.get() != nullptr) {
6525 const ssize_t flushed = mPipeSource->flush();
6526 if (flushed > 0) {
6527 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6528 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6529 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6530 }
6531 }
Eric Laurent81784c32012-11-19 14:55:58 -08006532}
6533
Glenn Kasten05997e22014-03-13 15:08:33 -07006534// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006535sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006536 const sp<AudioFlinger::Client>& client,
6537 uint32_t sampleRate,
6538 audio_format_t format,
6539 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006540 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006541 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006542 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006543 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006544 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006545 pid_t tid,
6546 status_t *status)
6547{
Glenn Kasten74935e42013-12-19 08:56:45 -08006548 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006549 sp<RecordTrack> track;
6550 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006551 audio_input_flags_t inputFlags = mInput->flags;
6552
6553 // special case for FAST flag considered OK if fast capture is present
6554 if (hasFastCapture()) {
6555 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6556 }
6557
6558 // Check if requested flags are compatible with output stream flags
6559 if ((*flags & inputFlags) != *flags) {
6560 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6561 " input flags (%08x)",
6562 *flags, inputFlags);
6563 *flags = (audio_input_flags_t)(*flags & inputFlags);
6564 }
Eric Laurent81784c32012-11-19 14:55:58 -08006565
Glenn Kasten90e58b12013-07-31 16:16:02 -07006566 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006567 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006568 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006569 // we formerly checked for a callback handler (non-0 tid),
6570 // but that is no longer required for TRANSFER_OBTAIN mode
6571 //
Glenn Kasten74105912014-07-03 12:28:53 -07006572 // frame count is not specified, or is exactly the pipe depth
6573 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006574 // PCM data
6575 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006576 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006577 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006578 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006579 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006580 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006581 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006582 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006583 hasFastCapture() &&
6584 // there are sufficient fast track slots available
6585 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006586 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006587 // check compatibility with audio effects.
6588 Mutex::Autolock _l(mLock);
6589 // Do not accept FAST flag if the session has software effects
6590 sp<EffectChain> chain = getEffectChain_l(sessionId);
6591 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07006592 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006593 "AUDIO_INPUT_FLAG_RAW denied: effect present on session");
6594 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
6595 if (chain->hasSoftwareEffect()) {
6596 ALOGV("AUDIO_INPUT_FLAG_FAST denied: software effect present on session");
6597 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
6598 }
6599 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006600 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006601 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6602 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006603 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006604 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006605 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006606 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006607 frameCount, mFrameCount, mPipeFramesP2,
6608 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6609 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006610 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006611 }
6612 }
6613
6614 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006615 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006616 // fast track: frame count is exactly the pipe depth
6617 frameCount = mPipeFramesP2;
6618 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6619 *notificationFrames = mFrameCount;
6620 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006621 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6622 // or 20 ms if there is a fast capture
6623 // TODO This could be a roundupRatio inline, and const
6624 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6625 * sampleRate + mSampleRate - 1) / mSampleRate;
6626 // minimum number of notification periods is at least kMinNotifications,
6627 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6628 static const size_t kMinNotifications = 3;
6629 static const uint32_t kMinMs = 30;
6630 // TODO This could be a roundupRatio inline
6631 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6632 // TODO This could be a roundupRatio inline
6633 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6634 maxNotificationFrames;
6635 const size_t minFrameCount = maxNotificationFrames *
6636 max(kMinNotifications, minNotificationsByMs);
6637 frameCount = max(frameCount, minFrameCount);
6638 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6639 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006640 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006641 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006642 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006643
Glenn Kasten15e57982013-09-24 11:52:37 -07006644 lStatus = initCheck();
6645 if (lStatus != NO_ERROR) {
6646 ALOGE("createRecordTrack_l() audio driver not initialized");
6647 goto Exit;
6648 }
Eric Laurent81784c32012-11-19 14:55:58 -08006649
6650 { // scope for mLock
6651 Mutex::Autolock _l(mLock);
6652
6653 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006654 format, channelMask, frameCount, NULL, sessionId, uid,
6655 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006656
Glenn Kasten03003332013-08-06 15:40:54 -07006657 lStatus = track->initCheck();
6658 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006659 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006660 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006661 goto Exit;
6662 }
6663 mTracks.add(track);
6664
6665 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6666 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6667 mAudioFlinger->btNrecIsOff();
6668 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6669 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006670
Eric Laurent05067782016-06-01 18:27:28 -07006671 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006672 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6673 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6674 // so ask activity manager to do this on our behalf
6675 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6676 }
Eric Laurent81784c32012-11-19 14:55:58 -08006677 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006678
Eric Laurent81784c32012-11-19 14:55:58 -08006679 lStatus = NO_ERROR;
6680
6681Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006682 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006683 return track;
6684}
6685
6686status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6687 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006688 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006689{
6690 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6691 sp<ThreadBase> strongMe = this;
6692 status_t status = NO_ERROR;
6693
6694 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006695 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006696 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006697 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006698 triggerSession,
6699 recordTrack->sessionId(),
6700 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006701 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006702 // Sync event can be cancelled by the trigger session if the track is not in a
6703 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006704 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006705 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006706 } else {
6707 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006708 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006709 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006710 }
6711 }
6712
6713 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006714 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006715 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006716 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6717 if (recordTrack->mState == TrackBase::PAUSING) {
6718 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006719 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006720 } else {
6721 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006722 }
6723 return status;
6724 }
6725
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006726 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6727 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6728 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006729 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006730 mActiveTracks.add(recordTrack);
6731 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006732 status_t status = NO_ERROR;
6733 if (recordTrack->isExternalTrack()) {
6734 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006735 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006736 mLock.lock();
6737 // FIXME should verify that recordTrack is still in mActiveTracks
6738 if (status != NO_ERROR) {
6739 mActiveTracks.remove(recordTrack);
6740 mActiveTracksGen++;
6741 recordTrack->clearSyncStartEvent();
6742 ALOGV("RecordThread::start error %d", status);
6743 return status;
6744 }
Eric Laurent81784c32012-11-19 14:55:58 -08006745 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006746 // Catch up with current buffer indices if thread is already running.
6747 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6748 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6749 // see previously buffered data before it called start(), but with greater risk of overrun.
6750
Andy Hung73c02e42015-03-29 01:13:58 -07006751 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006752 // clear any converter state as new data will be discontinuous
6753 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006754 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006755 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006756 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006757 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006758 ALOGV("Record failed to start");
6759 status = BAD_VALUE;
6760 goto startError;
6761 }
Eric Laurent81784c32012-11-19 14:55:58 -08006762 return status;
6763 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006764
Eric Laurent81784c32012-11-19 14:55:58 -08006765startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006766 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006767 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006768 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006769 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006770 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006771 return status;
6772}
6773
Eric Laurent81784c32012-11-19 14:55:58 -08006774void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6775{
6776 sp<SyncEvent> strongEvent = event.promote();
6777
6778 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006779 sp<RefBase> ptr = strongEvent->cookie().promote();
6780 if (ptr != 0) {
6781 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6782 recordTrack->handleSyncStartEvent(strongEvent);
6783 }
Eric Laurent81784c32012-11-19 14:55:58 -08006784 }
6785}
6786
Glenn Kastena8356f62013-07-25 14:37:52 -07006787bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006788 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006789 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006790 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006791 return false;
6792 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006793 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006794 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006795 // signal thread to stop
6796 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006797 // do not wait for mStartStopCond if exiting
6798 if (exitPending()) {
6799 return true;
6800 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006801 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006802 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006803 // if we have been restarted, recordTrack is in mActiveTracks here
6804 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006805 ALOGV("Record stopped OK");
6806 return true;
6807 }
6808 return false;
6809}
6810
Glenn Kasten0f11b512014-01-31 16:18:54 -08006811bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006812{
6813 return false;
6814}
6815
Glenn Kasten0f11b512014-01-31 16:18:54 -08006816status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006817{
6818#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6819 if (!isValidSyncEvent(event)) {
6820 return BAD_VALUE;
6821 }
6822
Glenn Kastend848eb42016-03-08 13:42:11 -08006823 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006824 status_t ret = NAME_NOT_FOUND;
6825
6826 Mutex::Autolock _l(mLock);
6827
6828 for (size_t i = 0; i < mTracks.size(); i++) {
6829 sp<RecordTrack> track = mTracks[i];
6830 if (eventSession == track->sessionId()) {
6831 (void) track->setSyncEvent(event);
6832 ret = NO_ERROR;
6833 }
6834 }
6835 return ret;
6836#else
6837 return BAD_VALUE;
6838#endif
6839}
6840
6841// destroyTrack_l() must be called with ThreadBase::mLock held
6842void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6843{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006844 track->terminate();
6845 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006846 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006847 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006848 removeTrack_l(track);
6849 }
6850}
6851
6852void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6853{
6854 mTracks.remove(track);
6855 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006856 if (track->isFastTrack()) {
6857 ALOG_ASSERT(!mFastTrackAvail);
6858 mFastTrackAvail = true;
6859 }
Eric Laurent81784c32012-11-19 14:55:58 -08006860}
6861
6862void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6863{
6864 dumpInternals(fd, args);
6865 dumpTracks(fd, args);
6866 dumpEffectChains(fd, args);
6867}
6868
6869void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6870{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006871 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006872
Glenn Kasten44182c22015-03-05 17:12:23 -08006873 dumpBase(fd, args);
6874
6875 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006876 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006877 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006878 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006879 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006880
Glenn Kasten2f90c512015-12-02 11:40:09 -08006881 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6882 // while we are dumping it. It may be inconsistent, but it won't mutate!
6883 // This is a large object so we place it on the heap.
6884 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6885 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6886 copy->dump(fd);
6887 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006888}
6889
Glenn Kasten0f11b512014-01-31 16:18:54 -08006890void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006891{
6892 const size_t SIZE = 256;
6893 char buffer[SIZE];
6894 String8 result;
6895
Marco Nelissenb2208842014-02-07 14:00:50 -08006896 size_t numtracks = mTracks.size();
6897 size_t numactive = mActiveTracks.size();
6898 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006899 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006900 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006901 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006902 RecordTrack::appendDumpHeader(result);
6903 for (size_t i = 0; i < numtracks ; ++i) {
6904 sp<RecordTrack> track = mTracks[i];
6905 if (track != 0) {
6906 bool active = mActiveTracks.indexOf(track) >= 0;
6907 if (active) {
6908 numactiveseen++;
6909 }
6910 track->dump(buffer, SIZE, active);
6911 result.append(buffer);
6912 }
Eric Laurent81784c32012-11-19 14:55:58 -08006913 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006914 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006915 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006916 }
6917
Marco Nelissenb2208842014-02-07 14:00:50 -08006918 if (numactiveseen != numactive) {
6919 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6920 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006921 result.append(buffer);
6922 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006923 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006924 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006925 if (mTracks.indexOf(track) < 0) {
6926 track->dump(buffer, SIZE, true);
6927 result.append(buffer);
6928 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006929 }
Eric Laurent81784c32012-11-19 14:55:58 -08006930
6931 }
6932 write(fd, result.string(), result.size());
6933}
6934
Andy Hung73c02e42015-03-29 01:13:58 -07006935
6936void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6937{
6938 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6939 RecordThread *recordThread = (RecordThread *) threadBase.get();
6940 mRsmpInFront = recordThread->mRsmpInRear;
6941 mRsmpInUnrel = 0;
6942}
6943
6944void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6945 size_t *framesAvailable, bool *hasOverrun)
6946{
6947 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6948 RecordThread *recordThread = (RecordThread *) threadBase.get();
6949 const int32_t rear = recordThread->mRsmpInRear;
6950 const int32_t front = mRsmpInFront;
6951 const ssize_t filled = rear - front;
6952
6953 size_t framesIn;
6954 bool overrun = false;
6955 if (filled < 0) {
6956 // should not happen, but treat like a massive overrun and re-sync
6957 framesIn = 0;
6958 mRsmpInFront = rear;
6959 overrun = true;
6960 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6961 framesIn = (size_t) filled;
6962 } else {
6963 // client is not keeping up with server, but give it latest data
6964 framesIn = recordThread->mRsmpInFrames;
6965 mRsmpInFront = /* front = */ rear - framesIn;
6966 overrun = true;
6967 }
6968 if (framesAvailable != NULL) {
6969 *framesAvailable = framesIn;
6970 }
6971 if (hasOverrun != NULL) {
6972 *hasOverrun = overrun;
6973 }
6974}
6975
Eric Laurent81784c32012-11-19 14:55:58 -08006976// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006977status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006978 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006979{
Andy Hung73c02e42015-03-29 01:13:58 -07006980 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006981 if (threadBase == 0) {
6982 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006983 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006984 return NOT_ENOUGH_DATA;
6985 }
6986 RecordThread *recordThread = (RecordThread *) threadBase.get();
6987 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006988 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006989 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006990 // FIXME should not be P2 (don't want to increase latency)
6991 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006992 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006993 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006994 front &= recordThread->mRsmpInFramesP2 - 1;
6995 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006996 if (part1 > (size_t) filled) {
6997 part1 = filled;
6998 }
6999 size_t ask = buffer->frameCount;
7000 ALOG_ASSERT(ask > 0);
7001 if (part1 > ask) {
7002 part1 = ask;
7003 }
7004 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007005 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007006 buffer->raw = NULL;
7007 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007008 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007009 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007010 }
7011
Andy Hung57446612015-04-19 23:56:46 -07007012 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007013 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007014 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007015 return NO_ERROR;
7016}
7017
7018// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007019void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7020 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007021{
Glenn Kasten85948432013-08-19 12:09:05 -07007022 size_t stepCount = buffer->frameCount;
7023 if (stepCount == 0) {
7024 return;
7025 }
Andy Hung73c02e42015-03-29 01:13:58 -07007026 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7027 mRsmpInUnrel -= stepCount;
7028 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007029 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007030 buffer->frameCount = 0;
7031}
7032
Andy Hung97a893e2015-03-29 01:03:07 -07007033AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7034 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7035 uint32_t srcSampleRate,
7036 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7037 uint32_t dstSampleRate) :
7038 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7039 // mSrcFormat
7040 // mSrcSampleRate
7041 // mDstChannelMask
7042 // mDstFormat
7043 // mDstSampleRate
7044 // mSrcChannelCount
7045 // mDstChannelCount
7046 // mDstFrameSize
7047 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07007048 mResampler(NULL),
7049 mIsLegacyDownmix(false),
7050 mIsLegacyUpmix(false),
7051 mRequiresFloat(false),
7052 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007053{
7054 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7055 dstChannelMask, dstFormat, dstSampleRate);
7056}
7057
7058AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7059 free(mBuf);
7060 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007061 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007062}
7063
7064size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7065 AudioBufferProvider *provider, size_t frames)
7066{
Andy Hungd330ee42015-04-20 13:23:41 -07007067 if (mInputConverterProvider != NULL) {
7068 mInputConverterProvider->setBufferProvider(provider);
7069 provider = mInputConverterProvider;
7070 }
7071
7072 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007073 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7074 mSrcSampleRate, mSrcFormat, mDstFormat);
7075
7076 AudioBufferProvider::Buffer buffer;
7077 for (size_t i = frames; i > 0; ) {
7078 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007079 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007080 if (status != OK || buffer.frameCount == 0) {
7081 frames -= i; // cannot fill request.
7082 break;
7083 }
Andy Hungd330ee42015-04-20 13:23:41 -07007084 // format convert to destination buffer
7085 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007086
7087 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7088 i -= buffer.frameCount;
7089 provider->releaseBuffer(&buffer);
7090 }
7091 } else {
7092 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7093 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7094
Andy Hungd330ee42015-04-20 13:23:41 -07007095 // reallocate buffer if needed
7096 if (mBufFrameSize != 0 && mBufFrames < frames) {
7097 free(mBuf);
7098 mBufFrames = frames;
7099 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7100 }
Andy Hung97a893e2015-03-29 01:03:07 -07007101 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007102 memset(mBuf, 0, frames * mBufFrameSize);
7103 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7104 // format convert to destination buffer
7105 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007106 }
7107 return frames;
7108}
7109
7110status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7111 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7112 uint32_t srcSampleRate,
7113 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7114 uint32_t dstSampleRate)
7115{
7116 // quick evaluation if there is any change.
7117 if (mSrcFormat == srcFormat
7118 && mSrcChannelMask == srcChannelMask
7119 && mSrcSampleRate == srcSampleRate
7120 && mDstFormat == dstFormat
7121 && mDstChannelMask == dstChannelMask
7122 && mDstSampleRate == dstSampleRate) {
7123 return NO_ERROR;
7124 }
7125
Andy Hungdb4c0312015-05-06 08:46:52 -07007126 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7127 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7128 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007129 const bool valid =
7130 audio_is_input_channel(srcChannelMask)
7131 && audio_is_input_channel(dstChannelMask)
7132 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7133 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7134 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7135 ; // no upsampling checks for now
7136 if (!valid) {
7137 return BAD_VALUE;
7138 }
7139
7140 mSrcFormat = srcFormat;
7141 mSrcChannelMask = srcChannelMask;
7142 mSrcSampleRate = srcSampleRate;
7143 mDstFormat = dstFormat;
7144 mDstChannelMask = dstChannelMask;
7145 mDstSampleRate = dstSampleRate;
7146
7147 // compute derived parameters
7148 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7149 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7150 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7151
Andy Hungd330ee42015-04-20 13:23:41 -07007152 // do we need to resample?
7153 delete mResampler;
7154 mResampler = NULL;
7155 if (mSrcSampleRate != mDstSampleRate) {
7156 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7157 mSrcChannelCount, mDstSampleRate);
7158 mResampler->setSampleRate(mSrcSampleRate);
7159 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7160 }
7161
7162 // are we running legacy channel conversion modes?
7163 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7164 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7165 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7166 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7167 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7168 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7169
7170 // do we need to process in float?
7171 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7172
7173 // do we need a staging buffer to convert for destination (we can still optimize this)?
7174 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7175 if (mResampler != NULL) {
7176 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7177 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007178 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007179 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7180 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007181 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7182 } else {
7183 mBufFrameSize = 0;
7184 }
7185 mBufFrames = 0; // force the buffer to be resized.
7186
Andy Hungd330ee42015-04-20 13:23:41 -07007187 // do we need an input converter buffer provider to give us float?
7188 delete mInputConverterProvider;
7189 mInputConverterProvider = NULL;
7190 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7191 mInputConverterProvider = new ReformatBufferProvider(
7192 audio_channel_count_from_in_mask(mSrcChannelMask),
7193 mSrcFormat,
7194 AUDIO_FORMAT_PCM_FLOAT,
7195 256 /* provider buffer frame count */);
7196 }
7197
7198 // do we need a remixer to do channel mask conversion
7199 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7200 (void) memcpy_by_index_array_initialization_from_channel_mask(
7201 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007202 }
7203 return NO_ERROR;
7204}
7205
Andy Hungd330ee42015-04-20 13:23:41 -07007206void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7207 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007208{
Andy Hungd330ee42015-04-20 13:23:41 -07007209 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007210 if (mBufFrameSize != 0 && mBufFrames < frames) {
7211 free(mBuf);
7212 mBufFrames = frames;
7213 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7214 }
Andy Hungd330ee42015-04-20 13:23:41 -07007215 // do we need to do legacy upmix and downmix?
7216 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007217 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007218 if (mIsLegacyUpmix) {
7219 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7220 (const float *)src, frames);
7221 } else /*mIsLegacyDownmix */ {
7222 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7223 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007224 }
Andy Hungd330ee42015-04-20 13:23:41 -07007225 if (mBuf != NULL) {
7226 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7227 frames * mDstChannelCount);
7228 }
7229 return;
7230 }
7231 // do we need to do channel mask conversion?
7232 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007233 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007234 memcpy_by_index_array(dstBuf, mDstChannelCount,
7235 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7236 if (dstBuf == dst) {
7237 return; // format is the same
7238 }
7239 }
7240 // convert to destination buffer
7241 const void *convertBuf = mBuf != NULL ? mBuf : src;
7242 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7243 frames * mDstChannelCount);
7244}
7245
7246void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7247 void *dst, /*not-a-const*/ void *src, size_t frames)
7248{
7249 // src buffer format is ALWAYS float when entering this routine
7250 if (mIsLegacyUpmix) {
7251 ; // mono to stereo already handled by resampler
7252 } else if (mIsLegacyDownmix
7253 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7254 // the resampler outputs stereo for mono input channel (a feature?)
7255 // must convert to mono
7256 downmix_to_mono_float_from_stereo_float((float *)src,
7257 (const float *)src, frames);
7258 } else if (mSrcChannelMask != mDstChannelMask) {
7259 // convert to mono channel again for channel mask conversion (could be skipped
7260 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007261 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007262 downmix_to_mono_float_from_stereo_float((float *)src,
7263 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007264 }
Andy Hungd330ee42015-04-20 13:23:41 -07007265 // convert to destination format (in place, OK as float is larger than other types)
7266 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7267 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7268 frames * mSrcChannelCount);
7269 }
7270 // channel convert and save to dst
7271 memcpy_by_index_array(dst, mDstChannelCount,
7272 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7273 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007274 }
Andy Hungd330ee42015-04-20 13:23:41 -07007275 // convert to destination format and save to dst
7276 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7277 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007278}
7279
Eric Laurent10351942014-05-08 18:49:52 -07007280bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7281 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007282{
7283 bool reconfig = false;
7284
Eric Laurent10351942014-05-08 18:49:52 -07007285 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007286
Eric Laurent10351942014-05-08 18:49:52 -07007287 audio_format_t reqFormat = mFormat;
7288 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007289 // 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 -07007290 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7291
7292 AudioParameter param = AudioParameter(keyValuePair);
7293 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007294
7295 // scope for AutoPark extends to end of method
7296 AutoPark<FastCapture> park(mFastCapture);
7297
Eric Laurent10351942014-05-08 18:49:52 -07007298 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7299 // channel count change can be requested. Do we mandate the first client defines the
7300 // HAL sampling rate and channel count or do we allow changes on the fly?
7301 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7302 samplingRate = value;
7303 reconfig = true;
7304 }
7305 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007306 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007307 status = BAD_VALUE;
7308 } else {
7309 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007310 reconfig = true;
7311 }
Eric Laurent10351942014-05-08 18:49:52 -07007312 }
7313 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7314 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007315 if (!audio_is_input_channel(mask) ||
7316 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007317 status = BAD_VALUE;
7318 } else {
7319 channelMask = mask;
7320 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007321 }
Eric Laurent10351942014-05-08 18:49:52 -07007322 }
7323 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7324 // do not accept frame count changes if tracks are open as the track buffer
7325 // size depends on frame count and correct behavior would not be guaranteed
7326 // if frame count is changed after track creation
7327 if (mActiveTracks.size() > 0) {
7328 status = INVALID_OPERATION;
7329 } else {
7330 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007331 }
Eric Laurent10351942014-05-08 18:49:52 -07007332 }
7333 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7334 // forward device change to effects that have requested to be
7335 // aware of attached audio device.
7336 for (size_t i = 0; i < mEffectChains.size(); i++) {
7337 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007338 }
Eric Laurent81784c32012-11-19 14:55:58 -08007339
Eric Laurent10351942014-05-08 18:49:52 -07007340 // store input device and output device but do not forward output device to audio HAL.
7341 // Note that status is ignored by the caller for output device
7342 // (see AudioFlinger::setParameters()
7343 if (audio_is_output_devices(value)) {
7344 mOutDevice = value;
7345 status = BAD_VALUE;
7346 } else {
7347 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007348 if (value != AUDIO_DEVICE_NONE) {
7349 mPrevInDevice = value;
7350 }
Eric Laurent10351942014-05-08 18:49:52 -07007351 // disable AEC and NS if the device is a BT SCO headset supporting those
7352 // pre processings
7353 if (mTracks.size() > 0) {
7354 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7355 mAudioFlinger->btNrecIsOff();
7356 for (size_t i = 0; i < mTracks.size(); i++) {
7357 sp<RecordTrack> track = mTracks[i];
7358 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7359 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007360 }
7361 }
7362 }
Eric Laurent10351942014-05-08 18:49:52 -07007363 }
7364 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7365 mAudioSource != (audio_source_t)value) {
7366 // forward device change to effects that have requested to be
7367 // aware of attached audio device.
7368 for (size_t i = 0; i < mEffectChains.size(); i++) {
7369 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007370 }
Eric Laurent10351942014-05-08 18:49:52 -07007371 mAudioSource = (audio_source_t)value;
7372 }
Glenn Kastene198c362013-08-13 09:13:36 -07007373
Eric Laurent10351942014-05-08 18:49:52 -07007374 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007375 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007376 if (status == INVALID_OPERATION) {
7377 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007378 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007379 }
7380 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007381 if (status == BAD_VALUE) {
7382 uint32_t sRate;
7383 audio_channel_mask_t channelMask;
7384 audio_format_t format;
7385 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7386 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7387 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7388 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7389 status = NO_ERROR;
7390 }
Eric Laurent81784c32012-11-19 14:55:58 -08007391 }
Eric Laurent10351942014-05-08 18:49:52 -07007392 if (status == NO_ERROR) {
7393 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007394 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007395 }
7396 }
Eric Laurent81784c32012-11-19 14:55:58 -08007397 }
Eric Laurent10351942014-05-08 18:49:52 -07007398
Eric Laurent81784c32012-11-19 14:55:58 -08007399 return reconfig;
7400}
7401
7402String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7403{
Eric Laurent81784c32012-11-19 14:55:58 -08007404 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007405 if (initCheck() == NO_ERROR) {
7406 String8 out_s8;
7407 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7408 return out_s8;
7409 }
Eric Laurent81784c32012-11-19 14:55:58 -08007410 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007411 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007412}
7413
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007414void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007415 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7416
7417 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007418
7419 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007420 case AUDIO_INPUT_OPENED:
7421 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007422 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007423 desc->mChannelMask = mChannelMask;
7424 desc->mSamplingRate = mSampleRate;
7425 desc->mFormat = mFormat;
7426 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007427 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007428 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007429 break;
7430
Eric Laurent73e26b62015-04-27 16:55:58 -07007431 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007432 default:
7433 break;
7434 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007435 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007436}
7437
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007438void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007439{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007440 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7441 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007442 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007443 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007444 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007445 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7446 result = mInput->stream->getFrameSize(&mFrameSize);
7447 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7448 result = mInput->stream->getBufferSize(&mBufferSize);
7449 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007450 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007451 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007452 // 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 -07007453 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007454 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007455 // A larger value should allow more old data to be read after a track calls start(),
7456 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007457 //
7458 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007459 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007460 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007461 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007462 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007463
7464 // TODO optimize audio capture buffer sizes ...
7465 // Here we calculate the size of the sliding buffer used as a source
7466 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7467 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7468 // be better to have it derived from the pipe depth in the long term.
7469 // The current value is higher than necessary. However it should not add to latency.
7470
Glenn Kasten85948432013-08-19 12:09:05 -07007471 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007472 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7473 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7474 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007475
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007476 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7477 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007478}
7479
Glenn Kasten5f972c02014-01-13 09:59:31 -08007480uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007481{
7482 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007483 uint32_t result;
7484 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7485 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007486 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007487 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007488}
7489
Eric Laurent4c415062016-06-17 16:14:16 -07007490// hasAudioSession_l() must be called with ThreadBase::mLock held
7491uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007492{
Eric Laurent81784c32012-11-19 14:55:58 -08007493 uint32_t result = 0;
7494 if (getEffectChain_l(sessionId) != 0) {
7495 result = EFFECT_SESSION;
7496 }
7497
7498 for (size_t i = 0; i < mTracks.size(); ++i) {
7499 if (sessionId == mTracks[i]->sessionId()) {
7500 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007501 if (mTracks[i]->isFastTrack()) {
7502 result |= FAST_SESSION;
7503 }
Eric Laurent81784c32012-11-19 14:55:58 -08007504 break;
7505 }
7506 }
7507
7508 return result;
7509}
7510
Glenn Kastend848eb42016-03-08 13:42:11 -08007511KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007512{
Glenn Kastend848eb42016-03-08 13:42:11 -08007513 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007514 Mutex::Autolock _l(mLock);
7515 for (size_t j = 0; j < mTracks.size(); ++j) {
7516 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007517 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007518 if (ids.indexOfKey(sessionId) < 0) {
7519 ids.add(sessionId, true);
7520 }
7521 }
7522 return ids;
7523}
7524
7525AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7526{
7527 Mutex::Autolock _l(mLock);
7528 AudioStreamIn *input = mInput;
7529 mInput = NULL;
7530 return input;
7531}
7532
7533// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007534sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007535{
7536 if (mInput == NULL) {
7537 return NULL;
7538 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007539 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007540}
7541
7542status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7543{
7544 // only one chain per input thread
7545 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007546 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007547 return INVALID_OPERATION;
7548 }
7549 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007550 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007551 chain->setInBuffer(NULL);
7552 chain->setOutBuffer(NULL);
7553
7554 checkSuspendOnAddEffectChain_l(chain);
7555
Eric Laurent1b928682014-10-02 19:41:47 -07007556 // make sure enabled pre processing effects state is communicated to the HAL as we
7557 // just moved them to a new input stream.
7558 chain->syncHalEffectsState();
7559
Eric Laurent81784c32012-11-19 14:55:58 -08007560 mEffectChains.add(chain);
7561
7562 return NO_ERROR;
7563}
7564
7565size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7566{
7567 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7568 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007569 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007570 chain.get(), mEffectChains.size(), this);
7571 if (mEffectChains.size() == 1) {
7572 mEffectChains.removeAt(0);
7573 }
7574 return 0;
7575}
7576
Eric Laurent1c333e22014-05-20 10:48:17 -07007577status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7578 audio_patch_handle_t *handle)
7579{
7580 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007581
7582 // store new device and send to effects
7583 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007584 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007585 for (size_t i = 0; i < mEffectChains.size(); i++) {
7586 mEffectChains[i]->setDevice_l(mInDevice);
7587 }
7588
7589 // disable AEC and NS if the device is a BT SCO headset supporting those
7590 // pre processings
7591 if (mTracks.size() > 0) {
7592 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7593 mAudioFlinger->btNrecIsOff();
7594 for (size_t i = 0; i < mTracks.size(); i++) {
7595 sp<RecordTrack> track = mTracks[i];
7596 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7597 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7598 }
7599 }
7600
7601 // store new source and send to effects
7602 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7603 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007604 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007605 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007606 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007607 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007608
Eric Laurent054d9d32015-04-24 08:48:48 -07007609 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007610 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7611 status = hwDevice->createAudioPatch(patch->num_sources,
7612 patch->sources,
7613 patch->num_sinks,
7614 patch->sinks,
7615 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007616 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007617 char *address;
7618 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7619 address = audio_device_address_to_parameter(
7620 patch->sources[0].ext.device.type,
7621 patch->sources[0].ext.device.address);
7622 } else {
7623 address = (char *)calloc(1, 1);
7624 }
7625 AudioParameter param = AudioParameter(String8(address));
7626 free(address);
7627 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7628 (int)patch->sources[0].ext.device.type);
7629 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7630 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007631 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007632 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007633 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007634
Eric Laurente8726fe2015-06-26 09:39:24 -07007635 if (mInDevice != mPrevInDevice) {
7636 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7637 mPrevInDevice = mInDevice;
7638 }
Eric Laurent296fb132015-05-01 11:38:42 -07007639
Eric Laurent1c333e22014-05-20 10:48:17 -07007640 return status;
7641}
7642
7643status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7644{
7645 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007646
7647 mInDevice = AUDIO_DEVICE_NONE;
7648
Eric Laurent1c333e22014-05-20 10:48:17 -07007649 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007650 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7651 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007652 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007653 AudioParameter param;
7654 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007655 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007656 }
7657 return status;
7658}
7659
Eric Laurent83b88082014-06-20 18:31:16 -07007660void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7661{
7662 Mutex::Autolock _l(mLock);
7663 mTracks.add(record);
7664}
7665
7666void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7667{
7668 Mutex::Autolock _l(mLock);
7669 destroyTrack_l(record);
7670}
7671
7672void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7673{
7674 ThreadBase::getAudioPortConfig(config);
7675 config->role = AUDIO_PORT_ROLE_SINK;
7676 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7677 config->ext.mix.usecase.source = mAudioSource;
7678}
Eric Laurent1c333e22014-05-20 10:48:17 -07007679
Glenn Kasten63238ef2015-03-02 15:50:29 -08007680} // namespace android