blob: 7675a126f60d872895455283bf8a1d508bd7cece [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());
Andy Hungb54c8542016-09-21 12:55:15 -07001838 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1839 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1840 if (mPipeSink.get() != nullptr) {
1841 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1842 }
1843 if (output != nullptr) {
1844 dprintf(fd, " Hal stream dump:\n");
1845 (void)output->stream->dump(fd);
1846 }
Eric Laurent81784c32012-11-19 14:55:58 -08001847}
1848
1849// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001850
1851void AudioFlinger::PlaybackThread::onFirstRef()
1852{
Glenn Kastend7dca052015-03-05 16:05:54 -08001853 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001854}
1855
1856// ThreadBase virtuals
1857void AudioFlinger::PlaybackThread::preExit()
1858{
1859 ALOGV(" preExit()");
1860 // FIXME this is using hard-coded strings but in the future, this functionality will be
1861 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001862 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1863 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001864}
1865
1866// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1867sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1868 const sp<AudioFlinger::Client>& client,
1869 audio_stream_type_t streamType,
1870 uint32_t sampleRate,
1871 audio_format_t format,
1872 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001873 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001874 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001875 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001876 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001877 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001878 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001879 status_t *status)
1880{
Glenn Kasten74935e42013-12-19 08:56:45 -08001881 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001882 sp<Track> track;
1883 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001884 audio_output_flags_t outputFlags = mOutput->flags;
1885
1886 // special case for FAST flag considered OK if fast mixer is present
1887 if (hasFastMixer()) {
1888 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1889 }
1890
1891 // Check if requested flags are compatible with output stream flags
1892 if ((*flags & outputFlags) != *flags) {
1893 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1894 *flags, outputFlags);
1895 *flags = (audio_output_flags_t)(*flags & outputFlags);
1896 }
Eric Laurent81784c32012-11-19 14:55:58 -08001897
Eric Laurent81784c32012-11-19 14:55:58 -08001898 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001899 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001900 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001901 // PCM data
1902 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001903 // TODO: extract as a data library function that checks that a computationally
1904 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001905 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001906 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1907 (channelMask == AUDIO_CHANNEL_OUT_MONO
1908 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001909 // hardware sample rate
1910 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001911 // normal mixer has an associated fast mixer
1912 hasFastMixer() &&
1913 // there are sufficient fast track slots available
1914 (mFastTrackAvailMask != 0)
1915 // FIXME test that MixerThread for this fast track has a capable output HAL
1916 // FIXME add a permission test also?
1917 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001918 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1919 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001920 // read the fast track multiplier property the first time it is needed
1921 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1922 if (ok != 0) {
1923 ALOGE("%s pthread_once failed: %d", __func__, ok);
1924 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001925 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001926 }
Eric Laurent4c415062016-06-17 16:14:16 -07001927
1928 // check compatibility with audio effects.
1929 { // scope for mLock
1930 Mutex::Autolock _l(mLock);
1931 // do not accept RAW flag if post processing are present. Note that post processing on
1932 // a fast mixer are necessarily hardware
1933 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
1934 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001935 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001936 "AUDIO_OUTPUT_FLAG_RAW denied: post processing effect present");
1937 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1938 }
1939 // Do not accept FAST flag if software global effects are present
1940 chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
1941 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001942 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001943 "AUDIO_OUTPUT_FLAG_RAW denied: global effect present");
1944 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1945 if (chain->hasSoftwareEffect()) {
1946 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software global effect present");
1947 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1948 }
1949 }
1950 // Do not accept FAST flag if the session has software effects
1951 chain = getEffectChain_l(sessionId);
1952 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001953 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001954 "AUDIO_OUTPUT_FLAG_RAW denied: effect present on session");
1955 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1956 if (chain->hasSoftwareEffect()) {
1957 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software effect present on session");
1958 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1959 }
1960 }
1961 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001962 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001963 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1964 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001965 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001966 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1967 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001968 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001969 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001970 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001971 audio_is_linear_pcm(format),
1972 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001973 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001974 }
1975 }
1976 // For normal PCM streaming tracks, update minimum frame count.
1977 // For compatibility with AudioTrack calculation, buffer depth is forced
1978 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1979 // This is probably too conservative, but legacy application code may depend on it.
1980 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001981 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001982 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001983 // this must match AudioTrack.cpp calculateMinFrameCount().
1984 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001985 uint32_t latencyMs = 0;
1986 lStatus = mOutput->stream->getLatency(&latencyMs);
1987 if (lStatus != OK) {
1988 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1989 goto Exit;
1990 }
Eric Laurent81784c32012-11-19 14:55:58 -08001991 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1992 if (minBufCount < 2) {
1993 minBufCount = 2;
1994 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001995 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1996 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001997 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001998 minBufCount * sourceFramesNeededWithTimestretch(
1999 sampleRate, mNormalFrameCount,
2000 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08002001 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08002002 frameCount = minFrameCount;
2003 }
Eric Laurent81784c32012-11-19 14:55:58 -08002004 }
Glenn Kasten74935e42013-12-19 08:56:45 -08002005 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002006
Glenn Kastenc3df8382014-03-13 15:05:25 -07002007 switch (mType) {
2008
2009 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002010 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002011 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002012 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2013 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002014 sampleRate, format, channelMask, mOutput, mFormat);
2015 lStatus = BAD_VALUE;
2016 goto Exit;
2017 }
2018 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002019 break;
2020
2021 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002022 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002023 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2024 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002025 sampleRate, format, channelMask, mOutput, mFormat);
2026 lStatus = BAD_VALUE;
2027 goto Exit;
2028 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002029 break;
2030
2031 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002032 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002033 ALOGE("createTrack_l() Bad parameter: format %#x \""
2034 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002035 format, mOutput, mFormat);
2036 lStatus = BAD_VALUE;
2037 goto Exit;
2038 }
Andy Hungcd044842014-08-07 11:04:34 -07002039 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002040 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2041 lStatus = BAD_VALUE;
2042 goto Exit;
2043 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002044 break;
2045
Eric Laurent81784c32012-11-19 14:55:58 -08002046 }
2047
2048 lStatus = initCheck();
2049 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002050 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002051 goto Exit;
2052 }
2053
2054 { // scope for mLock
2055 Mutex::Autolock _l(mLock);
2056
2057 // all tracks in same audio session must share the same routing strategy otherwise
2058 // conflicts will happen when tracks are moved from one output to another by audio policy
2059 // manager
2060 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2061 for (size_t i = 0; i < mTracks.size(); ++i) {
2062 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002063 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002064 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2065 if (sessionId == t->sessionId() && strategy != actual) {
2066 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2067 strategy, actual);
2068 lStatus = BAD_VALUE;
2069 goto Exit;
2070 }
2071 }
2072 }
2073
Glenn Kastend79072e2016-01-06 08:41:20 -08002074 track = new Track(this, client, streamType, sampleRate, format,
2075 channelMask, frameCount, NULL, sharedBuffer,
2076 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002077
Glenn Kasten03003332013-08-06 15:40:54 -07002078 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2079 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002080 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002081 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002082 goto Exit;
2083 }
2084 mTracks.add(track);
2085
2086 sp<EffectChain> chain = getEffectChain_l(sessionId);
2087 if (chain != 0) {
2088 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2089 track->setMainBuffer(chain->inBuffer());
2090 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2091 chain->incTrackCnt();
2092 }
2093
Eric Laurent05067782016-06-01 18:27:28 -07002094 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002095 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2096 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2097 // so ask activity manager to do this on our behalf
2098 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2099 }
2100 }
2101
2102 lStatus = NO_ERROR;
2103
2104Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002105 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002106 return track;
2107}
2108
2109uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2110{
2111 return latency;
2112}
2113
2114uint32_t AudioFlinger::PlaybackThread::latency() const
2115{
2116 Mutex::Autolock _l(mLock);
2117 return latency_l();
2118}
2119uint32_t AudioFlinger::PlaybackThread::latency_l() const
2120{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002121 uint32_t latency;
2122 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2123 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002124 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002125 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002126}
2127
2128void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2129{
2130 Mutex::Autolock _l(mLock);
2131 // Don't apply master volume in SW if our HAL can do it for us.
2132 if (mOutput && mOutput->audioHwDev &&
2133 mOutput->audioHwDev->canSetMasterVolume()) {
2134 mMasterVolume = 1.0;
2135 } else {
2136 mMasterVolume = value;
2137 }
2138}
2139
2140void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2141{
2142 Mutex::Autolock _l(mLock);
2143 // Don't apply master mute in SW if our HAL can do it for us.
2144 if (mOutput && mOutput->audioHwDev &&
2145 mOutput->audioHwDev->canSetMasterMute()) {
2146 mMasterMute = false;
2147 } else {
2148 mMasterMute = muted;
2149 }
2150}
2151
2152void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2153{
2154 Mutex::Autolock _l(mLock);
2155 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002156 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002157}
2158
2159void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2160{
2161 Mutex::Autolock _l(mLock);
2162 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002163 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002164}
2165
2166float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2167{
2168 Mutex::Autolock _l(mLock);
2169 return mStreamTypes[stream].volume;
2170}
2171
2172// addTrack_l() must be called with ThreadBase::mLock held
2173status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2174{
2175 status_t status = ALREADY_EXISTS;
2176
Eric Laurent81784c32012-11-19 14:55:58 -08002177 if (mActiveTracks.indexOf(track) < 0) {
2178 // the track is newly added, make sure it fills up all its
2179 // buffers before playing. This is to ensure the client will
2180 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002181 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002182 TrackBase::track_state state = track->mState;
2183 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002184 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002185 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002186 mLock.lock();
2187 // abort track was stopped/paused while we released the lock
2188 if (state != track->mState) {
2189 if (status == NO_ERROR) {
2190 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002191 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002192 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002193 mLock.lock();
2194 }
2195 return INVALID_OPERATION;
2196 }
2197 // abort if start is rejected by audio policy manager
2198 if (status != NO_ERROR) {
2199 return PERMISSION_DENIED;
2200 }
2201#ifdef ADD_BATTERY_DATA
2202 // to track the speaker usage
2203 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2204#endif
2205 }
2206
Eric Laurent51716182016-02-29 18:00:56 -08002207 // set retry count for buffer fill
2208 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002209 if (track->isStopping_1()) {
2210 track->mRetryCount = kMaxTrackStopRetriesOffload;
2211 } else {
2212 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2213 }
2214 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002215 } else {
2216 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002217 track->mFillingUpStatus =
2218 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002219 }
2220
Eric Laurent81784c32012-11-19 14:55:58 -08002221 track->mResetDone = false;
2222 track->mPresentationCompleteFrames = 0;
2223 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002224 mWakeLockUids.add(track->uid());
2225 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002226 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002227 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2228 if (chain != 0) {
2229 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2230 track->sessionId());
2231 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002232 }
2233
2234 status = NO_ERROR;
2235 }
2236
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002237 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002238 return status;
2239}
2240
Eric Laurentbfb1b832013-01-07 09:53:42 -08002241bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002242{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002243 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002244 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002245 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2246 track->mState = TrackBase::STOPPED;
2247 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002248 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002249 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002250 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002251 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002252
2253 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002254}
2255
2256void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2257{
2258 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2259 mTracks.remove(track);
2260 deleteTrackName_l(track->name());
2261 // redundant as track is about to be destroyed, for dumpsys only
2262 track->mName = -1;
2263 if (track->isFastTrack()) {
2264 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002265 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002266 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2267 mFastTrackAvailMask |= 1 << index;
2268 // redundant as track is about to be destroyed, for dumpsys only
2269 track->mFastIndex = -1;
2270 }
2271 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2272 if (chain != 0) {
2273 chain->decTrackCnt();
2274 }
2275}
2276
Eric Laurentede6c3b2013-09-19 14:37:46 -07002277void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278{
2279 // Thread could be blocked waiting for async
2280 // so signal it to handle state changes immediately
2281 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2282 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2283 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002284 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002285}
2286
Eric Laurent81784c32012-11-19 14:55:58 -08002287String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2288{
Eric Laurent81784c32012-11-19 14:55:58 -08002289 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002290 String8 out_s8;
2291 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2292 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002293 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002294 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002295}
2296
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002297void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002298 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2299 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002300
Eric Laurent73e26b62015-04-27 16:55:58 -07002301 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002302
2303 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002304 case AUDIO_OUTPUT_OPENED:
2305 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002306 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002307 desc->mChannelMask = mChannelMask;
2308 desc->mSamplingRate = mSampleRate;
2309 desc->mFormat = mFormat;
2310 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002311 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002312 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002313 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002314 break;
2315
Eric Laurent73e26b62015-04-27 16:55:58 -07002316 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002317 default:
2318 break;
2319 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002320 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002321}
2322
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002323void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002324{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002325 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002326}
2327
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002328void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002329{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002330 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002331}
2332
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002333void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002334{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002335 mCallbackThread->setAsyncError();
2336}
2337
Eric Laurent3b4529e2013-09-05 18:09:19 -07002338void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002339{
2340 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002341 // reject out of sequence requests
2342 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2343 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002344 mWaitWorkCV.signal();
2345 }
2346}
2347
Eric Laurent3b4529e2013-09-05 18:09:19 -07002348void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002349{
2350 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002351 // reject out of sequence requests
2352 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2353 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002354 mWaitWorkCV.signal();
2355 }
2356}
2357
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002358void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002359{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002360 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002361 mSampleRate = mOutput->getSampleRate();
2362 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002363 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002364 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002365 }
Andy Hung9a592762014-07-21 21:56:01 -07002366 if ((mType == MIXER || mType == DUPLICATING)
2367 && !isValidPcmSinkChannelMask(mChannelMask)) {
2368 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2369 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002370 }
Andy Hunge5412692014-05-16 11:25:07 -07002371 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002372
2373 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002374 status_t result = mOutput->stream->getFormat(&mHALFormat);
2375 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002376 // Get format from the shim, which will be different than the HAL format
2377 // if playing compressed audio over HDMI passthrough.
2378 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002379 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002380 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002381 }
Andy Hung6146c082014-03-18 11:56:15 -07002382 if ((mType == MIXER || mType == DUPLICATING)
2383 && !isValidPcmSinkFormat(mFormat)) {
2384 LOG_FATAL("HAL format %#x not supported for mixed output",
2385 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002386 }
Phil Burk062e67a2015-02-11 13:40:50 -08002387 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002388 result = mOutput->stream->getBufferSize(&mBufferSize);
2389 LOG_ALWAYS_FATAL_IF(result != OK,
2390 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002391 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002392 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002393 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002394 mFrameCount);
2395 }
2396
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002397 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2398 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002399 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002400 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002401 }
2402 }
2403
Eric Laurentd1f69b02014-12-15 14:33:13 -08002404 mHwSupportsPause = false;
2405 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002406 bool supportsPause = false, supportsResume = false;
2407 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2408 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002409 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002410 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002411 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002412 } else if (supportsResume) {
2413 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002414 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002415 }
2416 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002417 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2418 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2419 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002420
Andy Hungfbfc3952015-01-15 13:33:51 -08002421 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2422 // For best precision, we use float instead of the associated output
2423 // device format (typically PCM 16 bit).
2424
2425 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2426 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2427 mBufferSize = mFrameSize * mFrameCount;
2428
2429 // TODO: We currently use the associated output device channel mask and sample rate.
2430 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2431 // (if a valid mask) to avoid premature downmix.
2432 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2433 // instead of the output device sample rate to avoid loss of high frequency information.
2434 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2435 }
2436
Andy Hung09a50072014-02-27 14:30:47 -08002437 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002438 double multiplier = 1.0;
2439 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2440 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002441 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2442 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002443
Eric Laurent81784c32012-11-19 14:55:58 -08002444 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2445 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2446 maxNormalFrameCount = maxNormalFrameCount & ~15;
2447 if (maxNormalFrameCount < minNormalFrameCount) {
2448 maxNormalFrameCount = minNormalFrameCount;
2449 }
2450 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2451 if (multiplier <= 1.0) {
2452 multiplier = 1.0;
2453 } else if (multiplier <= 2.0) {
2454 if (2 * mFrameCount <= maxNormalFrameCount) {
2455 multiplier = 2.0;
2456 } else {
2457 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2458 }
2459 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002460 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002461 }
2462 }
2463 mNormalFrameCount = multiplier * mFrameCount;
2464 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002465 if (mType == MIXER || mType == DUPLICATING) {
2466 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2467 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002468 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002469 mNormalFrameCount);
2470
Andy Hung08fb1742015-05-31 23:22:10 -07002471 // Check if we want to throttle the processing to no more than 2x normal rate
2472 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002473 mThreadThrottleTimeMs = 0;
2474 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002475 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2476
Andy Hung010a1a12014-03-13 13:57:33 -07002477 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2478 // Originally this was int16_t[] array, need to remove legacy implications.
2479 free(mSinkBuffer);
2480 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002481 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2482 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2483 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002484 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002485
Andy Hung69aed5f2014-02-25 17:24:40 -08002486 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2487 // drives the output.
2488 free(mMixerBuffer);
2489 mMixerBuffer = NULL;
2490 if (mMixerBufferEnabled) {
2491 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2492 mMixerBufferSize = mNormalFrameCount * mChannelCount
2493 * audio_bytes_per_sample(mMixerBufferFormat);
2494 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2495 }
Andy Hung98ef9782014-03-04 14:46:50 -08002496 free(mEffectBuffer);
2497 mEffectBuffer = NULL;
2498 if (mEffectBufferEnabled) {
2499 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2500 mEffectBufferSize = mNormalFrameCount * mChannelCount
2501 * audio_bytes_per_sample(mEffectBufferFormat);
2502 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2503 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002504
Eric Laurent81784c32012-11-19 14:55:58 -08002505 // force reconfiguration of effect chains and engines to take new buffer size and audio
2506 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002507 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002508 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2509 // matter.
2510 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2511 Vector< sp<EffectChain> > effectChains = mEffectChains;
2512 for (size_t i = 0; i < effectChains.size(); i ++) {
2513 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2514 }
2515}
2516
2517
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002518status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002519{
2520 if (halFrames == NULL || dspFrames == NULL) {
2521 return BAD_VALUE;
2522 }
2523 Mutex::Autolock _l(mLock);
2524 if (initCheck() != NO_ERROR) {
2525 return INVALID_OPERATION;
2526 }
Andy Hung818e7a32016-02-16 18:08:07 -08002527 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002528 *halFrames = framesWritten;
2529
2530 if (isSuspended()) {
2531 // return an estimation of rendered frames when the output is suspended
2532 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002533 *dspFrames = (uint32_t)
2534 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002535 return NO_ERROR;
2536 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002537 status_t status;
2538 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002539 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002540 *dspFrames = (size_t)frames;
2541 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002542 }
2543}
2544
Eric Laurent4c415062016-06-17 16:14:16 -07002545// hasAudioSession_l() must be called with ThreadBase::mLock held
2546uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002547{
Eric Laurent81784c32012-11-19 14:55:58 -08002548 uint32_t result = 0;
2549 if (getEffectChain_l(sessionId) != 0) {
2550 result = EFFECT_SESSION;
2551 }
2552
2553 for (size_t i = 0; i < mTracks.size(); ++i) {
2554 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002555 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002556 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002557 if (track->isFastTrack()) {
2558 result |= FAST_SESSION;
2559 }
Eric Laurent81784c32012-11-19 14:55:58 -08002560 break;
2561 }
2562 }
2563
2564 return result;
2565}
2566
Glenn Kastend848eb42016-03-08 13:42:11 -08002567uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002568{
2569 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2570 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2571 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2572 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2573 }
2574 for (size_t i = 0; i < mTracks.size(); i++) {
2575 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002576 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002577 return AudioSystem::getStrategyForStream(track->streamType());
2578 }
2579 }
2580 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2581}
2582
2583
Phil Burk062e67a2015-02-11 13:40:50 -08002584AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002585{
2586 Mutex::Autolock _l(mLock);
2587 return mOutput;
2588}
2589
Phil Burk062e67a2015-02-11 13:40:50 -08002590AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002591{
2592 Mutex::Autolock _l(mLock);
2593 AudioStreamOut *output = mOutput;
2594 mOutput = NULL;
2595 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2596 // must push a NULL and wait for ack
2597 mOutputSink.clear();
2598 mPipeSink.clear();
2599 mNormalSink.clear();
2600 return output;
2601}
2602
2603// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002604sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002605{
2606 if (mOutput == NULL) {
2607 return NULL;
2608 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002609 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002610}
2611
2612uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2613{
2614 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2615}
2616
2617status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2618{
2619 if (!isValidSyncEvent(event)) {
2620 return BAD_VALUE;
2621 }
2622
2623 Mutex::Autolock _l(mLock);
2624
2625 for (size_t i = 0; i < mTracks.size(); ++i) {
2626 sp<Track> track = mTracks[i];
2627 if (event->triggerSession() == track->sessionId()) {
2628 (void) track->setSyncEvent(event);
2629 return NO_ERROR;
2630 }
2631 }
2632
2633 return NAME_NOT_FOUND;
2634}
2635
2636bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2637{
2638 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2639}
2640
2641void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2642 const Vector< sp<Track> >& tracksToRemove)
2643{
2644 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002645 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002646 for (size_t i = 0 ; i < count ; i++) {
2647 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002648 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002649 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002650 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651#ifdef ADD_BATTERY_DATA
2652 // to track the speaker usage
2653 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2654#endif
2655 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002656 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002657 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 }
Eric Laurent81784c32012-11-19 14:55:58 -08002659 }
2660 }
2661 }
Eric Laurent81784c32012-11-19 14:55:58 -08002662}
2663
2664void AudioFlinger::PlaybackThread::checkSilentMode_l()
2665{
2666 if (!mMasterMute) {
2667 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002668 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2669 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2670 return;
2671 }
Eric Laurent81784c32012-11-19 14:55:58 -08002672 if (property_get("ro.audio.silent", value, "0") > 0) {
2673 char *endptr;
2674 unsigned long ul = strtoul(value, &endptr, 0);
2675 if (*endptr == '\0' && ul != 0) {
2676 ALOGD("Silence is golden");
2677 // The setprop command will not allow a property to be changed after
2678 // the first time it is set, so we don't have to worry about un-muting.
2679 setMasterMute_l(true);
2680 }
2681 }
2682 }
2683}
2684
2685// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002687{
Eric Laurent81784c32012-11-19 14:55:58 -08002688 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002689 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002690 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002691
2692 // If an NBAIO sink is present, use it to write the normal mixer's submix
2693 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002694
Andy Hung010a1a12014-03-13 13:57:33 -07002695 const size_t count = mBytesRemaining / mFrameSize;
2696
Simon Wilson2d590962012-11-29 15:18:50 -08002697 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002698 // update the setpoint when AudioFlinger::mScreenState changes
2699 uint32_t screenState = AudioFlinger::mScreenState;
2700 if (screenState != mScreenState) {
2701 mScreenState = screenState;
2702 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2703 if (pipe != NULL) {
2704 pipe->setAvgFrames((mScreenState & 1) ?
2705 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2706 }
2707 }
Andy Hung010a1a12014-03-13 13:57:33 -07002708 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002709 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002710 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002711 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002712 } else {
2713 bytesWritten = framesWritten;
2714 }
2715 // otherwise use the HAL / AudioStreamOut directly
2716 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002717 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002718
Eric Laurentbfb1b832013-01-07 09:53:42 -08002719 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002720 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2721 mWriteAckSequence += 2;
2722 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002723 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002724 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002725 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002726 // FIXME We should have an implementation of timestamps for direct output threads.
2727 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002728 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002729
Eric Laurentbfb1b832013-01-07 09:53:42 -08002730 if (mUseAsyncWrite &&
2731 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2732 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002733 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002734 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002735 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002736 }
Eric Laurent81784c32012-11-19 14:55:58 -08002737 }
2738
Eric Laurent81784c32012-11-19 14:55:58 -08002739 mNumWrites++;
2740 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002741 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002742 return bytesWritten;
2743}
2744
2745void AudioFlinger::PlaybackThread::threadLoop_drain()
2746{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002747 bool supportsDrain = false;
2748 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002749 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2750 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002751 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2752 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002753 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002754 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002755 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002756 status_t result = mOutput->stream->drain(
Eric Laurentbfb1b832013-01-07 09:53:42 -08002757 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2758 : AUDIO_DRAIN_ALL);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002759 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002760 }
2761}
2762
2763void AudioFlinger::PlaybackThread::threadLoop_exit()
2764{
Eric Laurent275e8e92014-11-30 15:14:47 -08002765 {
2766 Mutex::Autolock _l(mLock);
2767 for (size_t i = 0; i < mTracks.size(); i++) {
2768 sp<Track> track = mTracks[i];
2769 track->invalidate();
2770 }
2771 }
Eric Laurent81784c32012-11-19 14:55:58 -08002772}
2773
2774/*
2775The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002776 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002777 - mActiveSleepTimeUs from activeSleepTimeUs()
2778 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002779 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2780 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002781 - maxPeriod from frame count and sample rate (MIXER only)
2782
2783The parameters that affect these derived values are:
2784 - frame count
2785 - frame size
2786 - sample rate
2787 - device type: A2DP or not
2788 - device latency
2789 - format: PCM or not
2790 - active sleep time
2791 - idle sleep time
2792*/
2793
2794void AudioFlinger::PlaybackThread::cacheParameters_l()
2795{
Andy Hung25c2dac2014-02-27 14:56:00 -08002796 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002797 mActiveSleepTimeUs = activeSleepTimeUs();
2798 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002799
2800 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2801 // truncating audio when going to standby.
2802 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2803 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2804 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2805 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2806 }
2807 }
Eric Laurent81784c32012-11-19 14:55:58 -08002808}
2809
Eric Laurent13084622016-05-17 10:51:49 -07002810bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002811{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002812 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002813 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002814 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002815 size_t size = mTracks.size();
2816 for (size_t i = 0; i < size; i++) {
2817 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002818 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002819 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002820 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002821 }
2822 }
Eric Laurent13084622016-05-17 10:51:49 -07002823 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002824}
2825
Haynes Mathew George05317d22016-05-03 16:34:26 -07002826void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2827{
2828 Mutex::Autolock _l(mLock);
2829 invalidateTracks_l(streamType);
2830}
2831
Eric Laurent81784c32012-11-19 14:55:58 -08002832status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2833{
Glenn Kastend848eb42016-03-08 13:42:11 -08002834 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002835 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2836 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002837 bool ownsBuffer = false;
2838
2839 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002840 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002841 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002842 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002843 if (mType != DIRECT) {
2844 size_t numSamples = mNormalFrameCount * mChannelCount;
2845 buffer = new int16_t[numSamples];
2846 memset(buffer, 0, numSamples * sizeof(int16_t));
2847 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2848 ownsBuffer = true;
2849 }
2850
2851 // Attach all tracks with same session ID to this chain.
2852 for (size_t i = 0; i < mTracks.size(); ++i) {
2853 sp<Track> track = mTracks[i];
2854 if (session == track->sessionId()) {
2855 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2856 buffer);
2857 track->setMainBuffer(buffer);
2858 chain->incTrackCnt();
2859 }
2860 }
2861
2862 // indicate all active tracks in the chain
2863 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2864 sp<Track> track = mActiveTracks[i].promote();
2865 if (track == 0) {
2866 continue;
2867 }
2868 if (session == track->sessionId()) {
2869 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2870 chain->incActiveTrackCnt();
2871 }
2872 }
2873 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002874 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002875 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002876 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2877 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002878 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002879 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002880 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2881 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002882 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002883 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002884 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002885 // Effect chain for other sessions are inserted at beginning of effect
2886 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002887 // sessions is not important.
2888 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2889 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2890 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002891 size_t size = mEffectChains.size();
2892 size_t i = 0;
2893 for (i = 0; i < size; i++) {
2894 if (mEffectChains[i]->sessionId() < session) {
2895 break;
2896 }
2897 }
2898 mEffectChains.insertAt(chain, i);
2899 checkSuspendOnAddEffectChain_l(chain);
2900
2901 return NO_ERROR;
2902}
2903
2904size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2905{
Glenn Kastend848eb42016-03-08 13:42:11 -08002906 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002907
2908 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2909
2910 for (size_t i = 0; i < mEffectChains.size(); i++) {
2911 if (chain == mEffectChains[i]) {
2912 mEffectChains.removeAt(i);
2913 // detach all active tracks from the chain
2914 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2915 sp<Track> track = mActiveTracks[i].promote();
2916 if (track == 0) {
2917 continue;
2918 }
2919 if (session == track->sessionId()) {
2920 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2921 chain.get(), session);
2922 chain->decActiveTrackCnt();
2923 }
2924 }
2925
2926 // detach all tracks with same session ID from this chain
2927 for (size_t i = 0; i < mTracks.size(); ++i) {
2928 sp<Track> track = mTracks[i];
2929 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002930 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002931 chain->decTrackCnt();
2932 }
2933 }
2934 break;
2935 }
2936 }
2937 return mEffectChains.size();
2938}
2939
2940status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002941 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002942{
2943 Mutex::Autolock _l(mLock);
2944 return attachAuxEffect_l(track, EffectId);
2945}
2946
2947status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002948 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002949{
2950 status_t status = NO_ERROR;
2951
2952 if (EffectId == 0) {
2953 track->setAuxBuffer(0, NULL);
2954 } else {
2955 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2956 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2957 if (effect != 0) {
2958 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2959 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2960 } else {
2961 status = INVALID_OPERATION;
2962 }
2963 } else {
2964 status = BAD_VALUE;
2965 }
2966 }
2967 return status;
2968}
2969
2970void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2971{
2972 for (size_t i = 0; i < mTracks.size(); ++i) {
2973 sp<Track> track = mTracks[i];
2974 if (track->auxEffectId() == effectId) {
2975 attachAuxEffect_l(track, 0);
2976 }
2977 }
2978}
2979
2980bool AudioFlinger::PlaybackThread::threadLoop()
2981{
2982 Vector< sp<Track> > tracksToRemove;
2983
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002984 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002985 nsecs_t lastWriteFinished = -1; // time last server write completed
2986 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002987
2988 // MIXER
2989 nsecs_t lastWarning = 0;
2990
2991 // DUPLICATING
2992 // FIXME could this be made local to while loop?
2993 writeFrames = 0;
2994
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002995 int lastGeneration = 0;
2996
Eric Laurent81784c32012-11-19 14:55:58 -08002997 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002998 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002999
3000 if (mType == MIXER) {
3001 sleepTimeShift = 0;
3002 }
3003
3004 CpuStats cpuStats;
3005 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3006
3007 acquireWakeLock();
3008
Glenn Kasten9e58b552013-01-18 15:09:48 -08003009 // mNBLogWriter->log can only be called while thread mutex mLock is held.
3010 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3011 // and then that string will be logged at the next convenient opportunity.
3012 const char *logString = NULL;
3013
Eric Laurent664539d2013-09-23 18:24:31 -07003014 checkSilentMode_l();
3015
Eric Laurent81784c32012-11-19 14:55:58 -08003016 while (!exitPending())
3017 {
3018 cpuStats.sample(myName);
3019
3020 Vector< sp<EffectChain> > effectChains;
3021
Eric Laurent81784c32012-11-19 14:55:58 -08003022 { // scope for mLock
3023
3024 Mutex::Autolock _l(mLock);
3025
Eric Laurent021cf962014-05-13 10:18:14 -07003026 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003027
Glenn Kasten9e58b552013-01-18 15:09:48 -08003028 if (logString != NULL) {
3029 mNBLogWriter->logTimestamp();
3030 mNBLogWriter->log(logString);
3031 logString = NULL;
3032 }
3033
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003034 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003035 // and associate with the sink frames written out. We need
3036 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003037 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003038 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003039 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003040 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003041 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003042 ExtendedTimestamp timestamp; // use private copy to fetch
3043 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003044
3045 // We keep track of the last valid kernel position in case we are in underrun
3046 // and the normal mixer period is the same as the fast mixer period, or there
3047 // is some error from the HAL.
3048 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3049 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3050 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3051 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3052 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3053
3054 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3055 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3056 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3057 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003058 }
3059
3060 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3061 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003062 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003063 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003064 }
3065
Andy Hung818e7a32016-02-16 18:08:07 -08003066 // copy over kernel info
3067 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003068 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3069 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003070 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3071 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003072 }
3073 // mFramesWritten for non-offloaded tracks are contiguous
3074 // even after standby() is called. This is useful for the track frame
3075 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003076 bool serverLocationUpdate = false;
3077 if (mFramesWritten != lastFramesWritten) {
3078 serverLocationUpdate = true;
3079 lastFramesWritten = mFramesWritten;
3080 }
3081 // Only update timestamps if there is a meaningful change.
3082 // Either the kernel timestamp must be valid or we have written something.
3083 if (kernelLocationUpdate || serverLocationUpdate) {
3084 if (serverLocationUpdate) {
3085 // use the time before we called the HAL write - it is a bit more accurate
3086 // to when the server last read data than the current time here.
3087 //
3088 // If we haven't written anything, mLastWriteTime will be -1
3089 // and we use systemTime().
3090 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3091 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3092 ? systemTime() : mLastWriteTime;
3093 }
3094 const size_t size = mActiveTracks.size();
3095 for (size_t i = 0; i < size; ++i) {
3096 sp<Track> t = mActiveTracks[i].promote();
3097 if (t != 0 && !t->isFastTrack()) {
3098 t->updateTrackFrameInfo(
3099 t->mAudioTrackServerProxy->framesReleased(),
3100 mFramesWritten,
3101 mTimestamp);
3102 }
Andy Hunge10393e2015-06-12 13:59:33 -07003103 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003104 }
3105
Eric Laurent81784c32012-11-19 14:55:58 -08003106 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107 if (mSignalPending) {
3108 // A signal was raised while we were unlocked
3109 mSignalPending = false;
3110 } else if (waitingAsyncCallback_l()) {
3111 if (exitPending()) {
3112 break;
3113 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003114 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003115 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003116 releaseWakeLock_l();
3117 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07003118 mWakeLockUids.clear();
3119 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07003120 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003121 ALOGV("wait async completion");
3122 mWaitWorkCV.wait(mLock);
3123 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003124 if (released) {
3125 acquireWakeLock_l();
3126 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003127 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3128 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003129
3130 continue;
3131 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003132 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003133 isSuspended()) {
3134 // put audio hardware into standby after short delay
3135 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003136
3137 threadLoop_standby();
3138
3139 mStandby = true;
3140 }
3141
3142 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3143 // we're about to wait, flush the binder command buffer
3144 IPCThreadState::self()->flushCommands();
3145
3146 clearOutputTracks();
3147
3148 if (exitPending()) {
3149 break;
3150 }
3151
3152 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003153 mWakeLockUids.clear();
3154 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003155 // wait until we have something to do...
3156 ALOGV("%s going to sleep", myName.string());
3157 mWaitWorkCV.wait(mLock);
3158 ALOGV("%s waking up", myName.string());
3159 acquireWakeLock_l();
3160
3161 mMixerStatus = MIXER_IDLE;
3162 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3163 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003165 checkSilentMode_l();
3166
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003167 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3168 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003169 if (mType == MIXER) {
3170 sleepTimeShift = 0;
3171 }
3172
3173 continue;
3174 }
3175 }
Eric Laurent81784c32012-11-19 14:55:58 -08003176 // mMixerStatusIgnoringFastTracks is also updated internally
3177 mMixerStatus = prepareTracks_l(&tracksToRemove);
3178
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003179 // compare with previously applied list
3180 if (lastGeneration != mActiveTracksGeneration) {
3181 // update wakelock
3182 updateWakeLockUids_l(mWakeLockUids);
3183 lastGeneration = mActiveTracksGeneration;
3184 }
3185
Eric Laurent81784c32012-11-19 14:55:58 -08003186 // prevent any changes in effect chain list and in each effect chain
3187 // during mixing and effect process as the audio buffers could be deleted
3188 // or modified if an effect is created or deleted
3189 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003190 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003191
Eric Laurentbfb1b832013-01-07 09:53:42 -08003192 if (mBytesRemaining == 0) {
3193 mCurrentWriteLength = 0;
3194 if (mMixerStatus == MIXER_TRACKS_READY) {
3195 // threadLoop_mix() sets mCurrentWriteLength
3196 threadLoop_mix();
3197 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3198 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003199 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003200 // must be written to HAL
3201 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003202 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003203 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003204 }
3205 }
Andy Hung98ef9782014-03-04 14:46:50 -08003206 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003207 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003208 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3209 // or mSinkBuffer (if there are no effects).
3210 //
3211 // This is done pre-effects computation; if effects change to
3212 // support higher precision, this needs to move.
3213 //
3214 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003215 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003216 if (mMixerBufferValid) {
3217 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3218 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3219
Andy Hung2ddee192015-12-18 17:34:44 -08003220 // mono blend occurs for mixer threads only (not direct or offloaded)
3221 // and is handled here if we're going directly to the sink.
3222 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003223 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3224 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003225 }
3226
Andy Hung98ef9782014-03-04 14:46:50 -08003227 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3228 mNormalFrameCount * mChannelCount);
3229 }
3230
Eric Laurentbfb1b832013-01-07 09:53:42 -08003231 mBytesRemaining = mCurrentWriteLength;
3232 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003233 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3234 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3235 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3236 mBytesWritten += mBytesRemaining;
3237 mFramesWritten += framesRemaining;
3238 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003239 mBytesRemaining = 0;
3240 }
Eric Laurent81784c32012-11-19 14:55:58 -08003241
Eric Laurentbfb1b832013-01-07 09:53:42 -08003242 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003243 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003244 for (size_t i = 0; i < effectChains.size(); i ++) {
3245 effectChains[i]->process_l();
3246 }
Eric Laurent81784c32012-11-19 14:55:58 -08003247 }
3248 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003249 // Process effect chains for offloaded thread even if no audio
3250 // was read from audio track: process only updates effect state
3251 // and thus does have to be synchronized with audio writes but may have
3252 // to be called while waiting for async write callback
3253 if (mType == OFFLOAD) {
3254 for (size_t i = 0; i < effectChains.size(); i ++) {
3255 effectChains[i]->process_l();
3256 }
3257 }
Eric Laurent81784c32012-11-19 14:55:58 -08003258
Andy Hung98ef9782014-03-04 14:46:50 -08003259 // Only if the Effects buffer is enabled and there is data in the
3260 // Effects buffer (buffer valid), we need to
3261 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003262 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003263 if (mEffectBufferValid) {
3264 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003265
3266 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003267 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3268 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003269 }
3270
Andy Hung98ef9782014-03-04 14:46:50 -08003271 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3272 mNormalFrameCount * mChannelCount);
3273 }
3274
Eric Laurent81784c32012-11-19 14:55:58 -08003275 // enable changes in effect chain
3276 unlockEffectChains(effectChains);
3277
Eric Laurentbfb1b832013-01-07 09:53:42 -08003278 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003279 // mSleepTimeUs == 0 means we must write to audio hardware
3280 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003281 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003282 // We save lastWriteFinished here, as previousLastWriteFinished,
3283 // for throttling. On thread start, previousLastWriteFinished will be
3284 // set to -1, which properly results in no throttling after the first write.
3285 nsecs_t previousLastWriteFinished = lastWriteFinished;
3286 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003287 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003288 // FIXME rewrite to reduce number of system calls
3289 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003290 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003291 lastWriteFinished = systemTime();
3292 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003293 if (ret < 0) {
3294 mBytesRemaining = 0;
3295 } else {
3296 mBytesWritten += ret;
3297 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003298 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003299 }
3300 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3301 (mMixerStatus == MIXER_DRAIN_ALL)) {
3302 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003303 }
Andy Hung08fb1742015-05-31 23:22:10 -07003304 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003305 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003306 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003307 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003308 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003309 ATRACE_NAME("underrun");
3310 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003311 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003312 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003313 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003314 }
Andy Hung08fb1742015-05-31 23:22:10 -07003315
3316 if (mThreadThrottle
3317 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3318 && ret > 0) { // we wrote something
3319 // Limit MixerThread data processing to no more than twice the
3320 // expected processing rate.
3321 //
3322 // This helps prevent underruns with NuPlayer and other applications
3323 // which may set up buffers that are close to the minimum size, or use
3324 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3325 //
3326 // The throttle smooths out sudden large data drains from the device,
3327 // e.g. when it comes out of standby, which often causes problems with
3328 // (1) mixer threads without a fast mixer (which has its own warm-up)
3329 // (2) minimum buffer sized tracks (even if the track is full,
3330 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003331 //
3332 // Total time spent in last processing cycle equals time spent in
3333 // 1. threadLoop_write, as well as time spent in
3334 // 2. threadLoop_mix (significant for heavy mixing, especially
3335 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003336
Andy Hung69488c42016-05-16 18:43:33 -07003337 // it's OK if deltaMs is an overestimate.
3338 const int32_t deltaMs =
3339 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003340 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3341 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3342 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003343 // notify of throttle start on verbose log
3344 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3345 "mixer(%p) throttle begin:"
3346 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003347 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003348 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003349 // Throttle must be attributed to the previous mixer loop's write time
3350 // to allow back-to-back throttling.
3351 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003352 } else {
3353 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3354 if (diff > 0) {
3355 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003356 // but prevent spamming for bluetooth
3357 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3358 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003359 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3360 }
Andy Hung08fb1742015-05-31 23:22:10 -07003361 }
3362 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003363 }
Eric Laurent81784c32012-11-19 14:55:58 -08003364
Eric Laurentbfb1b832013-01-07 09:53:42 -08003365 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003366 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003367 Mutex::Autolock _l(mLock);
3368 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3369 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003370 }
Glenn Kastene7754022014-10-31 12:11:26 -07003371 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003372 }
Eric Laurent81784c32012-11-19 14:55:58 -08003373 }
3374
3375 // Finally let go of removed track(s), without the lock held
3376 // since we can't guarantee the destructors won't acquire that
3377 // same lock. This will also mutate and push a new fast mixer state.
3378 threadLoop_removeTracks(tracksToRemove);
3379 tracksToRemove.clear();
3380
3381 // FIXME I don't understand the need for this here;
3382 // it was in the original code but maybe the
3383 // assignment in saveOutputTracks() makes this unnecessary?
3384 clearOutputTracks();
3385
3386 // Effect chains will be actually deleted here if they were removed from
3387 // mEffectChains list during mixing or effects processing
3388 effectChains.clear();
3389
3390 // FIXME Note that the above .clear() is no longer necessary since effectChains
3391 // is now local to this block, but will keep it for now (at least until merge done).
3392 }
3393
Eric Laurentbfb1b832013-01-07 09:53:42 -08003394 threadLoop_exit();
3395
Eric Laurentcf817a22014-08-04 20:36:31 -07003396 if (!mStandby) {
3397 threadLoop_standby();
3398 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003399 }
3400
3401 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003402 mWakeLockUids.clear();
3403 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003404
3405 ALOGV("Thread %p type %d exiting", this, mType);
3406 return false;
3407}
3408
Eric Laurentbfb1b832013-01-07 09:53:42 -08003409// removeTracks_l() must be called with ThreadBase::mLock held
3410void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3411{
3412 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003413 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003414 for (size_t i=0 ; i<count ; i++) {
3415 const sp<Track>& track = tracksToRemove.itemAt(i);
3416 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003417 mWakeLockUids.remove(track->uid());
3418 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003419 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3420 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3421 if (chain != 0) {
3422 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3423 track->sessionId());
3424 chain->decActiveTrackCnt();
3425 }
3426 if (track->isTerminated()) {
3427 removeTrack_l(track);
3428 }
3429 }
3430 }
3431
3432}
Eric Laurent81784c32012-11-19 14:55:58 -08003433
Eric Laurentaccc1472013-09-20 09:36:34 -07003434status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3435{
3436 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003437 ExtendedTimestamp ets;
3438 status_t status = mNormalSink->getTimestamp(ets);
3439 if (status == NO_ERROR) {
3440 status = ets.getBestTimestamp(&timestamp);
3441 }
3442 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003443 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003444 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003445 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003446 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003447 timestamp.mPosition = (uint32_t)position64;
3448 return NO_ERROR;
3449 }
3450 }
3451 return INVALID_OPERATION;
3452}
Eric Laurent1c333e22014-05-20 10:48:17 -07003453
Eric Laurent054d9d32015-04-24 08:48:48 -07003454status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3455 audio_patch_handle_t *handle)
3456{
Andy Hungf60abce2016-08-26 11:37:54 -07003457 status_t status;
3458 if (property_get_bool("af.patch_park", false /* default_value */)) {
3459 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3460 // or if HAL does not properly lock against access.
3461 AutoPark<FastMixer> park(mFastMixer);
3462 status = PlaybackThread::createAudioPatch_l(patch, handle);
3463 } else {
3464 status = PlaybackThread::createAudioPatch_l(patch, handle);
3465 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003466 return status;
3467}
3468
Eric Laurent1c333e22014-05-20 10:48:17 -07003469status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3470 audio_patch_handle_t *handle)
3471{
3472 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003473
3474 // store new device and send to effects
3475 audio_devices_t type = AUDIO_DEVICE_NONE;
3476 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3477 type |= patch->sinks[i].ext.device.type;
3478 }
3479
3480#ifdef ADD_BATTERY_DATA
3481 // when changing the audio output device, call addBatteryData to notify
3482 // the change
3483 if (mOutDevice != type) {
3484 uint32_t params = 0;
3485 // check whether speaker is on
3486 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3487 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003488 }
3489
Eric Laurent054d9d32015-04-24 08:48:48 -07003490 audio_devices_t deviceWithoutSpeaker
3491 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3492 // check if any other device (except speaker) is on
3493 if (type & deviceWithoutSpeaker) {
3494 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3495 }
3496
3497 if (params != 0) {
3498 addBatteryData(params);
3499 }
3500 }
3501#endif
3502
3503 for (size_t i = 0; i < mEffectChains.size(); i++) {
3504 mEffectChains[i]->setDevice_l(type);
3505 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003506
3507 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3508 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3509 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003510 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003511 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003512
3513 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003514 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3515 status = hwDevice->createAudioPatch(patch->num_sources,
3516 patch->sources,
3517 patch->num_sinks,
3518 patch->sinks,
3519 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003520 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003521 char *address;
3522 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3523 //FIXME: we only support address on first sink with HAL version < 3.0
3524 address = audio_device_address_to_parameter(
3525 patch->sinks[0].ext.device.type,
3526 patch->sinks[0].ext.device.address);
3527 } else {
3528 address = (char *)calloc(1, 1);
3529 }
3530 AudioParameter param = AudioParameter(String8(address));
3531 free(address);
3532 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003533 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003534 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003535 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003536 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003537 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003538 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3539 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003540 return status;
3541}
3542
Eric Laurent054d9d32015-04-24 08:48:48 -07003543status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3544{
Andy Hungf60abce2016-08-26 11:37:54 -07003545 status_t status;
3546 if (property_get_bool("af.patch_park", false /* default_value */)) {
3547 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3548 // or if HAL does not properly lock against access.
3549 AutoPark<FastMixer> park(mFastMixer);
3550 status = PlaybackThread::releaseAudioPatch_l(handle);
3551 } else {
3552 status = PlaybackThread::releaseAudioPatch_l(handle);
3553 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003554 return status;
3555}
3556
Eric Laurent1c333e22014-05-20 10:48:17 -07003557status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3558{
3559 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003560
3561 mOutDevice = AUDIO_DEVICE_NONE;
3562
Eric Laurent1c333e22014-05-20 10:48:17 -07003563 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003564 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3565 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003566 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003567 AudioParameter param;
3568 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003569 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003570 }
3571 return status;
3572}
3573
Eric Laurent83b88082014-06-20 18:31:16 -07003574void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3575{
3576 Mutex::Autolock _l(mLock);
3577 mTracks.add(track);
3578}
3579
3580void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3581{
3582 Mutex::Autolock _l(mLock);
3583 destroyTrack_l(track);
3584}
3585
3586void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3587{
3588 ThreadBase::getAudioPortConfig(config);
3589 config->role = AUDIO_PORT_ROLE_SOURCE;
3590 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3591 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3592}
3593
Eric Laurent81784c32012-11-19 14:55:58 -08003594// ----------------------------------------------------------------------------
3595
3596AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003597 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3598 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003599 // mAudioMixer below
3600 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003601 mFastMixerFutex(0),
3602 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003603 // mOutputSink below
3604 // mPipeSink below
3605 // mNormalSink below
3606{
3607 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003608 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3609 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003610 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3611 mNormalFrameCount);
3612 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3613
Andy Hungfbfc3952015-01-15 13:33:51 -08003614 if (type == DUPLICATING) {
3615 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3616 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3617 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3618 return;
3619 }
Eric Laurent81784c32012-11-19 14:55:58 -08003620 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003621 mOutputSink = new AudioStreamOutSink(
3622 static_cast<StreamOutHalLocal*>(output->stream.get())->getStream());
Eric Laurent81784c32012-11-19 14:55:58 -08003623 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003624 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003625#if !LOG_NDEBUG
3626 ssize_t index =
3627#else
3628 (void)
3629#endif
3630 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003631 ALOG_ASSERT(index == 0);
3632
3633 // initialize fast mixer depending on configuration
3634 bool initFastMixer;
3635 switch (kUseFastMixer) {
3636 case FastMixer_Never:
3637 initFastMixer = false;
3638 break;
3639 case FastMixer_Always:
3640 initFastMixer = true;
3641 break;
3642 case FastMixer_Static:
3643 case FastMixer_Dynamic:
3644 initFastMixer = mFrameCount < mNormalFrameCount;
3645 break;
3646 }
3647 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003648 audio_format_t fastMixerFormat;
3649 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3650 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3651 } else {
3652 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3653 }
3654 if (mFormat != fastMixerFormat) {
3655 // change our Sink format to accept our intermediate precision
3656 mFormat = fastMixerFormat;
3657 free(mSinkBuffer);
3658 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3659 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3660 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3661 }
Eric Laurent81784c32012-11-19 14:55:58 -08003662
3663 // create a MonoPipe to connect our submix to FastMixer
3664 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003665#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003666 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003667#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003668 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003669 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003670 format.mFormat = fastMixerFormat;
3671 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3672
Eric Laurent81784c32012-11-19 14:55:58 -08003673 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3674 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3675 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3676 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3677 const NBAIO_Format offers[1] = {format};
3678 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003679#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003680 ssize_t index =
3681#else
3682 (void)
3683#endif
3684 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003685 ALOG_ASSERT(index == 0);
3686 monoPipe->setAvgFrames((mScreenState & 1) ?
3687 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3688 mPipeSink = monoPipe;
3689
Glenn Kasten46909e72013-02-26 09:20:22 -08003690#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003691 if (mTeeSinkOutputEnabled) {
3692 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003693 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3694 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003695 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003696 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003697 ALOG_ASSERT(index == 0);
3698 mTeeSink = teeSink;
3699 PipeReader *teeSource = new PipeReader(*teeSink);
3700 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003701 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003702 ALOG_ASSERT(index == 0);
3703 mTeeSource = teeSource;
3704 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003705#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003706
3707 // create fast mixer and configure it initially with just one fast track for our submix
3708 mFastMixer = new FastMixer();
3709 FastMixerStateQueue *sq = mFastMixer->sq();
3710#ifdef STATE_QUEUE_DUMP
3711 sq->setObserverDump(&mStateQueueObserverDump);
3712 sq->setMutatorDump(&mStateQueueMutatorDump);
3713#endif
3714 FastMixerState *state = sq->begin();
3715 FastTrack *fastTrack = &state->mFastTracks[0];
3716 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3717 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3718 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003719 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3720 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003721 fastTrack->mGeneration++;
3722 state->mFastTracksGen++;
3723 state->mTrackMask = 1;
3724 // fast mixer will use the HAL output sink
3725 state->mOutputSink = mOutputSink.get();
3726 state->mOutputSinkGen++;
3727 state->mFrameCount = mFrameCount;
3728 state->mCommand = FastMixerState::COLD_IDLE;
3729 // already done in constructor initialization list
3730 //mFastMixerFutex = 0;
3731 state->mColdFutexAddr = &mFastMixerFutex;
3732 state->mColdGen++;
3733 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003734#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003735 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003736#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003737 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3738 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003739 sq->end();
3740 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3741
3742 // start the fast mixer
3743 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3744 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003745 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003746
3747#ifdef AUDIO_WATCHDOG
3748 // create and start the watchdog
3749 mAudioWatchdog = new AudioWatchdog();
3750 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3751 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3752 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003753 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003754#endif
3755
Eric Laurent81784c32012-11-19 14:55:58 -08003756 }
3757
3758 switch (kUseFastMixer) {
3759 case FastMixer_Never:
3760 case FastMixer_Dynamic:
3761 mNormalSink = mOutputSink;
3762 break;
3763 case FastMixer_Always:
3764 mNormalSink = mPipeSink;
3765 break;
3766 case FastMixer_Static:
3767 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3768 break;
3769 }
3770}
3771
3772AudioFlinger::MixerThread::~MixerThread()
3773{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003774 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003775 FastMixerStateQueue *sq = mFastMixer->sq();
3776 FastMixerState *state = sq->begin();
3777 if (state->mCommand == FastMixerState::COLD_IDLE) {
3778 int32_t old = android_atomic_inc(&mFastMixerFutex);
3779 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003780 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003781 }
3782 }
3783 state->mCommand = FastMixerState::EXIT;
3784 sq->end();
3785 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3786 mFastMixer->join();
3787 // Though the fast mixer thread has exited, it's state queue is still valid.
3788 // We'll use that extract the final state which contains one remaining fast track
3789 // corresponding to our sub-mix.
3790 state = sq->begin();
3791 ALOG_ASSERT(state->mTrackMask == 1);
3792 FastTrack *fastTrack = &state->mFastTracks[0];
3793 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3794 delete fastTrack->mBufferProvider;
3795 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003796 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003797#ifdef AUDIO_WATCHDOG
3798 if (mAudioWatchdog != 0) {
3799 mAudioWatchdog->requestExit();
3800 mAudioWatchdog->requestExitAndWait();
3801 mAudioWatchdog.clear();
3802 }
3803#endif
3804 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003805 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003806 delete mAudioMixer;
3807}
3808
3809
3810uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3811{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003812 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003813 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3814 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3815 }
3816 return latency;
3817}
3818
3819
3820void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3821{
3822 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3823}
3824
Eric Laurentbfb1b832013-01-07 09:53:42 -08003825ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003826{
3827 // FIXME we should only do one push per cycle; confirm this is true
3828 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003829 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003830 FastMixerStateQueue *sq = mFastMixer->sq();
3831 FastMixerState *state = sq->begin();
3832 if (state->mCommand != FastMixerState::MIX_WRITE &&
3833 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3834 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003835
3836 // FIXME workaround for first HAL write being CPU bound on some devices
3837 ATRACE_BEGIN("write");
3838 mOutput->write((char *)mSinkBuffer, 0);
3839 ATRACE_END();
3840
Eric Laurent81784c32012-11-19 14:55:58 -08003841 int32_t old = android_atomic_inc(&mFastMixerFutex);
3842 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003843 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003844 }
3845#ifdef AUDIO_WATCHDOG
3846 if (mAudioWatchdog != 0) {
3847 mAudioWatchdog->resume();
3848 }
3849#endif
3850 }
3851 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003852#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003853 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003854 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003855#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003856 sq->end();
3857 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3858 if (kUseFastMixer == FastMixer_Dynamic) {
3859 mNormalSink = mPipeSink;
3860 }
3861 } else {
3862 sq->end(false /*didModify*/);
3863 }
3864 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003865 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003866}
3867
3868void AudioFlinger::MixerThread::threadLoop_standby()
3869{
3870 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003871 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003872 FastMixerStateQueue *sq = mFastMixer->sq();
3873 FastMixerState *state = sq->begin();
3874 if (!(state->mCommand & FastMixerState::IDLE)) {
3875 state->mCommand = FastMixerState::COLD_IDLE;
3876 state->mColdFutexAddr = &mFastMixerFutex;
3877 state->mColdGen++;
3878 mFastMixerFutex = 0;
3879 sq->end();
3880 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3881 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3882 if (kUseFastMixer == FastMixer_Dynamic) {
3883 mNormalSink = mOutputSink;
3884 }
3885#ifdef AUDIO_WATCHDOG
3886 if (mAudioWatchdog != 0) {
3887 mAudioWatchdog->pause();
3888 }
3889#endif
3890 } else {
3891 sq->end(false /*didModify*/);
3892 }
3893 }
3894 PlaybackThread::threadLoop_standby();
3895}
3896
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3898{
3899 return false;
3900}
3901
3902bool AudioFlinger::PlaybackThread::shouldStandby_l()
3903{
3904 return !mStandby;
3905}
3906
3907bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3908{
3909 Mutex::Autolock _l(mLock);
3910 return waitingAsyncCallback_l();
3911}
3912
Eric Laurent81784c32012-11-19 14:55:58 -08003913// shared by MIXER and DIRECT, overridden by DUPLICATING
3914void AudioFlinger::PlaybackThread::threadLoop_standby()
3915{
3916 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003917 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003919 // discard any pending drain or write ack by incrementing sequence
3920 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3921 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003922 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003923 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3924 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003925 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003926 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003927}
3928
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003929void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3930{
3931 ALOGV("signal playback thread");
3932 broadcast_l();
3933}
3934
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003935void AudioFlinger::PlaybackThread::onAsyncError()
3936{
3937 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3938 invalidateTracks((audio_stream_type_t)i);
3939 }
3940}
3941
Eric Laurent81784c32012-11-19 14:55:58 -08003942void AudioFlinger::MixerThread::threadLoop_mix()
3943{
Eric Laurent81784c32012-11-19 14:55:58 -08003944 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003945 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003946 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003947 // increase sleep time progressively when application underrun condition clears.
3948 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3949 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3950 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003951 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003952 sleepTimeShift--;
3953 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003954 mSleepTimeUs = 0;
3955 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003956 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003957
Eric Laurent81784c32012-11-19 14:55:58 -08003958}
3959
3960void AudioFlinger::MixerThread::threadLoop_sleepTime()
3961{
3962 // If no tracks are ready, sleep once for the duration of an output
3963 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003964 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003965 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003966 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3967 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3968 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003969 }
3970 // reduce sleep time in case of consecutive application underruns to avoid
3971 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3972 // duration we would end up writing less data than needed by the audio HAL if
3973 // the condition persists.
3974 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3975 sleepTimeShift++;
3976 }
3977 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003978 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003979 }
3980 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003981 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3982 // before effects processing or output.
3983 if (mMixerBufferValid) {
3984 memset(mMixerBuffer, 0, mMixerBufferSize);
3985 } else {
3986 memset(mSinkBuffer, 0, mSinkBufferSize);
3987 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003988 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003989 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3990 "anticipated start");
3991 }
3992 // TODO add standby time extension fct of effect tail
3993}
3994
3995// prepareTracks_l() must be called with ThreadBase::mLock held
3996AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3997 Vector< sp<Track> > *tracksToRemove)
3998{
3999
4000 mixer_state mixerStatus = MIXER_IDLE;
4001 // find out which tracks need to be processed
4002 size_t count = mActiveTracks.size();
4003 size_t mixedTracks = 0;
4004 size_t tracksWithEffect = 0;
4005 // counts only _active_ fast tracks
4006 size_t fastTracks = 0;
4007 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4008
4009 float masterVolume = mMasterVolume;
4010 bool masterMute = mMasterMute;
4011
4012 if (masterMute) {
4013 masterVolume = 0;
4014 }
4015 // Delegate master volume control to effect in output mix effect chain if needed
4016 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4017 if (chain != 0) {
4018 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4019 chain->setVolume_l(&v, &v);
4020 masterVolume = (float)((v + (1 << 23)) >> 24);
4021 chain.clear();
4022 }
4023
4024 // prepare a new state to push
4025 FastMixerStateQueue *sq = NULL;
4026 FastMixerState *state = NULL;
4027 bool didModify = false;
4028 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004029 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004030 sq = mFastMixer->sq();
4031 state = sq->begin();
4032 }
4033
Andy Hung69aed5f2014-02-25 17:24:40 -08004034 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004035 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004036
Eric Laurent81784c32012-11-19 14:55:58 -08004037 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004038 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004039 if (t == 0) {
4040 continue;
4041 }
4042
4043 // this const just means the local variable doesn't change
4044 Track* const track = t.get();
4045
4046 // process fast tracks
4047 if (track->isFastTrack()) {
4048
4049 // It's theoretically possible (though unlikely) for a fast track to be created
4050 // and then removed within the same normal mix cycle. This is not a problem, as
4051 // the track never becomes active so it's fast mixer slot is never touched.
4052 // The converse, of removing an (active) track and then creating a new track
4053 // at the identical fast mixer slot within the same normal mix cycle,
4054 // is impossible because the slot isn't marked available until the end of each cycle.
4055 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004056 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004057 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4058 FastTrack *fastTrack = &state->mFastTracks[j];
4059
4060 // Determine whether the track is currently in underrun condition,
4061 // and whether it had a recent underrun.
4062 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4063 FastTrackUnderruns underruns = ftDump->mUnderruns;
4064 uint32_t recentFull = (underruns.mBitFields.mFull -
4065 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4066 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4067 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4068 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4069 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4070 uint32_t recentUnderruns = recentPartial + recentEmpty;
4071 track->mObservedUnderruns = underruns;
4072 // don't count underruns that occur while stopping or pausing
4073 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004074 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4075 recentUnderruns > 0) {
4076 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4077 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004078 } else {
4079 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004080 }
4081
4082 // This is similar to the state machine for normal tracks,
4083 // with a few modifications for fast tracks.
4084 bool isActive = true;
4085 switch (track->mState) {
4086 case TrackBase::STOPPING_1:
4087 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004088 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004089 track->mState = TrackBase::STOPPING_2;
4090 }
4091 break;
4092 case TrackBase::PAUSING:
4093 // ramp down is not yet implemented
4094 track->setPaused();
4095 break;
4096 case TrackBase::RESUMING:
4097 // ramp up is not yet implemented
4098 track->mState = TrackBase::ACTIVE;
4099 break;
4100 case TrackBase::ACTIVE:
4101 if (recentFull > 0 || recentPartial > 0) {
4102 // track has provided at least some frames recently: reset retry count
4103 track->mRetryCount = kMaxTrackRetries;
4104 }
4105 if (recentUnderruns == 0) {
4106 // no recent underruns: stay active
4107 break;
4108 }
4109 // there has recently been an underrun of some kind
4110 if (track->sharedBuffer() == 0) {
4111 // were any of the recent underruns "empty" (no frames available)?
4112 if (recentEmpty == 0) {
4113 // no, then ignore the partial underruns as they are allowed indefinitely
4114 break;
4115 }
4116 // there has recently been an "empty" underrun: decrement the retry counter
4117 if (--(track->mRetryCount) > 0) {
4118 break;
4119 }
4120 // indicate to client process that the track was disabled because of underrun;
4121 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004122 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004123 // remove from active list, but state remains ACTIVE [confusing but true]
4124 isActive = false;
4125 break;
4126 }
4127 // fall through
4128 case TrackBase::STOPPING_2:
4129 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004130 case TrackBase::STOPPED:
4131 case TrackBase::FLUSHED: // flush() while active
4132 // Check for presentation complete if track is inactive
4133 // We have consumed all the buffers of this track.
4134 // This would be incomplete if we auto-paused on underrun
4135 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004136 uint32_t latency = 0;
4137 status_t result = mOutput->stream->getLatency(&latency);
4138 ALOGE_IF(result != OK,
4139 "Error when retrieving output stream latency: %d", result);
4140 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004141 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004142 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4143 // track stays in active list until presentation is complete
4144 break;
4145 }
4146 }
4147 if (track->isStopping_2()) {
4148 track->mState = TrackBase::STOPPED;
4149 }
4150 if (track->isStopped()) {
4151 // Can't reset directly, as fast mixer is still polling this track
4152 // track->reset();
4153 // So instead mark this track as needing to be reset after push with ack
4154 resetMask |= 1 << i;
4155 }
4156 isActive = false;
4157 break;
4158 case TrackBase::IDLE:
4159 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004160 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004161 }
4162
4163 if (isActive) {
4164 // was it previously inactive?
4165 if (!(state->mTrackMask & (1 << j))) {
4166 ExtendedAudioBufferProvider *eabp = track;
4167 VolumeProvider *vp = track;
4168 fastTrack->mBufferProvider = eabp;
4169 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004170 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004171 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004172 fastTrack->mGeneration++;
4173 state->mTrackMask |= 1 << j;
4174 didModify = true;
4175 // no acknowledgement required for newly active tracks
4176 }
4177 // cache the combined master volume and stream type volume for fast mixer; this
4178 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004179 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004180 ++fastTracks;
4181 } else {
4182 // was it previously active?
4183 if (state->mTrackMask & (1 << j)) {
4184 fastTrack->mBufferProvider = NULL;
4185 fastTrack->mGeneration++;
4186 state->mTrackMask &= ~(1 << j);
4187 didModify = true;
4188 // If any fast tracks were removed, we must wait for acknowledgement
4189 // because we're about to decrement the last sp<> on those tracks.
4190 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4191 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004192 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4193 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4194 j, track->mState, state->mTrackMask, recentUnderruns,
4195 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004196 }
4197 tracksToRemove->add(track);
4198 // Avoids a misleading display in dumpsys
4199 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4200 }
4201 continue;
4202 }
4203
4204 { // local variable scope to avoid goto warning
4205
4206 audio_track_cblk_t* cblk = track->cblk();
4207
4208 // The first time a track is added we wait
4209 // for all its buffers to be filled before processing it
4210 int name = track->name();
4211 // make sure that we have enough frames to mix one full buffer.
4212 // enforce this condition only once to enable draining the buffer in case the client
4213 // app does not call stop() and relies on underrun to stop:
4214 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4215 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004216 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004217 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004218 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004219
4220 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004221 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004222 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4223 // add frames already consumed but not yet released by the resampler
4224 // because mAudioTrackServerProxy->framesReady() will include these frames
4225 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4226
Eric Laurent81784c32012-11-19 14:55:58 -08004227 uint32_t minFrames = 1;
4228 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4229 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004230 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004231 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004232
4233 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004234 if (ATRACE_ENABLED()) {
4235 // I wish we had formatted trace names
4236 char traceName[16];
4237 strcpy(traceName, "nRdy");
4238 int name = track->name();
4239 if (AudioMixer::TRACK0 <= name &&
4240 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4241 name -= AudioMixer::TRACK0;
4242 traceName[4] = (name / 10) + '0';
4243 traceName[5] = (name % 10) + '0';
4244 } else {
4245 traceName[4] = '?';
4246 traceName[5] = '?';
4247 }
4248 traceName[6] = '\0';
4249 ATRACE_INT(traceName, framesReady);
4250 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004251 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004252 !track->isPaused() && !track->isTerminated())
4253 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004254 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004255
4256 mixedTracks++;
4257
Andy Hung69aed5f2014-02-25 17:24:40 -08004258 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4259 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004260 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004261 if (track->mainBuffer() != mSinkBuffer &&
4262 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004263 if (mEffectBufferEnabled) {
4264 mEffectBufferValid = true; // Later can set directly.
4265 }
Eric Laurent81784c32012-11-19 14:55:58 -08004266 chain = getEffectChain_l(track->sessionId());
4267 // Delegate volume control to effect in track effect chain if needed
4268 if (chain != 0) {
4269 tracksWithEffect++;
4270 } else {
4271 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4272 "session %d",
4273 name, track->sessionId());
4274 }
4275 }
4276
4277
4278 int param = AudioMixer::VOLUME;
4279 if (track->mFillingUpStatus == Track::FS_FILLED) {
4280 // no ramp for the first volume setting
4281 track->mFillingUpStatus = Track::FS_ACTIVE;
4282 if (track->mState == TrackBase::RESUMING) {
4283 track->mState = TrackBase::ACTIVE;
4284 param = AudioMixer::RAMP_VOLUME;
4285 }
4286 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004287 // FIXME should not make a decision based on mServer
4288 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004289 // If the track is stopped before the first frame was mixed,
4290 // do not apply ramp
4291 param = AudioMixer::RAMP_VOLUME;
4292 }
4293
4294 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004295 uint32_t vl, vr; // in U8.24 integer format
4296 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004297 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004298 vl = vr = 0;
4299 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004300 if (track->isPausing()) {
4301 track->setPaused();
4302 }
4303 } else {
4304
4305 // read original volumes with volume control
4306 float typeVolume = mStreamTypes[track->streamType()].volume;
4307 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004308 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004309 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004310 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4311 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004312 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004313 if (vlf > GAIN_FLOAT_UNITY) {
4314 ALOGV("Track left volume out of range: %.3g", vlf);
4315 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004316 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004317 if (vrf > GAIN_FLOAT_UNITY) {
4318 ALOGV("Track right volume out of range: %.3g", vrf);
4319 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004320 }
4321 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004322 vlf *= v;
4323 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004324 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004325 // then derive vl and vr as U8.24 versions for the effect chain
4326 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4327 vl = (uint32_t) (scaleto8_24 * vlf);
4328 vr = (uint32_t) (scaleto8_24 * vrf);
4329 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004330 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004331 // send level comes from shared memory and so may be corrupt
4332 if (sendLevel > MAX_GAIN_INT) {
4333 ALOGV("Track send level out of range: %04X", sendLevel);
4334 sendLevel = MAX_GAIN_INT;
4335 }
Andy Hung6be49402014-05-30 10:42:03 -07004336 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4337 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004338 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004339
Eric Laurent81784c32012-11-19 14:55:58 -08004340 // Delegate volume control to effect in track effect chain if needed
4341 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4342 // Do not ramp volume if volume is controlled by effect
4343 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004344 // Update remaining floating point volume levels
4345 vlf = (float)vl / (1 << 24);
4346 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004347 track->mHasVolumeController = true;
4348 } else {
4349 // force no volume ramp when volume controller was just disabled or removed
4350 // from effect chain to avoid volume spike
4351 if (track->mHasVolumeController) {
4352 param = AudioMixer::VOLUME;
4353 }
4354 track->mHasVolumeController = false;
4355 }
4356
Eric Laurent81784c32012-11-19 14:55:58 -08004357 // XXX: these things DON'T need to be done each time
4358 mAudioMixer->setBufferProvider(name, track);
4359 mAudioMixer->enable(name);
4360
Andy Hung6be49402014-05-30 10:42:03 -07004361 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4362 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4363 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004364 mAudioMixer->setParameter(
4365 name,
4366 AudioMixer::TRACK,
4367 AudioMixer::FORMAT, (void *)track->format());
4368 mAudioMixer->setParameter(
4369 name,
4370 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004371 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004372 mAudioMixer->setParameter(
4373 name,
4374 AudioMixer::TRACK,
4375 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004376 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004377 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004378 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004379 if (reqSampleRate == 0) {
4380 reqSampleRate = mSampleRate;
4381 } else if (reqSampleRate > maxSampleRate) {
4382 reqSampleRate = maxSampleRate;
4383 }
Eric Laurent81784c32012-11-19 14:55:58 -08004384 mAudioMixer->setParameter(
4385 name,
4386 AudioMixer::RESAMPLE,
4387 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004388 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004389
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004390 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004391 mAudioMixer->setParameter(
4392 name,
4393 AudioMixer::TIMESTRETCH,
4394 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004395 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004396
Andy Hung69aed5f2014-02-25 17:24:40 -08004397 /*
4398 * Select the appropriate output buffer for the track.
4399 *
Andy Hung98ef9782014-03-04 14:46:50 -08004400 * Tracks with effects go into their own effects chain buffer
4401 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004402 *
4403 * Other tracks can use mMixerBuffer for higher precision
4404 * channel accumulation. If this buffer is enabled
4405 * (mMixerBufferEnabled true), then selected tracks will accumulate
4406 * into it.
4407 *
4408 */
4409 if (mMixerBufferEnabled
4410 && (track->mainBuffer() == mSinkBuffer
4411 || track->mainBuffer() == mMixerBuffer)) {
4412 mAudioMixer->setParameter(
4413 name,
4414 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004415 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004416 mAudioMixer->setParameter(
4417 name,
4418 AudioMixer::TRACK,
4419 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4420 // TODO: override track->mainBuffer()?
4421 mMixerBufferValid = true;
4422 } else {
4423 mAudioMixer->setParameter(
4424 name,
4425 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004426 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004427 mAudioMixer->setParameter(
4428 name,
4429 AudioMixer::TRACK,
4430 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4431 }
Eric Laurent81784c32012-11-19 14:55:58 -08004432 mAudioMixer->setParameter(
4433 name,
4434 AudioMixer::TRACK,
4435 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4436
4437 // reset retry count
4438 track->mRetryCount = kMaxTrackRetries;
4439
4440 // If one track is ready, set the mixer ready if:
4441 // - the mixer was not ready during previous round OR
4442 // - no other track is not ready
4443 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4444 mixerStatus != MIXER_TRACKS_ENABLED) {
4445 mixerStatus = MIXER_TRACKS_READY;
4446 }
4447 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004448 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004449 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4450 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004451 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004452 } else {
4453 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004454 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004455
Eric Laurent81784c32012-11-19 14:55:58 -08004456 // clear effect chain input buffer if an active track underruns to avoid sending
4457 // previous audio buffer again to effects
4458 chain = getEffectChain_l(track->sessionId());
4459 if (chain != 0) {
4460 chain->clearInputBuffer();
4461 }
4462
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004463 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004464 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4465 track->isStopped() || track->isPaused()) {
4466 // We have consumed all the buffers of this track.
4467 // Remove it from the list of active tracks.
4468 // TODO: use actual buffer filling status instead of latency when available from
4469 // audio HAL
4470 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004471 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004472 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4473 if (track->isStopped()) {
4474 track->reset();
4475 }
4476 tracksToRemove->add(track);
4477 }
4478 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004479 // No buffers for this track. Give it a few chances to
4480 // fill a buffer, then remove it from active list.
4481 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004482 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004483 tracksToRemove->add(track);
4484 // indicate to client process that the track was disabled because of underrun;
4485 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004486 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004487 // If one track is not ready, mark the mixer also not ready if:
4488 // - the mixer was ready during previous round OR
4489 // - no other track is ready
4490 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4491 mixerStatus != MIXER_TRACKS_READY) {
4492 mixerStatus = MIXER_TRACKS_ENABLED;
4493 }
4494 }
4495 mAudioMixer->disable(name);
4496 }
4497
4498 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004499
4500 }
4501
4502 // Push the new FastMixer state if necessary
4503 bool pauseAudioWatchdog = false;
4504 if (didModify) {
4505 state->mFastTracksGen++;
4506 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4507 if (kUseFastMixer == FastMixer_Dynamic &&
4508 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4509 state->mCommand = FastMixerState::COLD_IDLE;
4510 state->mColdFutexAddr = &mFastMixerFutex;
4511 state->mColdGen++;
4512 mFastMixerFutex = 0;
4513 if (kUseFastMixer == FastMixer_Dynamic) {
4514 mNormalSink = mOutputSink;
4515 }
4516 // If we go into cold idle, need to wait for acknowledgement
4517 // so that fast mixer stops doing I/O.
4518 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4519 pauseAudioWatchdog = true;
4520 }
Eric Laurent81784c32012-11-19 14:55:58 -08004521 }
4522 if (sq != NULL) {
4523 sq->end(didModify);
4524 sq->push(block);
4525 }
4526#ifdef AUDIO_WATCHDOG
4527 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4528 mAudioWatchdog->pause();
4529 }
4530#endif
4531
4532 // Now perform the deferred reset on fast tracks that have stopped
4533 while (resetMask != 0) {
4534 size_t i = __builtin_ctz(resetMask);
4535 ALOG_ASSERT(i < count);
4536 resetMask &= ~(1 << i);
4537 sp<Track> t = mActiveTracks[i].promote();
4538 if (t == 0) {
4539 continue;
4540 }
4541 Track* track = t.get();
4542 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4543 track->reset();
4544 }
4545
4546 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004547 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004548
Eric Laurent97d547d2014-09-02 14:45:53 -07004549 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4550 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004551 }
4552
4553 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004554 // as long as there are effects we should clear the effects buffer, to avoid
4555 // passing a non-clean buffer to the effect chain
4556 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004557 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004558 // sink or mix buffer must be cleared if all tracks are connected to an
4559 // effect chain as in this case the mixer will not write to the sink or mix buffer
4560 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004561 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4562 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004563 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004564 if (mMixerBufferValid) {
4565 memset(mMixerBuffer, 0, mMixerBufferSize);
4566 // TODO: In testing, mSinkBuffer below need not be cleared because
4567 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4568 // after mixing.
4569 //
4570 // To enforce this guarantee:
4571 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4572 // (mixedTracks == 0 && fastTracks > 0))
4573 // must imply MIXER_TRACKS_READY.
4574 // Later, we may clear buffers regardless, and skip much of this logic.
4575 }
Andy Hung98ef9782014-03-04 14:46:50 -08004576 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004577 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004578 }
4579
4580 // if any fast tracks, then status is ready
4581 mMixerStatusIgnoringFastTracks = mixerStatus;
4582 if (fastTracks > 0) {
4583 mixerStatus = MIXER_TRACKS_READY;
4584 }
4585 return mixerStatus;
4586}
4587
Eric Laurentad7dd962016-09-22 12:38:37 -07004588// trackCountForUid_l() must be called with ThreadBase::mLock held
4589uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4590{
4591 uint32_t trackCount = 0;
4592 for (size_t i = 0; i < mTracks.size() ; i++) {
4593 if (mTracks[i]->uid() == (int)uid) {
4594 trackCount++;
4595 }
4596 }
4597 return trackCount;
4598}
4599
Eric Laurent81784c32012-11-19 14:55:58 -08004600// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004601int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004602 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004603{
Eric Laurentad7dd962016-09-22 12:38:37 -07004604 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4605 return -1;
4606 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004607 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004608}
4609
4610// deleteTrackName_l() must be called with ThreadBase::mLock held
4611void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4612{
4613 ALOGV("remove track (%d) and delete from mixer", name);
4614 mAudioMixer->deleteTrackName(name);
4615}
4616
Eric Laurent10351942014-05-08 18:49:52 -07004617// checkForNewParameter_l() must be called with ThreadBase::mLock held
4618bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4619 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004620{
Eric Laurent81784c32012-11-19 14:55:58 -08004621 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004622 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004623
Eric Laurent10351942014-05-08 18:49:52 -07004624 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004625
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004626 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004627
Eric Laurent10351942014-05-08 18:49:52 -07004628 AudioParameter param = AudioParameter(keyValuePair);
4629 int value;
4630 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4631 reconfig = true;
4632 }
4633 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004634 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004635 status = BAD_VALUE;
4636 } else {
4637 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004638 reconfig = true;
4639 }
Eric Laurent10351942014-05-08 18:49:52 -07004640 }
4641 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004642 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004643 status = BAD_VALUE;
4644 } else {
4645 // no need to save value, since it's constant
4646 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004647 }
Eric Laurent10351942014-05-08 18:49:52 -07004648 }
4649 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4650 // do not accept frame count changes if tracks are open as the track buffer
4651 // size depends on frame count and correct behavior would not be guaranteed
4652 // if frame count is changed after track creation
4653 if (!mTracks.isEmpty()) {
4654 status = INVALID_OPERATION;
4655 } else {
4656 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004657 }
Eric Laurent10351942014-05-08 18:49:52 -07004658 }
4659 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004660#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004661 // when changing the audio output device, call addBatteryData to notify
4662 // the change
4663 if (mOutDevice != value) {
4664 uint32_t params = 0;
4665 // check whether speaker is on
4666 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4667 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004668 }
Eric Laurent10351942014-05-08 18:49:52 -07004669
4670 audio_devices_t deviceWithoutSpeaker
4671 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4672 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004673 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004674 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4675 }
4676
4677 if (params != 0) {
4678 addBatteryData(params);
4679 }
4680 }
Eric Laurent81784c32012-11-19 14:55:58 -08004681#endif
4682
Eric Laurent10351942014-05-08 18:49:52 -07004683 // forward device change to effects that have requested to be
4684 // aware of attached audio device.
4685 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004686 a2dpDeviceChanged =
4687 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004688 mOutDevice = value;
4689 for (size_t i = 0; i < mEffectChains.size(); i++) {
4690 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004691 }
4692 }
Eric Laurent10351942014-05-08 18:49:52 -07004693 }
Eric Laurent81784c32012-11-19 14:55:58 -08004694
Eric Laurent10351942014-05-08 18:49:52 -07004695 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004696 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004697 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004698 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004699 mStandby = true;
4700 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004701 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004702 }
Eric Laurent10351942014-05-08 18:49:52 -07004703 if (status == NO_ERROR && reconfig) {
4704 readOutputParameters_l();
4705 delete mAudioMixer;
4706 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4707 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004708 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004709 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004710 if (name < 0) {
4711 break;
4712 }
4713 mTracks[i]->mName = name;
4714 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004715 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004716 }
Eric Laurent81784c32012-11-19 14:55:58 -08004717 }
4718
Eric Laurent42537be2016-01-08 17:16:42 -08004719 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004720}
4721
4722
4723void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4724{
Eric Laurent81784c32012-11-19 14:55:58 -08004725 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004726 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004727 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004728 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004729
4730 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004731 // while we are dumping it. It may be inconsistent, but it won't mutate!
4732 // This is a large object so we place it on the heap.
4733 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4734 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4735 copy->dump(fd);
4736 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004737
4738#ifdef STATE_QUEUE_DUMP
4739 // Similar for state queue
4740 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4741 observerCopy.dump(fd);
4742 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4743 mutatorCopy.dump(fd);
4744#endif
4745
Glenn Kasten46909e72013-02-26 09:20:22 -08004746#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004747 // Write the tee output to a .wav file
4748 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004749#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004750
4751#ifdef AUDIO_WATCHDOG
4752 if (mAudioWatchdog != 0) {
4753 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4754 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4755 wdCopy.dump(fd);
4756 }
4757#endif
4758}
4759
4760uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4761{
4762 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4763}
4764
4765uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4766{
4767 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4768}
4769
4770void AudioFlinger::MixerThread::cacheParameters_l()
4771{
4772 PlaybackThread::cacheParameters_l();
4773
4774 // FIXME: Relaxed timing because of a certain device that can't meet latency
4775 // Should be reduced to 2x after the vendor fixes the driver issue
4776 // increase threshold again due to low power audio mode. The way this warning
4777 // threshold is calculated and its usefulness should be reconsidered anyway.
4778 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4779}
4780
4781// ----------------------------------------------------------------------------
4782
4783AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004784 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4785 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004786 // mLeftVolFloat, mRightVolFloat
4787{
4788}
4789
Eric Laurentbfb1b832013-01-07 09:53:42 -08004790AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4791 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004792 ThreadBase::type_t type, bool systemReady)
4793 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004794 // mLeftVolFloat, mRightVolFloat
4795{
4796}
4797
Eric Laurent81784c32012-11-19 14:55:58 -08004798AudioFlinger::DirectOutputThread::~DirectOutputThread()
4799{
4800}
4801
Eric Laurentbfb1b832013-01-07 09:53:42 -08004802void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4803{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004804 float left, right;
4805
4806 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4807 left = right = 0;
4808 } else {
4809 float typeVolume = mStreamTypes[track->streamType()].volume;
4810 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004811 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004812 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4813 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4814 if (left > GAIN_FLOAT_UNITY) {
4815 left = GAIN_FLOAT_UNITY;
4816 }
4817 left *= v;
4818 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4819 if (right > GAIN_FLOAT_UNITY) {
4820 right = GAIN_FLOAT_UNITY;
4821 }
4822 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004823 }
4824
4825 if (lastTrack) {
4826 if (left != mLeftVolFloat || right != mRightVolFloat) {
4827 mLeftVolFloat = left;
4828 mRightVolFloat = right;
4829
4830 // Convert volumes from float to 8.24
4831 uint32_t vl = (uint32_t)(left * (1 << 24));
4832 uint32_t vr = (uint32_t)(right * (1 << 24));
4833
4834 // Delegate volume control to effect in track effect chain if needed
4835 // only one effect chain can be present on DirectOutputThread, so if
4836 // there is one, the track is connected to it
4837 if (!mEffectChains.isEmpty()) {
4838 mEffectChains[0]->setVolume_l(&vl, &vr);
4839 left = (float)vl / (1 << 24);
4840 right = (float)vr / (1 << 24);
4841 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004842 status_t result = mOutput->stream->setVolume(left, right);
4843 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004844 }
4845 }
4846}
4847
Phil Burk43b4dcc2015-06-09 16:53:44 -07004848void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4849{
4850 sp<Track> previousTrack = mPreviousTrack.promote();
4851 sp<Track> latestTrack = mLatestActiveTrack.promote();
4852
Eric Laurent0f0631e2015-07-06 18:01:25 -07004853 if (previousTrack != 0 && latestTrack != 0) {
4854 if (mType == DIRECT) {
4855 if (previousTrack.get() != latestTrack.get()) {
4856 mFlushPending = true;
4857 }
4858 } else /* mType == OFFLOAD */ {
4859 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4860 mFlushPending = true;
4861 }
4862 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004863 }
4864 PlaybackThread::onAddNewTrack_l();
4865}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004866
Eric Laurent81784c32012-11-19 14:55:58 -08004867AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4868 Vector< sp<Track> > *tracksToRemove
4869)
4870{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004871 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004872 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004873 bool doHwPause = false;
4874 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004875
4876 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004877 for (size_t i = 0; i < count; i++) {
4878 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004879 // The track died recently
4880 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004881 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004882 }
4883
Phil Burk43b4dcc2015-06-09 16:53:44 -07004884 if (t->isInvalid()) {
4885 ALOGW("An invalidated track shouldn't be in active list");
4886 tracksToRemove->add(t);
4887 continue;
4888 }
4889
Eric Laurent81784c32012-11-19 14:55:58 -08004890 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004891#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004892 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004893#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004894 // Only consider last track started for volume and mixer state control.
4895 // In theory an older track could underrun and restart after the new one starts
4896 // but as we only care about the transition phase between two tracks on a
4897 // direct output, it is not a problem to ignore the underrun case.
4898 sp<Track> l = mLatestActiveTrack.promote();
4899 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004900
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004901 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004902 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004903 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004904 doHwPause = true;
4905 mHwPaused = true;
4906 }
4907 tracksToRemove->add(track);
4908 } else if (track->isFlushPending()) {
4909 track->flushAck();
4910 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004911 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004912 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004913 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004914 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004915 if (last) {
4916 mLeftVolFloat = mRightVolFloat = -1.0;
4917 if (mHwPaused) {
4918 doHwResume = true;
4919 mHwPaused = false;
4920 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004921 }
4922 }
4923
Eric Laurent81784c32012-11-19 14:55:58 -08004924 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004925 // for all its buffers to be filled before processing it.
4926 // Allow draining the buffer in case the client
4927 // app does not call stop() and relies on underrun to stop:
4928 // hence the test on (track->mRetryCount > 1).
4929 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004930 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004931 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004932 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004933 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004934 minFrames = mNormalFrameCount;
4935 } else {
4936 minFrames = 1;
4937 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004938
Eric Laurentab5cdba2014-06-09 17:22:27 -07004939 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4940 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004941 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004942 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004943
4944 if (track->mFillingUpStatus == Track::FS_FILLED) {
4945 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004946 if (last) {
4947 // make sure processVolume_l() will apply new volume even if 0
4948 mLeftVolFloat = mRightVolFloat = -1.0;
4949 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004950 if (!mHwSupportsPause) {
4951 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004952 }
4953 }
4954
4955 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004956 processVolume_l(track, last);
4957 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004958 sp<Track> previousTrack = mPreviousTrack.promote();
4959 if (previousTrack != 0) {
4960 if (track != previousTrack.get()) {
4961 // Flush any data still being written from last track
4962 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004963 // Invalidate previous track to force a seek when resuming.
4964 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004965 }
4966 }
4967 mPreviousTrack = track;
4968
Eric Laurentd595b7c2013-04-03 17:27:56 -07004969 // reset retry count
4970 track->mRetryCount = kMaxTrackRetriesDirect;
4971 mActiveTrack = t;
4972 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004973 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004974 doHwResume = true;
4975 mHwPaused = false;
4976 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004977 }
Eric Laurent81784c32012-11-19 14:55:58 -08004978 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004979 // clear effect chain input buffer if the last active track started underruns
4980 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004981 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004982 mEffectChains[0]->clearInputBuffer();
4983 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004984 if (track->isStopping_1()) {
4985 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004986 if (last && mHwPaused) {
4987 doHwResume = true;
4988 mHwPaused = false;
4989 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004990 }
4991 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4992 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004993 // We have consumed all the buffers of this track.
4994 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004995 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004996 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004997 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4998 } else {
4999 audioHALFrames = 0;
5000 }
5001
Andy Hung818e7a32016-02-16 18:08:07 -08005002 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005003 if (mStandby || !last ||
5004 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005005 if (track->isStopping_2()) {
5006 track->mState = TrackBase::STOPPED;
5007 }
Eric Laurent81784c32012-11-19 14:55:58 -08005008 if (track->isStopped()) {
5009 track->reset();
5010 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005011 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005012 }
5013 } else {
5014 // No buffers for this track. Give it a few chances to
5015 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005016 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005017 if (--(track->mRetryCount) <= 0) {
5018 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005019 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005020 // indicate to client process that the track was disabled because of underrun;
5021 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005022 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005023 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005024 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5025 "minFrames = %u, mFormat = %#x",
5026 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005027 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005028 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005029 doHwPause = true;
5030 mHwPaused = true;
5031 }
Eric Laurent81784c32012-11-19 14:55:58 -08005032 }
5033 }
5034 }
5035 }
5036
Eric Laurentd1f69b02014-12-15 14:33:13 -08005037 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005038 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005039 for (size_t i = 0; i < mTracks.size(); i++) {
5040 if (mTracks[i]->isFlushPending()) {
5041 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005042 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005043 }
5044 }
5045 }
5046
5047 // make sure the pause/flush/resume sequence is executed in the right order.
5048 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5049 // before flush and then resume HW. This can happen in case of pause/flush/resume
5050 // if resume is received before pause is executed.
5051 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005052 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005053 status_t result = mOutput->stream->pause();
5054 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005055 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005056 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005057 flushHw_l();
5058 }
5059 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005060 status_t result = mOutput->stream->resume();
5061 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005062 }
Eric Laurent81784c32012-11-19 14:55:58 -08005063 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005064 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005065
5066 return mixerStatus;
5067}
5068
5069void AudioFlinger::DirectOutputThread::threadLoop_mix()
5070{
Eric Laurent81784c32012-11-19 14:55:58 -08005071 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005072 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005073 // output audio to hardware
5074 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005075 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005076 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005077 status_t status = mActiveTrack->getNextBuffer(&buffer);
5078 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005079 // no need to pad with 0 for compressed audio
5080 if (audio_has_proportional_frames(mFormat)) {
5081 memset(curBuf, 0, frameCount * mFrameSize);
5082 }
Eric Laurent81784c32012-11-19 14:55:58 -08005083 break;
5084 }
5085 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5086 frameCount -= buffer.frameCount;
5087 curBuf += buffer.frameCount * mFrameSize;
5088 mActiveTrack->releaseBuffer(&buffer);
5089 }
Andy Hung2098f272014-02-27 14:00:06 -08005090 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005091 mSleepTimeUs = 0;
5092 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005093 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005094}
5095
5096void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5097{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005098 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005099 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005100 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005101 return;
5102 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005103 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005104 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005105 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005106 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005107 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005108 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005109 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005110 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005111 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005112 }
5113}
5114
Eric Laurentd1f69b02014-12-15 14:33:13 -08005115void AudioFlinger::DirectOutputThread::threadLoop_exit()
5116{
5117 {
5118 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005119 for (size_t i = 0; i < mTracks.size(); i++) {
5120 if (mTracks[i]->isFlushPending()) {
5121 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005122 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005123 }
5124 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005125 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005126 flushHw_l();
5127 }
5128 }
5129 PlaybackThread::threadLoop_exit();
5130}
5131
5132// must be called with thread mutex locked
5133bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5134{
5135 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005136 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005137
vivek mehta9cd7ad12016-03-17 00:18:29 -07005138 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5139 return !mStandby;
5140 }
5141
Eric Laurentd1f69b02014-12-15 14:33:13 -08005142 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5143 // after a timeout and we will enter standby then.
5144 if (mTracks.size() > 0) {
5145 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005146 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5147 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005148 }
5149
Eric Laurent5cff4032015-05-26 13:49:58 -07005150 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005151}
5152
Eric Laurent81784c32012-11-19 14:55:58 -08005153// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005154int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005155 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005156{
Eric Laurentad7dd962016-09-22 12:38:37 -07005157 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5158 return -1;
5159 }
Eric Laurent81784c32012-11-19 14:55:58 -08005160 return 0;
5161}
5162
5163// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005164void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005165{
5166}
5167
Eric Laurent10351942014-05-08 18:49:52 -07005168// checkForNewParameter_l() must be called with ThreadBase::mLock held
5169bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5170 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005171{
5172 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005173 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005174
Eric Laurent10351942014-05-08 18:49:52 -07005175 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005176
Eric Laurent10351942014-05-08 18:49:52 -07005177 AudioParameter param = AudioParameter(keyValuePair);
5178 int value;
5179 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5180 // forward device change to effects that have requested to be
5181 // aware of attached audio device.
5182 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005183 a2dpDeviceChanged =
5184 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005185 mOutDevice = value;
5186 for (size_t i = 0; i < mEffectChains.size(); i++) {
5187 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005188 }
5189 }
Eric Laurent81784c32012-11-19 14:55:58 -08005190 }
Eric Laurent10351942014-05-08 18:49:52 -07005191 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5192 // do not accept frame count changes if tracks are open as the track buffer
5193 // size depends on frame count and correct behavior would not be garantied
5194 // if frame count is changed after track creation
5195 if (!mTracks.isEmpty()) {
5196 status = INVALID_OPERATION;
5197 } else {
5198 reconfig = true;
5199 }
5200 }
5201 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005202 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005203 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005204 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005205 mStandby = true;
5206 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005207 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005208 }
5209 if (status == NO_ERROR && reconfig) {
5210 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005211 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005212 }
5213 }
5214
Eric Laurent42537be2016-01-08 17:16:42 -08005215 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005216}
5217
5218uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5219{
5220 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005221 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005222 time = PlaybackThread::activeSleepTimeUs();
5223 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005224 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005225 }
5226 return time;
5227}
5228
5229uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5230{
5231 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005232 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005233 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5234 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005235 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005236 }
5237 return time;
5238}
5239
5240uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5241{
5242 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005243 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005244 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5245 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005246 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005247 }
5248 return time;
5249}
5250
5251void AudioFlinger::DirectOutputThread::cacheParameters_l()
5252{
5253 PlaybackThread::cacheParameters_l();
5254
5255 // use shorter standby delay as on normal output to release
5256 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005257 // no delay on outputs with HW A/V sync
5258 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005259 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005260 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005261 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005262 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005263 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005264 }
Eric Laurent81784c32012-11-19 14:55:58 -08005265}
5266
Eric Laurente659ef42014-09-29 13:06:46 -07005267void AudioFlinger::DirectOutputThread::flushHw_l()
5268{
Phil Burk062e67a2015-02-11 13:40:50 -08005269 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005270 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005271 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005272}
5273
Eric Laurent81784c32012-11-19 14:55:58 -08005274// ----------------------------------------------------------------------------
5275
Eric Laurentbfb1b832013-01-07 09:53:42 -08005276AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005277 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005278 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005279 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005280 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005281 mDrainSequence(0),
5282 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005283{
5284}
5285
5286AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5287{
5288}
5289
5290void AudioFlinger::AsyncCallbackThread::onFirstRef()
5291{
5292 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5293}
5294
5295bool AudioFlinger::AsyncCallbackThread::threadLoop()
5296{
5297 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005298 uint32_t writeAckSequence;
5299 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005300 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005301
5302 {
5303 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005304 while (!((mWriteAckSequence & 1) ||
5305 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005306 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005307 exitPending())) {
5308 mWaitWorkCV.wait(mLock);
5309 }
5310
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311 if (exitPending()) {
5312 break;
5313 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005314 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5315 mWriteAckSequence, mDrainSequence);
5316 writeAckSequence = mWriteAckSequence;
5317 mWriteAckSequence &= ~1;
5318 drainSequence = mDrainSequence;
5319 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005320 asyncError = mAsyncError;
5321 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005322 }
5323 {
Eric Laurent4de95592013-09-26 15:28:21 -07005324 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5325 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005326 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005327 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005328 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005329 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005330 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005331 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005332 if (asyncError) {
5333 playbackThread->onAsyncError();
5334 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005335 }
5336 }
5337 }
5338 return false;
5339}
5340
5341void AudioFlinger::AsyncCallbackThread::exit()
5342{
5343 ALOGV("AsyncCallbackThread::exit");
5344 Mutex::Autolock _l(mLock);
5345 requestExit();
5346 mWaitWorkCV.broadcast();
5347}
5348
Eric Laurent3b4529e2013-09-05 18:09:19 -07005349void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005350{
5351 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005352 // bit 0 is cleared
5353 mWriteAckSequence = sequence << 1;
5354}
5355
5356void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5357{
5358 Mutex::Autolock _l(mLock);
5359 // ignore unexpected callbacks
5360 if (mWriteAckSequence & 2) {
5361 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005362 mWaitWorkCV.signal();
5363 }
5364}
5365
Eric Laurent3b4529e2013-09-05 18:09:19 -07005366void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005367{
5368 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005369 // bit 0 is cleared
5370 mDrainSequence = sequence << 1;
5371}
5372
5373void AudioFlinger::AsyncCallbackThread::resetDraining()
5374{
5375 Mutex::Autolock _l(mLock);
5376 // ignore unexpected callbacks
5377 if (mDrainSequence & 2) {
5378 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005379 mWaitWorkCV.signal();
5380 }
5381}
5382
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005383void AudioFlinger::AsyncCallbackThread::setAsyncError()
5384{
5385 Mutex::Autolock _l(mLock);
5386 mAsyncError = true;
5387 mWaitWorkCV.signal();
5388}
5389
Eric Laurentbfb1b832013-01-07 09:53:42 -08005390
5391// ----------------------------------------------------------------------------
5392AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005393 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5394 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005395 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5396 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397{
Eric Laurentfd477972013-10-25 18:10:40 -07005398 //FIXME: mStandby should be set to true by ThreadBase constructor
5399 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005400 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005401}
5402
Eric Laurentbfb1b832013-01-07 09:53:42 -08005403void AudioFlinger::OffloadThread::threadLoop_exit()
5404{
5405 if (mFlushPending || mHwPaused) {
5406 // If a flush is pending or track was paused, just discard buffered data
5407 flushHw_l();
5408 } else {
5409 mMixerStatus = MIXER_DRAIN_ALL;
5410 threadLoop_drain();
5411 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005412 if (mUseAsyncWrite) {
5413 ALOG_ASSERT(mCallbackThread != 0);
5414 mCallbackThread->exit();
5415 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416 PlaybackThread::threadLoop_exit();
5417}
5418
5419AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5420 Vector< sp<Track> > *tracksToRemove
5421)
5422{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005423 size_t count = mActiveTracks.size();
5424
5425 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005426 bool doHwPause = false;
5427 bool doHwResume = false;
5428
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005429 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005430
Eric Laurentbfb1b832013-01-07 09:53:42 -08005431 // find out which tracks need to be processed
5432 for (size_t i = 0; i < count; i++) {
5433 sp<Track> t = mActiveTracks[i].promote();
5434 // The track died recently
5435 if (t == 0) {
5436 continue;
5437 }
5438 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005439#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005440 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005441#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005442 // Only consider last track started for volume and mixer state control.
5443 // In theory an older track could underrun and restart after the new one starts
5444 // but as we only care about the transition phase between two tracks on a
5445 // direct output, it is not a problem to ignore the underrun case.
5446 sp<Track> l = mLatestActiveTrack.promote();
5447 bool last = l.get() == track;
5448
Haynes Mathew George7844f672014-01-15 12:32:55 -08005449 if (track->isInvalid()) {
5450 ALOGW("An invalidated track shouldn't be in active list");
5451 tracksToRemove->add(track);
5452 continue;
5453 }
5454
5455 if (track->mState == TrackBase::IDLE) {
5456 ALOGW("An idle track shouldn't be in active list");
5457 continue;
5458 }
5459
Eric Laurentbfb1b832013-01-07 09:53:42 -08005460 if (track->isPausing()) {
5461 track->setPaused();
5462 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005463 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005464 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005465 mHwPaused = true;
5466 }
5467 // If we were part way through writing the mixbuffer to
5468 // the HAL we must save this until we resume
5469 // BUG - this will be wrong if a different track is made active,
5470 // in that case we want to discard the pending data in the
5471 // mixbuffer and tell the client to present it again when the
5472 // track is resumed
5473 mPausedWriteLength = mCurrentWriteLength;
5474 mPausedBytesRemaining = mBytesRemaining;
5475 mBytesRemaining = 0; // stop writing
5476 }
5477 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005478 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005479 if (track->isStopping_1()) {
5480 track->mRetryCount = kMaxTrackStopRetriesOffload;
5481 } else {
5482 track->mRetryCount = kMaxTrackRetriesOffload;
5483 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005484 track->flushAck();
5485 if (last) {
5486 mFlushPending = true;
5487 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005488 } else if (track->isResumePending()){
5489 track->resumeAck();
5490 if (last) {
5491 if (mPausedBytesRemaining) {
5492 // Need to continue write that was interrupted
5493 mCurrentWriteLength = mPausedWriteLength;
5494 mBytesRemaining = mPausedBytesRemaining;
5495 mPausedBytesRemaining = 0;
5496 }
5497 if (mHwPaused) {
5498 doHwResume = true;
5499 mHwPaused = false;
5500 // threadLoop_mix() will handle the case that we need to
5501 // resume an interrupted write
5502 }
5503 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005504 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005505
Eric Laurent3df841a2016-07-15 15:15:40 -07005506 mLeftVolFloat = mRightVolFloat = -1.0;
5507
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005508 // Do not handle new data in this iteration even if track->framesReady()
5509 mixerStatus = MIXER_TRACKS_ENABLED;
5510 }
5511 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005512 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005513 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005514 if (track->mFillingUpStatus == Track::FS_FILLED) {
5515 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005516 if (last) {
5517 // make sure processVolume_l() will apply new volume even if 0
5518 mLeftVolFloat = mRightVolFloat = -1.0;
5519 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005520 }
5521
5522 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005523 sp<Track> previousTrack = mPreviousTrack.promote();
5524 if (previousTrack != 0) {
5525 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005526 // Flush any data still being written from last track
5527 mBytesRemaining = 0;
5528 if (mPausedBytesRemaining) {
5529 // Last track was paused so we also need to flush saved
5530 // mixbuffer state and invalidate track so that it will
5531 // re-submit that unwritten data when it is next resumed
5532 mPausedBytesRemaining = 0;
5533 // Invalidate is a bit drastic - would be more efficient
5534 // to have a flag to tell client that some of the
5535 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005536 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005537 }
5538 // flush data already sent to the DSP if changing audio session as audio
5539 // comes from a different source. Also invalidate previous track to force a
5540 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005541 if (previousTrack->sessionId() != track->sessionId()) {
5542 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005543 }
5544 }
5545 }
5546 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005547 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005548 if (track->isStopping_1()) {
5549 track->mRetryCount = kMaxTrackStopRetriesOffload;
5550 } else {
5551 track->mRetryCount = kMaxTrackRetriesOffload;
5552 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005553 mActiveTrack = t;
5554 mixerStatus = MIXER_TRACKS_READY;
5555 }
5556 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005557 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005558 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005559 if (--(track->mRetryCount) <= 0) {
5560 // Hardware buffer can hold a large amount of audio so we must
5561 // wait for all current track's data to drain before we say
5562 // that the track is stopped.
5563 if (mBytesRemaining == 0) {
5564 // Only start draining when all data in mixbuffer
5565 // has been written
5566 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5567 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5568 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5569 if (last && !mStandby) {
5570 // do not modify drain sequence if we are already draining. This happens
5571 // when resuming from pause after drain.
5572 if ((mDrainSequence & 1) == 0) {
5573 mSleepTimeUs = 0;
5574 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5575 mixerStatus = MIXER_DRAIN_TRACK;
5576 mDrainSequence += 2;
5577 }
5578 if (mHwPaused) {
5579 // It is possible to move from PAUSED to STOPPING_1 without
5580 // a resume so we must ensure hardware is running
5581 doHwResume = true;
5582 mHwPaused = false;
5583 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005584 }
5585 }
Eric Laurente93cc032016-05-05 10:15:10 -07005586 } else if (last) {
5587 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5588 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005589 }
5590 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005591 // Drain has completed or we are in standby, signal presentation complete
5592 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005593 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005594 uint32_t latency = 0;
5595 status_t result = mOutput->stream->getLatency(&latency);
5596 ALOGE_IF(result != OK,
5597 "Error when retrieving output stream latency: %d", result);
5598 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005599 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005600 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005601 track->presentationComplete(framesWritten, audioHALFrames);
5602 track->reset();
5603 tracksToRemove->add(track);
5604 }
5605 } else {
5606 // No buffers for this track. Give it a few chances to
5607 // fill a buffer, then remove it from active list.
5608 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005609 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005610 uint64_t position = 0;
5611 struct timespec unused;
5612 // The running check restarts the retry counter at least once.
5613 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5614 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5615 running = true;
5616 mOffloadUnderrunPosition = position;
5617 }
5618 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005619 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5620 (long long)position, (long long)mOffloadUnderrunPosition);
5621 }
5622 if (running) { // still running, give us more time.
5623 track->mRetryCount = kMaxTrackRetriesOffload;
5624 } else {
5625 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5626 track->name());
5627 tracksToRemove->add(track);
5628 // indicate to client process that the track was disabled because of underrun;
5629 // it will then automatically call start() when data is available
5630 track->disable();
5631 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005632 } else if (last){
5633 mixerStatus = MIXER_TRACKS_ENABLED;
5634 }
5635 }
5636 }
5637 // compute volume for this track
5638 processVolume_l(track, last);
5639 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005640
Eric Laurentea0fade2013-10-04 16:23:48 -07005641 // make sure the pause/flush/resume sequence is executed in the right order.
5642 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5643 // before flush and then resume HW. This can happen in case of pause/flush/resume
5644 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005645 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005646 status_t result = mOutput->stream->pause();
5647 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005648 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005649 if (mFlushPending) {
5650 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005651 }
Eric Laurentfd477972013-10-25 18:10:40 -07005652 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005653 status_t result = mOutput->stream->resume();
5654 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005655 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005656
Eric Laurentbfb1b832013-01-07 09:53:42 -08005657 // remove all the tracks that need to be...
5658 removeTracks_l(*tracksToRemove);
5659
5660 return mixerStatus;
5661}
5662
Eric Laurentbfb1b832013-01-07 09:53:42 -08005663// must be called with thread mutex locked
5664bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5665{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005666 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5667 mWriteAckSequence, mDrainSequence);
5668 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005669 return true;
5670 }
5671 return false;
5672}
5673
Eric Laurentbfb1b832013-01-07 09:53:42 -08005674bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5675{
5676 Mutex::Autolock _l(mLock);
5677 return waitingAsyncCallback_l();
5678}
5679
5680void AudioFlinger::OffloadThread::flushHw_l()
5681{
Eric Laurente659ef42014-09-29 13:06:46 -07005682 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005683 // Flush anything still waiting in the mixbuffer
5684 mCurrentWriteLength = 0;
5685 mBytesRemaining = 0;
5686 mPausedWriteLength = 0;
5687 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005688 // reset bytes written count to reflect that DSP buffers are empty after flush.
5689 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005690 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005691
Eric Laurentbfb1b832013-01-07 09:53:42 -08005692 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005693 // discard any pending drain or write ack by incrementing sequence
5694 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5695 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005696 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005697 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5698 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005699 }
5700}
5701
Haynes Mathew George05317d22016-05-03 16:34:26 -07005702void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5703{
5704 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005705 if (PlaybackThread::invalidateTracks_l(streamType)) {
5706 mFlushPending = true;
5707 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005708}
5709
Eric Laurentbfb1b832013-01-07 09:53:42 -08005710// ----------------------------------------------------------------------------
5711
Eric Laurent81784c32012-11-19 14:55:58 -08005712AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005713 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005714 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005715 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005716 mWaitTimeMs(UINT_MAX)
5717{
5718 addOutputTrack(mainThread);
5719}
5720
5721AudioFlinger::DuplicatingThread::~DuplicatingThread()
5722{
5723 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5724 mOutputTracks[i]->destroy();
5725 }
5726}
5727
5728void AudioFlinger::DuplicatingThread::threadLoop_mix()
5729{
5730 // mix buffers...
5731 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005732 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005733 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005734 if (mMixerBufferValid) {
5735 memset(mMixerBuffer, 0, mMixerBufferSize);
5736 } else {
5737 memset(mSinkBuffer, 0, mSinkBufferSize);
5738 }
Eric Laurent81784c32012-11-19 14:55:58 -08005739 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005740 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005741 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005742 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005743 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005744}
5745
5746void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5747{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005748 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005749 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005750 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005751 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005752 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005753 }
5754 } else if (mBytesWritten != 0) {
5755 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5756 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005757 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005758 } else {
5759 // flush remaining overflow buffers in output tracks
5760 writeFrames = 0;
5761 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005762 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005763 }
5764}
5765
Eric Laurentbfb1b832013-01-07 09:53:42 -08005766ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005767{
5768 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005769 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005770 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005771 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005772 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005773}
5774
5775void AudioFlinger::DuplicatingThread::threadLoop_standby()
5776{
5777 // DuplicatingThread implements standby by stopping all tracks
5778 for (size_t i = 0; i < outputTracks.size(); i++) {
5779 outputTracks[i]->stop();
5780 }
5781}
5782
5783void AudioFlinger::DuplicatingThread::saveOutputTracks()
5784{
5785 outputTracks = mOutputTracks;
5786}
5787
5788void AudioFlinger::DuplicatingThread::clearOutputTracks()
5789{
5790 outputTracks.clear();
5791}
5792
5793void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5794{
5795 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005796 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5797 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5798 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5799 const size_t frameCount =
5800 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5801 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5802 // from different OutputTracks and their associated MixerThreads (e.g. one may
5803 // nearly empty and the other may be dropping data).
5804
5805 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005806 this,
5807 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005808 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005809 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005810 frameCount,
5811 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005812 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5813 if (status != NO_ERROR) {
5814 ALOGE("addOutputTrack() initCheck failed %d", status);
5815 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005816 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005817 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5818 mOutputTracks.add(outputTrack);
5819 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5820 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005821}
5822
5823void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5824{
5825 Mutex::Autolock _l(mLock);
5826 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5827 if (mOutputTracks[i]->thread() == thread) {
5828 mOutputTracks[i]->destroy();
5829 mOutputTracks.removeAt(i);
5830 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005831 if (thread->getOutput() == mOutput) {
5832 mOutput = NULL;
5833 }
Eric Laurent81784c32012-11-19 14:55:58 -08005834 return;
5835 }
5836 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005837 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005838}
5839
5840// caller must hold mLock
5841void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5842{
5843 mWaitTimeMs = UINT_MAX;
5844 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5845 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5846 if (strong != 0) {
5847 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5848 if (waitTimeMs < mWaitTimeMs) {
5849 mWaitTimeMs = waitTimeMs;
5850 }
5851 }
5852 }
5853}
5854
5855
5856bool AudioFlinger::DuplicatingThread::outputsReady(
5857 const SortedVector< sp<OutputTrack> > &outputTracks)
5858{
5859 for (size_t i = 0; i < outputTracks.size(); i++) {
5860 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5861 if (thread == 0) {
5862 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5863 outputTracks[i].get());
5864 return false;
5865 }
5866 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5867 // see note at standby() declaration
5868 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5869 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5870 thread.get());
5871 return false;
5872 }
5873 }
5874 return true;
5875}
5876
5877uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5878{
5879 return (mWaitTimeMs * 1000) / 2;
5880}
5881
5882void AudioFlinger::DuplicatingThread::cacheParameters_l()
5883{
5884 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5885 updateWaitTime_l();
5886
5887 MixerThread::cacheParameters_l();
5888}
5889
5890// ----------------------------------------------------------------------------
5891// Record
5892// ----------------------------------------------------------------------------
5893
5894AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5895 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005896 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005897 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005898 audio_devices_t inDevice,
5899 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005900#ifdef TEE_SINK
5901 , const sp<NBAIO_Sink>& teeSink
5902#endif
5903 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005904 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005905 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005906 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005907 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005908#ifdef TEE_SINK
5909 , mTeeSink(teeSink)
5910#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005911 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5912 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005913 // mFastCapture below
5914 , mFastCaptureFutex(0)
5915 // mInputSource
5916 // mPipeSink
5917 // mPipeSource
5918 , mPipeFramesP2(0)
5919 // mPipeMemory
5920 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005921 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005922{
Glenn Kastend7dca052015-03-05 16:05:54 -08005923 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5924 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005925
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005926 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005927
5928 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005929 mInputSource = new AudioStreamInSource(
5930 static_cast<StreamInHalLocal*>(input->stream.get())->getStream());
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005931 size_t numCounterOffers = 0;
5932 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005933#if !LOG_NDEBUG
5934 ssize_t index =
5935#else
5936 (void)
5937#endif
5938 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005939 ALOG_ASSERT(index == 0);
5940
5941 // initialize fast capture depending on configuration
5942 bool initFastCapture;
5943 switch (kUseFastCapture) {
5944 case FastCapture_Never:
5945 initFastCapture = false;
5946 break;
5947 case FastCapture_Always:
5948 initFastCapture = true;
5949 break;
5950 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005951 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005952 break;
5953 // case FastCapture_Dynamic:
5954 }
5955
5956 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005957 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005958 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005959 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5960 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005961 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5962 void *pipeBuffer;
5963 const sp<MemoryDealer> roHeap(readOnlyHeap());
5964 sp<IMemory> pipeMemory;
5965 if ((roHeap == 0) ||
5966 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5967 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5968 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5969 goto failed;
5970 }
5971 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5972 memset(pipeBuffer, 0, pipeSize);
5973 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5974 const NBAIO_Format offers[1] = {format};
5975 size_t numCounterOffers = 0;
5976 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5977 ALOG_ASSERT(index == 0);
5978 mPipeSink = pipe;
5979 PipeReader *pipeReader = new PipeReader(*pipe);
5980 numCounterOffers = 0;
5981 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5982 ALOG_ASSERT(index == 0);
5983 mPipeSource = pipeReader;
5984 mPipeFramesP2 = pipeFramesP2;
5985 mPipeMemory = pipeMemory;
5986
5987 // create fast capture
5988 mFastCapture = new FastCapture();
5989 FastCaptureStateQueue *sq = mFastCapture->sq();
5990#ifdef STATE_QUEUE_DUMP
5991 // FIXME
5992#endif
5993 FastCaptureState *state = sq->begin();
5994 state->mCblk = NULL;
5995 state->mInputSource = mInputSource.get();
5996 state->mInputSourceGen++;
5997 state->mPipeSink = pipe;
5998 state->mPipeSinkGen++;
5999 state->mFrameCount = mFrameCount;
6000 state->mCommand = FastCaptureState::COLD_IDLE;
6001 // already done in constructor initialization list
6002 //mFastCaptureFutex = 0;
6003 state->mColdFutexAddr = &mFastCaptureFutex;
6004 state->mColdGen++;
6005 state->mDumpState = &mFastCaptureDumpState;
6006#ifdef TEE_SINK
6007 // FIXME
6008#endif
6009 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6010 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6011 sq->end();
6012 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6013
6014 // start the fast capture
6015 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6016 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07006017 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006018#ifdef AUDIO_WATCHDOG
6019 // FIXME
6020#endif
6021
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006022 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006023 }
6024failed: ;
6025
6026 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006027}
6028
Eric Laurent81784c32012-11-19 14:55:58 -08006029AudioFlinger::RecordThread::~RecordThread()
6030{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006031 if (mFastCapture != 0) {
6032 FastCaptureStateQueue *sq = mFastCapture->sq();
6033 FastCaptureState *state = sq->begin();
6034 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6035 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6036 if (old == -1) {
6037 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6038 }
6039 }
6040 state->mCommand = FastCaptureState::EXIT;
6041 sq->end();
6042 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6043 mFastCapture->join();
6044 mFastCapture.clear();
6045 }
6046 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006047 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006048 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006049}
6050
6051void AudioFlinger::RecordThread::onFirstRef()
6052{
Glenn Kastend7dca052015-03-05 16:05:54 -08006053 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006054}
6055
Eric Laurent81784c32012-11-19 14:55:58 -08006056bool AudioFlinger::RecordThread::threadLoop()
6057{
Eric Laurent81784c32012-11-19 14:55:58 -08006058 nsecs_t lastWarning = 0;
6059
6060 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006061
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006062reacquire_wakelock:
6063 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08006064 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006065 {
6066 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006067 size_t size = mActiveTracks.size();
6068 activeTracksGen = mActiveTracksGen;
6069 if (size > 0) {
6070 // FIXME an arbitrary choice
6071 activeTrack = mActiveTracks[0];
6072 acquireWakeLock_l(activeTrack->uid());
6073 if (size > 1) {
6074 SortedVector<int> tmp;
6075 for (size_t i = 0; i < size; i++) {
6076 tmp.add(mActiveTracks[i]->uid());
6077 }
6078 updateWakeLockUids_l(tmp);
6079 }
6080 } else {
6081 acquireWakeLock_l(-1);
6082 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006083 }
6084
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006085 // used to request a deferred sleep, to be executed later while mutex is unlocked
6086 uint32_t sleepUs = 0;
6087
6088 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006089 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006090 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006091
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006092 // activeTracks accumulates a copy of a subset of mActiveTracks
6093 Vector< sp<RecordTrack> > activeTracks;
6094
Glenn Kasten735f45f2014-08-18 15:51:59 -07006095 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006096 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006097
Glenn Kasten735f45f2014-08-18 15:51:59 -07006098 // reference to a fast track which is about to be removed
6099 sp<RecordTrack> fastTrackToRemove;
6100
Eric Laurent81784c32012-11-19 14:55:58 -08006101 { // scope for mLock
6102 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006103
Eric Laurent021cf962014-05-13 10:18:14 -07006104 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006105
Eric Laurent000a4192014-01-29 15:17:32 -08006106 // check exitPending here because checkForNewParameters_l() and
6107 // checkForNewParameters_l() can temporarily release mLock
6108 if (exitPending()) {
6109 break;
6110 }
6111
Eric Laurent5c25d562016-07-13 17:17:45 -07006112 // sleep with mutex unlocked
6113 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006114 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006115 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6116 ATRACE_END();
6117 sleepUs = 0;
6118 continue;
6119 }
6120
Glenn Kasten2b806402013-11-20 16:37:38 -08006121 // if no active track(s), then standby and release wakelock
6122 size_t size = mActiveTracks.size();
6123 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006124 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006125 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006126 releaseWakeLock_l();
6127 ALOGV("RecordThread: loop stopping");
6128 // go to sleep
6129 mWaitWorkCV.wait(mLock);
6130 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006131 goto reacquire_wakelock;
6132 }
6133
Glenn Kasten2b806402013-11-20 16:37:38 -08006134 if (mActiveTracksGen != activeTracksGen) {
6135 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006136 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006137 for (size_t i = 0; i < size; i++) {
6138 tmp.add(mActiveTracks[i]->uid());
6139 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006140 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006141 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006142
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006143 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006144 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006145 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006146
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006147 activeTrack = mActiveTracks[i];
6148 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006149 if (activeTrack->isFastTrack()) {
6150 ALOG_ASSERT(fastTrackToRemove == 0);
6151 fastTrackToRemove = activeTrack;
6152 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006153 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006154 mActiveTracks.remove(activeTrack);
6155 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006156 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006157 continue;
6158 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006159
6160 TrackBase::track_state activeTrackState = activeTrack->mState;
6161 switch (activeTrackState) {
6162
6163 case TrackBase::PAUSING:
6164 mActiveTracks.remove(activeTrack);
6165 mActiveTracksGen++;
6166 doBroadcast = true;
6167 size--;
6168 continue;
6169
6170 case TrackBase::STARTING_1:
6171 sleepUs = 10000;
6172 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006173 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006174 continue;
6175
6176 case TrackBase::STARTING_2:
6177 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006178 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006179 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006180 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006181 break;
6182
6183 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006184 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185 break;
6186
6187 case TrackBase::IDLE:
6188 i++;
6189 continue;
6190
6191 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006192 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006193 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006194
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006195 activeTracks.add(activeTrack);
6196 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006197
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006198 if (activeTrack->isFastTrack()) {
6199 ALOG_ASSERT(!mFastTrackAvail);
6200 ALOG_ASSERT(fastTrack == 0);
6201 fastTrack = activeTrack;
6202 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006203 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006204
6205 if (allStopped) {
6206 standbyIfNotAlreadyInStandby();
6207 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006208 if (doBroadcast) {
6209 mStartStopCond.broadcast();
6210 }
6211
6212 // sleep if there are no active tracks to process
6213 if (activeTracks.size() == 0) {
6214 if (sleepUs == 0) {
6215 sleepUs = kRecordThreadSleepUs;
6216 }
6217 continue;
6218 }
6219 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006220
Eric Laurent81784c32012-11-19 14:55:58 -08006221 lockEffectChains_l(effectChains);
6222 }
6223
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006224 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006225
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006226 size_t size = effectChains.size();
6227 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006228 // thread mutex is not locked, but effect chain is locked
6229 effectChains[i]->process_l();
6230 }
6231
Glenn Kasten735f45f2014-08-18 15:51:59 -07006232 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006233 if (mFastCapture != 0) {
6234 FastCaptureStateQueue *sq = mFastCapture->sq();
6235 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006236 bool didModify = false;
6237 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006238 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6239 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6240 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6241 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6242 if (old == -1) {
6243 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6244 }
6245 }
6246 state->mCommand = FastCaptureState::READ_WRITE;
6247#if 0 // FIXME
6248 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006249 FastThreadDumpState::kSamplingNforLowRamDevice :
6250 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006251#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006252 didModify = true;
6253 }
6254 audio_track_cblk_t *cblkOld = state->mCblk;
6255 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6256 if (cblkNew != cblkOld) {
6257 state->mCblk = cblkNew;
6258 // block until acked if removing a fast track
6259 if (cblkOld != NULL) {
6260 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6261 }
6262 didModify = true;
6263 }
6264 sq->end(didModify);
6265 if (didModify) {
6266 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006267#if 0
6268 if (kUseFastCapture == FastCapture_Dynamic) {
6269 mNormalSource = mPipeSource;
6270 }
6271#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006272 }
6273 }
6274
Glenn Kasten735f45f2014-08-18 15:51:59 -07006275 // now run the fast track destructor with thread mutex unlocked
6276 fastTrackToRemove.clear();
6277
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006278 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6279 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6280 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6281 // If destination is non-contiguous, first read past the nominal end of buffer, then
6282 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006283
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006284 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006285 ssize_t framesRead;
6286
6287 // If an NBAIO source is present, use it to read the normal capture's data
6288 if (mPipeSource != 0) {
6289 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006290 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006291 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006292 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006293 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6294 // buffer size or at least for 20ms.
6295 size_t sleepFrames = max(
6296 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6297 if (framesRead <= (ssize_t) sleepFrames) {
6298 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6299 }
6300 if (framesRead < 0) {
6301 status_t status = (status_t) framesRead;
6302 switch (status) {
6303 case OVERRUN:
6304 ALOGW("overrun on read from pipe");
6305 framesRead = 0;
6306 break;
6307 case NEGOTIATE:
6308 ALOGE("re-negotiation is needed");
6309 framesRead = -1; // Will cause an attempt to recover.
6310 break;
6311 default:
6312 ALOGE("unknown error %d on read from pipe", status);
6313 break;
6314 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006315 }
6316 // otherwise use the HAL / AudioStreamIn directly
6317 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006318 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006319 size_t bytesRead;
6320 status_t result = mInput->stream->read(
6321 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006322 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006323 if (result < 0) {
6324 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006325 } else {
6326 framesRead = bytesRead / mFrameSize;
6327 }
6328 }
6329
Andy Hung3f0c9022016-01-15 17:49:46 -08006330 // Update server timestamp with server stats
6331 // systemTime() is optional if the hardware supports timestamps.
6332 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6333 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6334
6335 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006336 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006337 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006338 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006339 if (ret == NO_ERROR) {
6340 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6341 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6342 // Note: In general record buffers should tend to be empty in
6343 // a properly running pipeline.
6344 //
6345 // Also, it is not advantageous to call get_presentation_position during the read
6346 // as the read obtains a lock, preventing the timestamp call from executing.
6347 }
6348 }
6349 // Use this to track timestamp information
6350 // ALOGD("%s", mTimestamp.toString().c_str());
6351
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006352 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006353 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006354 // Force input into standby so that it tries to recover at next read attempt
6355 inputStandBy();
6356 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006357 }
6358 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006359 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006360 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006361 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006362
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006363 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006364 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006365 }
6366 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006367 {
6368 size_t part1 = mRsmpInFramesP2 - rear;
6369 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006370 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006371 (framesRead - part1) * mFrameSize);
6372 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006373 }
6374 rear = mRsmpInRear += framesRead;
6375
6376 size = activeTracks.size();
6377 // loop over each active track
6378 for (size_t i = 0; i < size; i++) {
6379 activeTrack = activeTracks[i];
6380
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006381 // skip fast tracks, as those are handled directly by FastCapture
6382 if (activeTrack->isFastTrack()) {
6383 continue;
6384 }
6385
Andy Hung73c02e42015-03-29 01:13:58 -07006386 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006387 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6388
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006389 enum {
6390 OVERRUN_UNKNOWN,
6391 OVERRUN_TRUE,
6392 OVERRUN_FALSE
6393 } overrun = OVERRUN_UNKNOWN;
6394
6395 // loop over getNextBuffer to handle circular sink
6396 for (;;) {
6397
6398 activeTrack->mSink.frameCount = ~0;
6399 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6400 size_t framesOut = activeTrack->mSink.frameCount;
6401 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6402
Andy Hung73c02e42015-03-29 01:13:58 -07006403 // check available frames and handle overrun conditions
6404 // if the record track isn't draining fast enough.
6405 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006406 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006407 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6408 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006409 overrun = OVERRUN_TRUE;
6410 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006411 if (framesOut == 0 || framesIn == 0) {
6412 break;
6413 }
6414
Andy Hung6770c6f2015-04-07 13:43:36 -07006415 // Don't allow framesOut to be larger than what is possible with resampling
6416 // from framesIn.
6417 // This isn't strictly necessary but helps limit buffer resizing in
6418 // RecordBufferConverter. TODO: remove when no longer needed.
6419 framesOut = min(framesOut,
6420 destinationFramesPossible(
6421 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006422 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6423 framesOut = activeTrack->mRecordBufferConverter->convert(
6424 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006425
6426 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6427 overrun = OVERRUN_FALSE;
6428 }
6429
6430 if (activeTrack->mFramesToDrop == 0) {
6431 if (framesOut > 0) {
6432 activeTrack->mSink.frameCount = framesOut;
6433 activeTrack->releaseBuffer(&activeTrack->mSink);
6434 }
6435 } else {
6436 // FIXME could do a partial drop of framesOut
6437 if (activeTrack->mFramesToDrop > 0) {
6438 activeTrack->mFramesToDrop -= framesOut;
6439 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006440 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006441 }
6442 } else {
6443 activeTrack->mFramesToDrop += framesOut;
6444 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6445 activeTrack->mSyncStartEvent->isCancelled()) {
6446 ALOGW("Synced record %s, session %d, trigger session %d",
6447 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6448 activeTrack->sessionId(),
6449 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006450 activeTrack->mSyncStartEvent->triggerSession() :
6451 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006452 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006453 }
6454 }
6455 }
6456
6457 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006458 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006459 }
6460 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006461
6462 switch (overrun) {
6463 case OVERRUN_TRUE:
6464 // client isn't retrieving buffers fast enough
6465 if (!activeTrack->setOverflow()) {
6466 nsecs_t now = systemTime();
6467 // FIXME should lastWarning per track?
6468 if ((now - lastWarning) > kWarningThrottleNs) {
6469 ALOGW("RecordThread: buffer overflow");
6470 lastWarning = now;
6471 }
6472 }
6473 break;
6474 case OVERRUN_FALSE:
6475 activeTrack->clearOverflow();
6476 break;
6477 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006478 break;
6479 }
6480
Andy Hung3f0c9022016-01-15 17:49:46 -08006481 // update frame information and push timestamp out
6482 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006483 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006484 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6485 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006486 }
6487
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006488unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006489 // enable changes in effect chain
6490 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006491 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006492 }
6493
Glenn Kasten93e471f2013-08-19 08:40:07 -07006494 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006495
6496 {
6497 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006498 for (size_t i = 0; i < mTracks.size(); i++) {
6499 sp<RecordTrack> track = mTracks[i];
6500 track->invalidate();
6501 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006502 mActiveTracks.clear();
6503 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006504 mStartStopCond.broadcast();
6505 }
6506
6507 releaseWakeLock();
6508
6509 ALOGV("RecordThread %p exiting", this);
6510 return false;
6511}
6512
Glenn Kasten93e471f2013-08-19 08:40:07 -07006513void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006514{
6515 if (!mStandby) {
6516 inputStandBy();
6517 mStandby = true;
6518 }
6519}
6520
6521void AudioFlinger::RecordThread::inputStandBy()
6522{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006523 // Idle the fast capture if it's currently running
6524 if (mFastCapture != 0) {
6525 FastCaptureStateQueue *sq = mFastCapture->sq();
6526 FastCaptureState *state = sq->begin();
6527 if (!(state->mCommand & FastCaptureState::IDLE)) {
6528 state->mCommand = FastCaptureState::COLD_IDLE;
6529 state->mColdFutexAddr = &mFastCaptureFutex;
6530 state->mColdGen++;
6531 mFastCaptureFutex = 0;
6532 sq->end();
6533 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6534 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6535#if 0
6536 if (kUseFastCapture == FastCapture_Dynamic) {
6537 // FIXME
6538 }
6539#endif
6540#ifdef AUDIO_WATCHDOG
6541 // FIXME
6542#endif
6543 } else {
6544 sq->end(false /*didModify*/);
6545 }
6546 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006547 status_t result = mInput->stream->standby();
6548 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006549
6550 // If going into standby, flush the pipe source.
6551 if (mPipeSource.get() != nullptr) {
6552 const ssize_t flushed = mPipeSource->flush();
6553 if (flushed > 0) {
6554 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6555 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6556 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6557 }
6558 }
Eric Laurent81784c32012-11-19 14:55:58 -08006559}
6560
Glenn Kasten05997e22014-03-13 15:08:33 -07006561// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006562sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006563 const sp<AudioFlinger::Client>& client,
6564 uint32_t sampleRate,
6565 audio_format_t format,
6566 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006567 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006568 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006569 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006570 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006571 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006572 pid_t tid,
6573 status_t *status)
6574{
Glenn Kasten74935e42013-12-19 08:56:45 -08006575 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006576 sp<RecordTrack> track;
6577 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006578 audio_input_flags_t inputFlags = mInput->flags;
6579
6580 // special case for FAST flag considered OK if fast capture is present
6581 if (hasFastCapture()) {
6582 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6583 }
6584
6585 // Check if requested flags are compatible with output stream flags
6586 if ((*flags & inputFlags) != *flags) {
6587 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6588 " input flags (%08x)",
6589 *flags, inputFlags);
6590 *flags = (audio_input_flags_t)(*flags & inputFlags);
6591 }
Eric Laurent81784c32012-11-19 14:55:58 -08006592
Glenn Kasten90e58b12013-07-31 16:16:02 -07006593 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006594 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006595 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006596 // we formerly checked for a callback handler (non-0 tid),
6597 // but that is no longer required for TRANSFER_OBTAIN mode
6598 //
Glenn Kasten74105912014-07-03 12:28:53 -07006599 // frame count is not specified, or is exactly the pipe depth
6600 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006601 // PCM data
6602 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006603 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006604 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006605 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006606 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006607 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006608 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006609 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006610 hasFastCapture() &&
6611 // there are sufficient fast track slots available
6612 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006613 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006614 // check compatibility with audio effects.
6615 Mutex::Autolock _l(mLock);
6616 // Do not accept FAST flag if the session has software effects
6617 sp<EffectChain> chain = getEffectChain_l(sessionId);
6618 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07006619 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006620 "AUDIO_INPUT_FLAG_RAW denied: effect present on session");
6621 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
6622 if (chain->hasSoftwareEffect()) {
6623 ALOGV("AUDIO_INPUT_FLAG_FAST denied: software effect present on session");
6624 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
6625 }
6626 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006627 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006628 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6629 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006630 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006631 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006632 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006633 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006634 frameCount, mFrameCount, mPipeFramesP2,
6635 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6636 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006637 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006638 }
6639 }
6640
6641 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006642 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006643 // fast track: frame count is exactly the pipe depth
6644 frameCount = mPipeFramesP2;
6645 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6646 *notificationFrames = mFrameCount;
6647 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006648 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6649 // or 20 ms if there is a fast capture
6650 // TODO This could be a roundupRatio inline, and const
6651 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6652 * sampleRate + mSampleRate - 1) / mSampleRate;
6653 // minimum number of notification periods is at least kMinNotifications,
6654 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6655 static const size_t kMinNotifications = 3;
6656 static const uint32_t kMinMs = 30;
6657 // TODO This could be a roundupRatio inline
6658 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6659 // TODO This could be a roundupRatio inline
6660 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6661 maxNotificationFrames;
6662 const size_t minFrameCount = maxNotificationFrames *
6663 max(kMinNotifications, minNotificationsByMs);
6664 frameCount = max(frameCount, minFrameCount);
6665 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6666 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006667 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006668 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006669 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006670
Glenn Kasten15e57982013-09-24 11:52:37 -07006671 lStatus = initCheck();
6672 if (lStatus != NO_ERROR) {
6673 ALOGE("createRecordTrack_l() audio driver not initialized");
6674 goto Exit;
6675 }
Eric Laurent81784c32012-11-19 14:55:58 -08006676
6677 { // scope for mLock
6678 Mutex::Autolock _l(mLock);
6679
6680 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006681 format, channelMask, frameCount, NULL, sessionId, uid,
6682 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006683
Glenn Kasten03003332013-08-06 15:40:54 -07006684 lStatus = track->initCheck();
6685 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006686 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006687 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006688 goto Exit;
6689 }
6690 mTracks.add(track);
6691
6692 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6693 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6694 mAudioFlinger->btNrecIsOff();
6695 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6696 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006697
Eric Laurent05067782016-06-01 18:27:28 -07006698 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006699 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6700 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6701 // so ask activity manager to do this on our behalf
6702 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6703 }
Eric Laurent81784c32012-11-19 14:55:58 -08006704 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006705
Eric Laurent81784c32012-11-19 14:55:58 -08006706 lStatus = NO_ERROR;
6707
6708Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006709 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006710 return track;
6711}
6712
6713status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6714 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006715 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006716{
6717 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6718 sp<ThreadBase> strongMe = this;
6719 status_t status = NO_ERROR;
6720
6721 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006722 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006723 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006724 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006725 triggerSession,
6726 recordTrack->sessionId(),
6727 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006728 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006729 // Sync event can be cancelled by the trigger session if the track is not in a
6730 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006731 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006732 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006733 } else {
6734 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006735 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006736 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006737 }
6738 }
6739
6740 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006741 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006742 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006743 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6744 if (recordTrack->mState == TrackBase::PAUSING) {
6745 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006746 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006747 } else {
6748 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006749 }
6750 return status;
6751 }
6752
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006753 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6754 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6755 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006756 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006757 mActiveTracks.add(recordTrack);
6758 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006759 status_t status = NO_ERROR;
6760 if (recordTrack->isExternalTrack()) {
6761 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006762 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006763 mLock.lock();
6764 // FIXME should verify that recordTrack is still in mActiveTracks
6765 if (status != NO_ERROR) {
6766 mActiveTracks.remove(recordTrack);
6767 mActiveTracksGen++;
6768 recordTrack->clearSyncStartEvent();
6769 ALOGV("RecordThread::start error %d", status);
6770 return status;
6771 }
Eric Laurent81784c32012-11-19 14:55:58 -08006772 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006773 // Catch up with current buffer indices if thread is already running.
6774 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6775 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6776 // see previously buffered data before it called start(), but with greater risk of overrun.
6777
Andy Hung73c02e42015-03-29 01:13:58 -07006778 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006779 // clear any converter state as new data will be discontinuous
6780 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006781 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006782 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006783 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006784 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006785 ALOGV("Record failed to start");
6786 status = BAD_VALUE;
6787 goto startError;
6788 }
Eric Laurent81784c32012-11-19 14:55:58 -08006789 return status;
6790 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006791
Eric Laurent81784c32012-11-19 14:55:58 -08006792startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006793 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006794 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006795 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006796 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006797 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006798 return status;
6799}
6800
Eric Laurent81784c32012-11-19 14:55:58 -08006801void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6802{
6803 sp<SyncEvent> strongEvent = event.promote();
6804
6805 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006806 sp<RefBase> ptr = strongEvent->cookie().promote();
6807 if (ptr != 0) {
6808 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6809 recordTrack->handleSyncStartEvent(strongEvent);
6810 }
Eric Laurent81784c32012-11-19 14:55:58 -08006811 }
6812}
6813
Glenn Kastena8356f62013-07-25 14:37:52 -07006814bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006815 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006816 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006817 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006818 return false;
6819 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006820 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006821 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006822 // signal thread to stop
6823 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006824 // do not wait for mStartStopCond if exiting
6825 if (exitPending()) {
6826 return true;
6827 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006828 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006829 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006830 // if we have been restarted, recordTrack is in mActiveTracks here
6831 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006832 ALOGV("Record stopped OK");
6833 return true;
6834 }
6835 return false;
6836}
6837
Glenn Kasten0f11b512014-01-31 16:18:54 -08006838bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006839{
6840 return false;
6841}
6842
Glenn Kasten0f11b512014-01-31 16:18:54 -08006843status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006844{
6845#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6846 if (!isValidSyncEvent(event)) {
6847 return BAD_VALUE;
6848 }
6849
Glenn Kastend848eb42016-03-08 13:42:11 -08006850 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006851 status_t ret = NAME_NOT_FOUND;
6852
6853 Mutex::Autolock _l(mLock);
6854
6855 for (size_t i = 0; i < mTracks.size(); i++) {
6856 sp<RecordTrack> track = mTracks[i];
6857 if (eventSession == track->sessionId()) {
6858 (void) track->setSyncEvent(event);
6859 ret = NO_ERROR;
6860 }
6861 }
6862 return ret;
6863#else
6864 return BAD_VALUE;
6865#endif
6866}
6867
6868// destroyTrack_l() must be called with ThreadBase::mLock held
6869void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6870{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006871 track->terminate();
6872 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006873 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006874 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006875 removeTrack_l(track);
6876 }
6877}
6878
6879void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6880{
6881 mTracks.remove(track);
6882 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006883 if (track->isFastTrack()) {
6884 ALOG_ASSERT(!mFastTrackAvail);
6885 mFastTrackAvail = true;
6886 }
Eric Laurent81784c32012-11-19 14:55:58 -08006887}
6888
6889void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6890{
6891 dumpInternals(fd, args);
6892 dumpTracks(fd, args);
6893 dumpEffectChains(fd, args);
6894}
6895
6896void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6897{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006898 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006899
Glenn Kasten44182c22015-03-05 17:12:23 -08006900 dumpBase(fd, args);
6901
6902 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006903 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006904 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006905 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006906 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006907
Glenn Kasten2f90c512015-12-02 11:40:09 -08006908 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6909 // while we are dumping it. It may be inconsistent, but it won't mutate!
6910 // This is a large object so we place it on the heap.
6911 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6912 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6913 copy->dump(fd);
6914 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006915}
6916
Glenn Kasten0f11b512014-01-31 16:18:54 -08006917void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006918{
6919 const size_t SIZE = 256;
6920 char buffer[SIZE];
6921 String8 result;
6922
Marco Nelissenb2208842014-02-07 14:00:50 -08006923 size_t numtracks = mTracks.size();
6924 size_t numactive = mActiveTracks.size();
6925 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006926 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006927 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006928 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006929 RecordTrack::appendDumpHeader(result);
6930 for (size_t i = 0; i < numtracks ; ++i) {
6931 sp<RecordTrack> track = mTracks[i];
6932 if (track != 0) {
6933 bool active = mActiveTracks.indexOf(track) >= 0;
6934 if (active) {
6935 numactiveseen++;
6936 }
6937 track->dump(buffer, SIZE, active);
6938 result.append(buffer);
6939 }
Eric Laurent81784c32012-11-19 14:55:58 -08006940 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006941 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006942 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006943 }
6944
Marco Nelissenb2208842014-02-07 14:00:50 -08006945 if (numactiveseen != numactive) {
6946 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6947 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006948 result.append(buffer);
6949 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006950 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006951 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006952 if (mTracks.indexOf(track) < 0) {
6953 track->dump(buffer, SIZE, true);
6954 result.append(buffer);
6955 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006956 }
Eric Laurent81784c32012-11-19 14:55:58 -08006957
6958 }
6959 write(fd, result.string(), result.size());
6960}
6961
Andy Hung73c02e42015-03-29 01:13:58 -07006962
6963void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6964{
6965 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6966 RecordThread *recordThread = (RecordThread *) threadBase.get();
6967 mRsmpInFront = recordThread->mRsmpInRear;
6968 mRsmpInUnrel = 0;
6969}
6970
6971void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6972 size_t *framesAvailable, bool *hasOverrun)
6973{
6974 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6975 RecordThread *recordThread = (RecordThread *) threadBase.get();
6976 const int32_t rear = recordThread->mRsmpInRear;
6977 const int32_t front = mRsmpInFront;
6978 const ssize_t filled = rear - front;
6979
6980 size_t framesIn;
6981 bool overrun = false;
6982 if (filled < 0) {
6983 // should not happen, but treat like a massive overrun and re-sync
6984 framesIn = 0;
6985 mRsmpInFront = rear;
6986 overrun = true;
6987 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6988 framesIn = (size_t) filled;
6989 } else {
6990 // client is not keeping up with server, but give it latest data
6991 framesIn = recordThread->mRsmpInFrames;
6992 mRsmpInFront = /* front = */ rear - framesIn;
6993 overrun = true;
6994 }
6995 if (framesAvailable != NULL) {
6996 *framesAvailable = framesIn;
6997 }
6998 if (hasOverrun != NULL) {
6999 *hasOverrun = overrun;
7000 }
7001}
7002
Eric Laurent81784c32012-11-19 14:55:58 -08007003// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007004status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007005 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007006{
Andy Hung73c02e42015-03-29 01:13:58 -07007007 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007008 if (threadBase == 0) {
7009 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007010 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007011 return NOT_ENOUGH_DATA;
7012 }
7013 RecordThread *recordThread = (RecordThread *) threadBase.get();
7014 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007015 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007016 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007017 // FIXME should not be P2 (don't want to increase latency)
7018 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007019 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007020 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007021 front &= recordThread->mRsmpInFramesP2 - 1;
7022 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007023 if (part1 > (size_t) filled) {
7024 part1 = filled;
7025 }
7026 size_t ask = buffer->frameCount;
7027 ALOG_ASSERT(ask > 0);
7028 if (part1 > ask) {
7029 part1 = ask;
7030 }
7031 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007032 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007033 buffer->raw = NULL;
7034 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007035 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007036 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007037 }
7038
Andy Hung57446612015-04-19 23:56:46 -07007039 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007040 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007041 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007042 return NO_ERROR;
7043}
7044
7045// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007046void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7047 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007048{
Glenn Kasten85948432013-08-19 12:09:05 -07007049 size_t stepCount = buffer->frameCount;
7050 if (stepCount == 0) {
7051 return;
7052 }
Andy Hung73c02e42015-03-29 01:13:58 -07007053 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7054 mRsmpInUnrel -= stepCount;
7055 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007056 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007057 buffer->frameCount = 0;
7058}
7059
Andy Hung97a893e2015-03-29 01:03:07 -07007060AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7061 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7062 uint32_t srcSampleRate,
7063 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7064 uint32_t dstSampleRate) :
7065 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7066 // mSrcFormat
7067 // mSrcSampleRate
7068 // mDstChannelMask
7069 // mDstFormat
7070 // mDstSampleRate
7071 // mSrcChannelCount
7072 // mDstChannelCount
7073 // mDstFrameSize
7074 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07007075 mResampler(NULL),
7076 mIsLegacyDownmix(false),
7077 mIsLegacyUpmix(false),
7078 mRequiresFloat(false),
7079 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007080{
7081 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7082 dstChannelMask, dstFormat, dstSampleRate);
7083}
7084
7085AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7086 free(mBuf);
7087 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007088 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007089}
7090
7091size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7092 AudioBufferProvider *provider, size_t frames)
7093{
Andy Hungd330ee42015-04-20 13:23:41 -07007094 if (mInputConverterProvider != NULL) {
7095 mInputConverterProvider->setBufferProvider(provider);
7096 provider = mInputConverterProvider;
7097 }
7098
7099 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007100 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7101 mSrcSampleRate, mSrcFormat, mDstFormat);
7102
7103 AudioBufferProvider::Buffer buffer;
7104 for (size_t i = frames; i > 0; ) {
7105 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007106 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007107 if (status != OK || buffer.frameCount == 0) {
7108 frames -= i; // cannot fill request.
7109 break;
7110 }
Andy Hungd330ee42015-04-20 13:23:41 -07007111 // format convert to destination buffer
7112 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007113
7114 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7115 i -= buffer.frameCount;
7116 provider->releaseBuffer(&buffer);
7117 }
7118 } else {
7119 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7120 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7121
Andy Hungd330ee42015-04-20 13:23:41 -07007122 // reallocate buffer if needed
7123 if (mBufFrameSize != 0 && mBufFrames < frames) {
7124 free(mBuf);
7125 mBufFrames = frames;
7126 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7127 }
Andy Hung97a893e2015-03-29 01:03:07 -07007128 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007129 memset(mBuf, 0, frames * mBufFrameSize);
7130 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7131 // format convert to destination buffer
7132 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007133 }
7134 return frames;
7135}
7136
7137status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7138 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7139 uint32_t srcSampleRate,
7140 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7141 uint32_t dstSampleRate)
7142{
7143 // quick evaluation if there is any change.
7144 if (mSrcFormat == srcFormat
7145 && mSrcChannelMask == srcChannelMask
7146 && mSrcSampleRate == srcSampleRate
7147 && mDstFormat == dstFormat
7148 && mDstChannelMask == dstChannelMask
7149 && mDstSampleRate == dstSampleRate) {
7150 return NO_ERROR;
7151 }
7152
Andy Hungdb4c0312015-05-06 08:46:52 -07007153 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7154 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7155 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007156 const bool valid =
7157 audio_is_input_channel(srcChannelMask)
7158 && audio_is_input_channel(dstChannelMask)
7159 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7160 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7161 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7162 ; // no upsampling checks for now
7163 if (!valid) {
7164 return BAD_VALUE;
7165 }
7166
7167 mSrcFormat = srcFormat;
7168 mSrcChannelMask = srcChannelMask;
7169 mSrcSampleRate = srcSampleRate;
7170 mDstFormat = dstFormat;
7171 mDstChannelMask = dstChannelMask;
7172 mDstSampleRate = dstSampleRate;
7173
7174 // compute derived parameters
7175 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7176 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7177 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7178
Andy Hungd330ee42015-04-20 13:23:41 -07007179 // do we need to resample?
7180 delete mResampler;
7181 mResampler = NULL;
7182 if (mSrcSampleRate != mDstSampleRate) {
7183 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7184 mSrcChannelCount, mDstSampleRate);
7185 mResampler->setSampleRate(mSrcSampleRate);
7186 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7187 }
7188
7189 // are we running legacy channel conversion modes?
7190 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7191 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7192 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7193 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7194 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7195 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7196
7197 // do we need to process in float?
7198 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7199
7200 // do we need a staging buffer to convert for destination (we can still optimize this)?
7201 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7202 if (mResampler != NULL) {
7203 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7204 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007205 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007206 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7207 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007208 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7209 } else {
7210 mBufFrameSize = 0;
7211 }
7212 mBufFrames = 0; // force the buffer to be resized.
7213
Andy Hungd330ee42015-04-20 13:23:41 -07007214 // do we need an input converter buffer provider to give us float?
7215 delete mInputConverterProvider;
7216 mInputConverterProvider = NULL;
7217 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7218 mInputConverterProvider = new ReformatBufferProvider(
7219 audio_channel_count_from_in_mask(mSrcChannelMask),
7220 mSrcFormat,
7221 AUDIO_FORMAT_PCM_FLOAT,
7222 256 /* provider buffer frame count */);
7223 }
7224
7225 // do we need a remixer to do channel mask conversion
7226 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7227 (void) memcpy_by_index_array_initialization_from_channel_mask(
7228 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007229 }
7230 return NO_ERROR;
7231}
7232
Andy Hungd330ee42015-04-20 13:23:41 -07007233void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7234 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007235{
Andy Hungd330ee42015-04-20 13:23:41 -07007236 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007237 if (mBufFrameSize != 0 && mBufFrames < frames) {
7238 free(mBuf);
7239 mBufFrames = frames;
7240 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7241 }
Andy Hungd330ee42015-04-20 13:23:41 -07007242 // do we need to do legacy upmix and downmix?
7243 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007244 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007245 if (mIsLegacyUpmix) {
7246 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7247 (const float *)src, frames);
7248 } else /*mIsLegacyDownmix */ {
7249 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7250 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007251 }
Andy Hungd330ee42015-04-20 13:23:41 -07007252 if (mBuf != NULL) {
7253 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7254 frames * mDstChannelCount);
7255 }
7256 return;
7257 }
7258 // do we need to do channel mask conversion?
7259 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007260 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007261 memcpy_by_index_array(dstBuf, mDstChannelCount,
7262 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7263 if (dstBuf == dst) {
7264 return; // format is the same
7265 }
7266 }
7267 // convert to destination buffer
7268 const void *convertBuf = mBuf != NULL ? mBuf : src;
7269 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7270 frames * mDstChannelCount);
7271}
7272
7273void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7274 void *dst, /*not-a-const*/ void *src, size_t frames)
7275{
7276 // src buffer format is ALWAYS float when entering this routine
7277 if (mIsLegacyUpmix) {
7278 ; // mono to stereo already handled by resampler
7279 } else if (mIsLegacyDownmix
7280 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7281 // the resampler outputs stereo for mono input channel (a feature?)
7282 // must convert to mono
7283 downmix_to_mono_float_from_stereo_float((float *)src,
7284 (const float *)src, frames);
7285 } else if (mSrcChannelMask != mDstChannelMask) {
7286 // convert to mono channel again for channel mask conversion (could be skipped
7287 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007288 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007289 downmix_to_mono_float_from_stereo_float((float *)src,
7290 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007291 }
Andy Hungd330ee42015-04-20 13:23:41 -07007292 // convert to destination format (in place, OK as float is larger than other types)
7293 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7294 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7295 frames * mSrcChannelCount);
7296 }
7297 // channel convert and save to dst
7298 memcpy_by_index_array(dst, mDstChannelCount,
7299 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7300 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007301 }
Andy Hungd330ee42015-04-20 13:23:41 -07007302 // convert to destination format and save to dst
7303 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7304 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007305}
7306
Eric Laurent10351942014-05-08 18:49:52 -07007307bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7308 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007309{
7310 bool reconfig = false;
7311
Eric Laurent10351942014-05-08 18:49:52 -07007312 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007313
Eric Laurent10351942014-05-08 18:49:52 -07007314 audio_format_t reqFormat = mFormat;
7315 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007316 // 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 -07007317 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7318
7319 AudioParameter param = AudioParameter(keyValuePair);
7320 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007321
7322 // scope for AutoPark extends to end of method
7323 AutoPark<FastCapture> park(mFastCapture);
7324
Eric Laurent10351942014-05-08 18:49:52 -07007325 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7326 // channel count change can be requested. Do we mandate the first client defines the
7327 // HAL sampling rate and channel count or do we allow changes on the fly?
7328 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7329 samplingRate = value;
7330 reconfig = true;
7331 }
7332 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007333 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007334 status = BAD_VALUE;
7335 } else {
7336 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007337 reconfig = true;
7338 }
Eric Laurent10351942014-05-08 18:49:52 -07007339 }
7340 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7341 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007342 if (!audio_is_input_channel(mask) ||
7343 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007344 status = BAD_VALUE;
7345 } else {
7346 channelMask = mask;
7347 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007348 }
Eric Laurent10351942014-05-08 18:49:52 -07007349 }
7350 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7351 // do not accept frame count changes if tracks are open as the track buffer
7352 // size depends on frame count and correct behavior would not be guaranteed
7353 // if frame count is changed after track creation
7354 if (mActiveTracks.size() > 0) {
7355 status = INVALID_OPERATION;
7356 } else {
7357 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007358 }
Eric Laurent10351942014-05-08 18:49:52 -07007359 }
7360 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7361 // forward device change to effects that have requested to be
7362 // aware of attached audio device.
7363 for (size_t i = 0; i < mEffectChains.size(); i++) {
7364 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007365 }
Eric Laurent81784c32012-11-19 14:55:58 -08007366
Eric Laurent10351942014-05-08 18:49:52 -07007367 // store input device and output device but do not forward output device to audio HAL.
7368 // Note that status is ignored by the caller for output device
7369 // (see AudioFlinger::setParameters()
7370 if (audio_is_output_devices(value)) {
7371 mOutDevice = value;
7372 status = BAD_VALUE;
7373 } else {
7374 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007375 if (value != AUDIO_DEVICE_NONE) {
7376 mPrevInDevice = value;
7377 }
Eric Laurent10351942014-05-08 18:49:52 -07007378 // disable AEC and NS if the device is a BT SCO headset supporting those
7379 // pre processings
7380 if (mTracks.size() > 0) {
7381 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7382 mAudioFlinger->btNrecIsOff();
7383 for (size_t i = 0; i < mTracks.size(); i++) {
7384 sp<RecordTrack> track = mTracks[i];
7385 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7386 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007387 }
7388 }
7389 }
Eric Laurent10351942014-05-08 18:49:52 -07007390 }
7391 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7392 mAudioSource != (audio_source_t)value) {
7393 // forward device change to effects that have requested to be
7394 // aware of attached audio device.
7395 for (size_t i = 0; i < mEffectChains.size(); i++) {
7396 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007397 }
Eric Laurent10351942014-05-08 18:49:52 -07007398 mAudioSource = (audio_source_t)value;
7399 }
Glenn Kastene198c362013-08-13 09:13:36 -07007400
Eric Laurent10351942014-05-08 18:49:52 -07007401 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007402 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007403 if (status == INVALID_OPERATION) {
7404 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007405 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007406 }
7407 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007408 if (status == BAD_VALUE) {
7409 uint32_t sRate;
7410 audio_channel_mask_t channelMask;
7411 audio_format_t format;
7412 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7413 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7414 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7415 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7416 status = NO_ERROR;
7417 }
Eric Laurent81784c32012-11-19 14:55:58 -08007418 }
Eric Laurent10351942014-05-08 18:49:52 -07007419 if (status == NO_ERROR) {
7420 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007421 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007422 }
7423 }
Eric Laurent81784c32012-11-19 14:55:58 -08007424 }
Eric Laurent10351942014-05-08 18:49:52 -07007425
Eric Laurent81784c32012-11-19 14:55:58 -08007426 return reconfig;
7427}
7428
7429String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7430{
Eric Laurent81784c32012-11-19 14:55:58 -08007431 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007432 if (initCheck() == NO_ERROR) {
7433 String8 out_s8;
7434 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7435 return out_s8;
7436 }
Eric Laurent81784c32012-11-19 14:55:58 -08007437 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007438 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007439}
7440
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007441void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007442 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7443
7444 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007445
7446 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007447 case AUDIO_INPUT_OPENED:
7448 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007449 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007450 desc->mChannelMask = mChannelMask;
7451 desc->mSamplingRate = mSampleRate;
7452 desc->mFormat = mFormat;
7453 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007454 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007455 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007456 break;
7457
Eric Laurent73e26b62015-04-27 16:55:58 -07007458 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007459 default:
7460 break;
7461 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007462 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007463}
7464
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007465void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007466{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007467 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7468 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007469 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007470 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007471 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007472 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7473 result = mInput->stream->getFrameSize(&mFrameSize);
7474 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7475 result = mInput->stream->getBufferSize(&mBufferSize);
7476 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007477 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007478 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007479 // 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 -07007480 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007481 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007482 // A larger value should allow more old data to be read after a track calls start(),
7483 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007484 //
7485 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007486 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007487 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007488 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007489 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007490
7491 // TODO optimize audio capture buffer sizes ...
7492 // Here we calculate the size of the sliding buffer used as a source
7493 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7494 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7495 // be better to have it derived from the pipe depth in the long term.
7496 // The current value is higher than necessary. However it should not add to latency.
7497
Glenn Kasten85948432013-08-19 12:09:05 -07007498 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007499 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7500 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7501 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007502
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007503 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7504 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007505}
7506
Glenn Kasten5f972c02014-01-13 09:59:31 -08007507uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007508{
7509 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007510 uint32_t result;
7511 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7512 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007513 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007514 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007515}
7516
Eric Laurent4c415062016-06-17 16:14:16 -07007517// hasAudioSession_l() must be called with ThreadBase::mLock held
7518uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007519{
Eric Laurent81784c32012-11-19 14:55:58 -08007520 uint32_t result = 0;
7521 if (getEffectChain_l(sessionId) != 0) {
7522 result = EFFECT_SESSION;
7523 }
7524
7525 for (size_t i = 0; i < mTracks.size(); ++i) {
7526 if (sessionId == mTracks[i]->sessionId()) {
7527 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007528 if (mTracks[i]->isFastTrack()) {
7529 result |= FAST_SESSION;
7530 }
Eric Laurent81784c32012-11-19 14:55:58 -08007531 break;
7532 }
7533 }
7534
7535 return result;
7536}
7537
Glenn Kastend848eb42016-03-08 13:42:11 -08007538KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007539{
Glenn Kastend848eb42016-03-08 13:42:11 -08007540 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007541 Mutex::Autolock _l(mLock);
7542 for (size_t j = 0; j < mTracks.size(); ++j) {
7543 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007544 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007545 if (ids.indexOfKey(sessionId) < 0) {
7546 ids.add(sessionId, true);
7547 }
7548 }
7549 return ids;
7550}
7551
7552AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7553{
7554 Mutex::Autolock _l(mLock);
7555 AudioStreamIn *input = mInput;
7556 mInput = NULL;
7557 return input;
7558}
7559
7560// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007561sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007562{
7563 if (mInput == NULL) {
7564 return NULL;
7565 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007566 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007567}
7568
7569status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7570{
7571 // only one chain per input thread
7572 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007573 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007574 return INVALID_OPERATION;
7575 }
7576 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007577 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007578 chain->setInBuffer(NULL);
7579 chain->setOutBuffer(NULL);
7580
7581 checkSuspendOnAddEffectChain_l(chain);
7582
Eric Laurent1b928682014-10-02 19:41:47 -07007583 // make sure enabled pre processing effects state is communicated to the HAL as we
7584 // just moved them to a new input stream.
7585 chain->syncHalEffectsState();
7586
Eric Laurent81784c32012-11-19 14:55:58 -08007587 mEffectChains.add(chain);
7588
7589 return NO_ERROR;
7590}
7591
7592size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7593{
7594 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7595 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007596 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007597 chain.get(), mEffectChains.size(), this);
7598 if (mEffectChains.size() == 1) {
7599 mEffectChains.removeAt(0);
7600 }
7601 return 0;
7602}
7603
Eric Laurent1c333e22014-05-20 10:48:17 -07007604status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7605 audio_patch_handle_t *handle)
7606{
7607 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007608
7609 // store new device and send to effects
7610 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007611 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007612 for (size_t i = 0; i < mEffectChains.size(); i++) {
7613 mEffectChains[i]->setDevice_l(mInDevice);
7614 }
7615
7616 // disable AEC and NS if the device is a BT SCO headset supporting those
7617 // pre processings
7618 if (mTracks.size() > 0) {
7619 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7620 mAudioFlinger->btNrecIsOff();
7621 for (size_t i = 0; i < mTracks.size(); i++) {
7622 sp<RecordTrack> track = mTracks[i];
7623 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7624 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7625 }
7626 }
7627
7628 // store new source and send to effects
7629 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7630 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007631 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007632 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007633 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007634 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007635
Eric Laurent054d9d32015-04-24 08:48:48 -07007636 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007637 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7638 status = hwDevice->createAudioPatch(patch->num_sources,
7639 patch->sources,
7640 patch->num_sinks,
7641 patch->sinks,
7642 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007643 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007644 char *address;
7645 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7646 address = audio_device_address_to_parameter(
7647 patch->sources[0].ext.device.type,
7648 patch->sources[0].ext.device.address);
7649 } else {
7650 address = (char *)calloc(1, 1);
7651 }
7652 AudioParameter param = AudioParameter(String8(address));
7653 free(address);
7654 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7655 (int)patch->sources[0].ext.device.type);
7656 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7657 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007658 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007659 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007660 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007661
Eric Laurente8726fe2015-06-26 09:39:24 -07007662 if (mInDevice != mPrevInDevice) {
7663 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7664 mPrevInDevice = mInDevice;
7665 }
Eric Laurent296fb132015-05-01 11:38:42 -07007666
Eric Laurent1c333e22014-05-20 10:48:17 -07007667 return status;
7668}
7669
7670status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7671{
7672 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007673
7674 mInDevice = AUDIO_DEVICE_NONE;
7675
Eric Laurent1c333e22014-05-20 10:48:17 -07007676 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007677 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7678 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007679 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007680 AudioParameter param;
7681 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007682 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007683 }
7684 return status;
7685}
7686
Eric Laurent83b88082014-06-20 18:31:16 -07007687void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7688{
7689 Mutex::Autolock _l(mLock);
7690 mTracks.add(record);
7691}
7692
7693void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7694{
7695 Mutex::Autolock _l(mLock);
7696 destroyTrack_l(record);
7697}
7698
7699void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7700{
7701 ThreadBase::getAudioPortConfig(config);
7702 config->role = AUDIO_PORT_ROLE_SINK;
7703 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7704 config->ext.mix.usecase.source = mAudioSource;
7705}
Eric Laurent1c333e22014-05-20 10:48:17 -07007706
Glenn Kasten63238ef2015-03-02 15:50:29 -08007707} // namespace android